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

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

Introduction

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

Prototype

Throwable failureCause();

Source Link

Document

Returns the Throwable that caused this service to fail.

Usage

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

/**
 * Attaches the given callbacks which will be invoked when the given Service enters a TERMINATED or FAILED state.
 * The callbacks are optional and may be invoked synchronously if the Service is already in one of these states.
 *
 * @param service            The Service to attach to.
 * @param terminatedCallback (Optional) A Runnable that will be invoked if the Service enters a TERMINATED state.
 * @param failureCallback    (Optional) A Runnable that will be invoked if the Service enters a FAILED state.
 * @param executor           An Executor to use for callback invocations.
 *///from w  ww .j  a  v  a2  s .  c  o m
public static void onStop(Service service, Runnable terminatedCallback, Consumer<Throwable> failureCallback,
        Executor executor) {
    ShutdownListener listener = new ShutdownListener(terminatedCallback, failureCallback);
    service.addListener(listener, executor);

    // addListener() will not invoke the callbacks if the service is already in a terminal state. As such, we need to
    // manually check for these states after registering the listener and invoke the appropriate callback. The
    // ShutdownListener will make sure they are not invoked multiple times.
    Service.State state = service.state();
    if (state == Service.State.FAILED) {
        // We don't care (or know) the state from which we came, so we just pass some random one.
        listener.failed(Service.State.FAILED, service.failureCause());
    } else if (state == Service.State.TERMINATED) {
        listener.terminated(Service.State.TERMINATED);
    }
}

From source file:org.apache.onami.lifecycle.guava.GuavaServiceStartModule.java

@Override
protected void configure() {
    bindLifeCycle(Service.class, "startAsync", new InvocationResultHandler() {
        public void afterInvocation(Object obj) throws Throwable {
            Service svc = (Service) obj;

            if (svc.state() == Service.State.FAILED) {
                throw svc.failureCause();
            }//from ww  w.j av  a  2s . co m
        }
    });
}

From source file:dropship.agent.statsd.Snitch.java

@Inject
Snitch(List<SnitchService> snitches) {
    this.snitches = new ServiceManager(snitches);

    this.snitches.addListener(new ServiceManager.Listener() {
        @Override/*w  w  w . j  ava 2s  . c o m*/
        public void healthy() {
        }

        @Override
        public void stopped() {
        }

        @Override
        public void failure(Service service) {
            System.err.format("StatsdAgent service failed: %s, cause: %s", service,
                    Throwables.getStackTraceAsString(service.failureCause()));
        }
    }, MoreExecutors.sameThreadExecutor());
}

From source file:gobblin.scheduler.Worker.java

/**
 * Start this worker./*from   www .j ava  2s.  c om*/
 */
public void start() {
    this.serviceManager.addListener(new ServiceManager.Listener() {

        @Override
        public void stopped() {
            LOG.info("Worker has been stopped");
        }

        @Override
        public void healthy() {
            LOG.info("All services are health and running");
            // Report services' uptimes
            Map<Service, Long> startupTimes = serviceManager.startupTimes();
            for (Map.Entry<Service, Long> entry : startupTimes.entrySet()) {
                LOG.info(String.format("Service %s is healthy with an uptime of %dms",
                        entry.getKey().toString(), entry.getValue()));
            }
        }

        @Override
        public void failure(Service service) {
            LOG.error(String.format("Service %s failed for the following reason:%n\t%s", service.toString(),
                    service.failureCause().toString()));
            System.exit(1);
        }
    }, Executors.newSingleThreadExecutor(ExecutorsUtils.newThreadFactory(Optional.of(LOG))));

    // Add a shutdown hook so the task scheduler gets properly shutdown
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            // Give the services 5 seconds to stop to ensure that we are
            // responsive to shutdown requests
            LOG.info("Shutting down the worker");
            try {
                serviceManager.stopAsync().awaitStopped(5, TimeUnit.SECONDS);
            } catch (TimeoutException te) {
                LOG.error("Timeout in stopping the service manager", te);
            }
        }
    });

    LOG.info("Starting the worker with configured services");
    // Start the worker
    this.serviceManager.startAsync();
}

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

/**
 * Runs Caliper, throwing an exception if the command line, configuration or benchmark class is
 * invalid.//from   w  w w  . j a v a  2s. co  m
 */
@VisibleForTesting
public void runInternal()
        throws InvalidCommandException, InvalidBenchmarkException, InvalidConfigurationException {
    try {
        if (options.get().printConfiguration()) {
            stdout.println("Configuration:");
            ImmutableSortedMap<String, String> sortedProperties = ImmutableSortedMap
                    .copyOf(config.get().properties());
            for (Entry<String, String> entry : sortedProperties.entrySet()) {
                stdout.printf("  %s = %s%n", entry.getKey(), entry.getValue());
            }
        }
        serviceManager.get().addListener(new ServiceManager.Listener() {
            @Override
            public void failure(Service service) {
                stderr.println("Service " + service + " failed with the following exception:");
                service.failureCause().printStackTrace(stderr);
            }
        });
        serviceManager.get().startAsync().awaitHealthy();
        try {
            TargetInfo targetInfo = targetInfoFactory.get().getTargetInfo();
            CaliperRun run = runComponentBuilder.get().targetInfo(targetInfo).build().getCaliperRun();
            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.get().stopAsync().awaitStopped(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                // That's fine
            }
        }
    } finally {
        shutdownAndAwaitTermination(executor, 5, SECONDS);
        // courtesy flush
        stderr.flush();
        stdout.flush();
    }
}

From source file:org.apache.gobblin.runtime.app.ServiceBasedAppLauncher.java

/**
 * Starts the {@link ApplicationLauncher} by starting all associated services. This method also adds a shutdown hook
 * that invokes {@link #stop()} and the {@link #close()} methods. So {@link #stop()} and {@link #close()} need not be
 * called explicitly; they can be triggered during the JVM shutdown.
 *///ww w.j  a  va 2s.  co  m
@Override
public synchronized void start() {
    if (this.hasStarted) {
        LOG.warn("ApplicationLauncher has already started");
        return;
    }
    this.hasStarted = true;

    this.serviceManager = new ServiceManager(this.services);
    // A listener that shutdowns the application if any service fails.
    this.serviceManager.addListener(new ServiceManager.Listener() {
        @Override
        public void failure(Service service) {
            super.failure(service);
            LOG.error(String.format("Service %s has failed.", service.getClass().getSimpleName()),
                    service.failureCause());
            try {
                service.stopAsync();
                ServiceBasedAppLauncher.this.stop();
            } catch (ApplicationException ae) {
                LOG.error("Could not shutdown services gracefully. This may cause the application to hang.");
            }
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                ServiceBasedAppLauncher.this.stop();
            } catch (ApplicationException e) {
                LOG.error("Failed to shutdown application", e);
            } finally {
                try {
                    ServiceBasedAppLauncher.this.close();
                } catch (IOException e) {
                    LOG.error("Failed to close application", e);
                }
            }
        }
    });

    LOG.info("Starting the Gobblin application and all its associated Services");

    // Start the application
    this.serviceManager.startAsync().awaitHealthy();
}

From source file:io.pravega.service.server.containers.StreamSegmentContainer.java

private Throwable getFailureCause(Service... services) {
    Throwable result = null;//w  w  w  .  j a  v a  2s  .  c o  m
    for (Service s : services) {
        if (s.state() == State.FAILED) {
            Throwable realEx = ExceptionHelpers.getRealException(s.failureCause());
            if (result == null) {
                result = realEx;
            } else {
                result.addSuppressed(realEx);
            }
        }
    }

    return result;
}