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

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

Introduction

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

Prototype

State state();

Source Link

Document

Returns the lifecycle state of the service.

Usage

From source file:org.apache.gobblin.runtime.spec_catalog.TopologyCatalog.java

@Override
public void remove(URI uri, Properties headers) {
    try {//  w  w  w  .j a  v  a 2  s  .  c om
        Preconditions.checkState(state() == Service.State.RUNNING,
                String.format("%s is not running.", this.getClass().getName()));
        Preconditions.checkNotNull(uri);

        log.info(String.format("Removing TopologySpec with URI: %s", uri));
        this.listeners.onDeleteSpec(uri, FlowSpec.Builder.DEFAULT_VERSION, headers);
        specStore.deleteSpec(uri);
    } catch (IOException e) {
        throw new RuntimeException("Cannot delete Spec from Spec store for URI: " + uri, e);
    }
}

From source file:com.griddynamics.jagger.master.Master.java

private void executeTask(Task task, Multimap<NodeType, NodeId> allNodes) throws TerminateException {
    log.debug("Distributing task {}", task);

    @SuppressWarnings("unchecked")
    TaskDistributor<Task> taskDistributor = (TaskDistributor<Task>) distributorRegistry
            .getTaskDistributor(task.getClass());

    Map<NodeId, RemoteExecutor> remotes = Maps.newHashMap();

    log.debug("Distributed task will be executed on {} nodes", remotes.size());

    String taskId = taskIdProvider.getTaskId();

    Service distribute = taskDistributor.distribute(executor, sessionIdProvider.getSessionId(), taskId,
            allNodes, coordinator, task, distributionListener());
    try {//from  w  w w  . ja  v  a 2 s.c  o m
        Future<Service.State> start;
        synchronized (terminateConfigurationLock) {
            distributes.put(distribute, null);
            start = distribute.start();
        }
        Futures.get(start, timeoutConfiguration.getDistributionStartTime());
        Services.awaitTermination(distribute, timeoutConfiguration.getTaskExecutionTime());
    } finally {
        Future<Service.State> stop = distribute.stop();
        Futures.get(stop, timeoutConfiguration.getDistributionStopTime());
    }

}

From source file:io.fluo.cluster.runner.YarnAppRunner.java

public void status(boolean extraInfo) {
    checkIfInitialized();//ww w.  ja  v a 2s  . c  o  m
    if (!twillIdExists()) {
        System.out.print("A Fluo '" + config.getApplicationName() + "' application is not running in YARN.");
        return;
    }
    String twillId = getTwillId();
    TwillController controller = getTwillRunner().lookup(config.getApplicationName(),
            RunIds.fromString(twillId));
    if (controller == null) {
        logExistsButNotRunning();
        System.err
                .println("You can clean up this reference by running 'fluo stop <app>' or 'fluo kill <app>'.");
    } else {
        Service.State state = controller.state();
        System.out.println("A Fluo '" + config.getApplicationName() + "' application is " + state + " in YARN "
                + getFullInfo());

        if (state.equals(Service.State.RUNNING) && !allContainersRunning(controller)) {
            System.out.println(
                    "\nWARNING - The Fluo application is not running all desired containers!  YARN may not have enough available resources.  Application is currently running "
                            + containerStatus(controller));
        }

        if (extraInfo) {
            Collection<TwillRunResources> resources = controller.getResourceReport()
                    .getRunnableResources(FluoOracleMain.ORACLE_NAME);
            System.out.println("\nThe application has " + resources.size() + " of "
                    + config.getOracleInstances() + " desired Oracle containers:\n");
            TwillUtil.printResources(resources);

            resources = controller.getResourceReport().getRunnableResources(FluoWorkerMain.WORKER_NAME);
            System.out.println("\nThe application has " + resources.size() + " of "
                    + config.getWorkerInstances() + " desired Worker containers:\n");
            TwillUtil.printResources(resources);
        }
    }
}

From source file:io.pravega.controller.eventProcessor.impl.EventProcessorCell.java

final void awaitStartupComplete() {
    try {/*from w  w w  .  j  av a  2s  . c  o  m*/
        // Wait for delegate to reach running state.
        delegate.awaitRunning();
    } catch (IllegalStateException e) {
        // If service state is NEW or RUNNING or STARTING, control wouldn't reach this point.
        Service.State state = delegate.state();
        // If service state is Stopping or Terminated, then startup has completed.
        if (state != Service.State.STOPPING && state != Service.State.TERMINATED) {
            // If service state is FAILED, throw error.
            throw e;
        }
    }
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSource.java

private void uninitialize() {
    LOG.debug("Source exiting " + this.peerId);
    metrics.clear();//from w  w  w .ja va 2  s.  co  m
    if (replicationEndpoint.state() == Service.State.STARTING
            || replicationEndpoint.state() == Service.State.RUNNING) {
        replicationEndpoint.stopAndWait();
    }
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSource.java

@Override
public void run() {
    // mark we are running now
    this.sourceRunning = true;
    try {/*from www .j  av a 2 s . c o m*/
        // start the endpoint, connect to the cluster
        Service.State state = replicationEndpoint.start().get();
        if (state != Service.State.RUNNING) {
            LOG.warn("ReplicationEndpoint was not started. Exiting");
            uninitialize();
            return;
        }
    } catch (Exception ex) {
        LOG.warn("Error starting ReplicationEndpoint, exiting", ex);
        throw new RuntimeException(ex);
    }

    // get the WALEntryFilter from ReplicationEndpoint and add it to default filters
    ArrayList<WALEntryFilter> filters = Lists.newArrayList((WALEntryFilter) new SystemTableWALEntryFilter());
    WALEntryFilter filterFromEndpoint = this.replicationEndpoint.getWALEntryfilter();
    if (filterFromEndpoint != null) {
        filters.add(filterFromEndpoint);
    }
    this.walEntryFilter = new ChainWALEntryFilter(filters);

    int sleepMultiplier = 1;
    // delay this until we are in an asynchronous thread
    while (this.isSourceActive() && this.peerClusterId == null) {
        this.peerClusterId = replicationEndpoint.getPeerUUID();
        if (this.isSourceActive() && this.peerClusterId == null) {
            if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) {
                sleepMultiplier++;
            }
        }
    }

    // In rare case, zookeeper setting may be messed up. That leads to the incorrect
    // peerClusterId value, which is the same as the source clusterId
    if (clusterId.equals(peerClusterId) && !replicationEndpoint.canReplicateToSameCluster()) {
        this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId " + peerClusterId
                + " which is not allowed by ReplicationEndpoint:" + replicationEndpoint.getClass().getName(),
                null, false);
    }
    LOG.info("Replicating " + clusterId + " -> " + peerClusterId);
    // start workers
    for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) {
        String walGroupId = entry.getKey();
        PriorityBlockingQueue<Path> queue = entry.getValue();
        final ReplicationSourceWorkerThread worker = new ReplicationSourceWorkerThread(walGroupId, queue,
                replicationQueueInfo, this);
        ReplicationSourceWorkerThread extant = workerThreads.putIfAbsent(walGroupId, worker);
        if (extant != null) {
            LOG.debug("Someone has beat us to start a worker thread for wal group " + walGroupId);
        } else {
            LOG.debug("Starting up worker for wal group " + walGroupId);
            worker.startup();
        }
    }
}

From source file:org.midonet.midolman.Midolman.java

private void doServicesCleanup() {
    log.info("MidoNet Agent shutting down...");

    try {/*from   w  w  w .j a v  a 2 s . c om*/
        minionProcess.stopAsync().awaitTerminated(MINION_PROCESS_WAIT_TIMEOUT, TimeUnit.SECONDS);
    } catch (Exception e) {
        log.error("Minion process failed while stopping.", e);
    }

    if (injector == null)
        return;

    MidolmanService instance = injector.getInstance(MidolmanService.class);

    if (instance.state() == Service.State.TERMINATED)
        return;

    try {
        instance.stopAsync().awaitTerminated();
    } catch (Exception e) {
        log.error("Agent service failed while stopping", e);
    } finally {
        watchedProcess.close();
        log.info("MidoNet Agent exiting. Bye!");
    }
}

From source file:co.cask.cdap.internal.app.runtime.batch.MapReduceProgramRunner.java

/**
 * Creates a service listener to reactor on state changes on {@link MapReduceRuntimeService}.
 *///from ww  w  . ja v a 2s.com
private Service.Listener createRuntimeServiceListener(final Program program, final RunId runId,
        final AdapterDefinition adapterSpec, final PluginInstantiator pluginInstantiator, Arguments arguments) {

    final String twillRunId = arguments.getOption(ProgramOptionConstants.TWILL_RUN_ID);
    final String workflowName = arguments.getOption(ProgramOptionConstants.WORKFLOW_NAME);
    final String workflowNodeId = arguments.getOption(ProgramOptionConstants.WORKFLOW_NODE_ID);
    final String workflowRunId = arguments.getOption(ProgramOptionConstants.WORKFLOW_RUN_ID);

    return new ServiceListenerAdapter() {
        @Override
        public void starting() {
            //Get start time from RunId
            long startTimeInSeconds = RunIds.getTime(runId, TimeUnit.SECONDS);
            if (startTimeInSeconds == -1) {
                // If RunId is not time-based, use current time as start time
                startTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            }
            String adapterName = adapterSpec == null ? null : adapterSpec.getName();
            if (workflowName == null) {
                store.setStart(program.getId(), runId.getId(), startTimeInSeconds, adapterName, twillRunId);
            } else {
                // Program started by Workflow
                store.setWorkflowProgramStart(program.getId(), runId.getId(), workflowName, workflowRunId,
                        workflowNodeId, startTimeInSeconds, adapterName, twillRunId);
            }
        }

        @Override
        public void terminated(Service.State from) {
            if (pluginInstantiator != null) {
                Closeables.closeQuietly(pluginInstantiator);
            }
            if (from == Service.State.STOPPING) {
                // Service was killed
                store.setStop(program.getId(), runId.getId(),
                        TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()),
                        ProgramController.State.KILLED.getRunStatus());
            } else {
                // Service completed by itself.
                store.setStop(program.getId(), runId.getId(),
                        TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()),
                        ProgramController.State.COMPLETED.getRunStatus());
            }
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            if (pluginInstantiator != null) {
                Closeables.closeQuietly(pluginInstantiator);
            }
            store.setStop(program.getId(), runId.getId(),
                    TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()),
                    ProgramController.State.ERROR.getRunStatus());
        }
    };
}

From source file:co.cask.cdap.app.runtime.spark.SparkProgramRunner.java

/**
 * Creates a service listener to reactor on state changes on {@link SparkRuntimeService}.
 *///from   w w  w . ja  v a 2s  .  c o  m
private Service.Listener createRuntimeServiceListener(final Id.Program programId, final RunId runId,
        final Arguments arguments, final Arguments userArgs, final Iterable<Closeable> closeables,
        final Store store) {

    final String twillRunId = arguments.getOption(ProgramOptionConstants.TWILL_RUN_ID);

    return new ServiceListenerAdapter() {
        @Override
        public void starting() {
            //Get start time from RunId
            long startTimeInSeconds = RunIds.getTime(runId, TimeUnit.SECONDS);
            if (startTimeInSeconds == -1) {
                // If RunId is not time-based, use current time as start time
                startTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            }
            store.setStart(programId, runId.getId(), startTimeInSeconds, twillRunId, userArgs.asMap(),
                    arguments.asMap());
        }

        @Override
        public void terminated(Service.State from) {
            closeAll(closeables);
            ProgramRunStatus runStatus = ProgramController.State.COMPLETED.getRunStatus();
            if (from == Service.State.STOPPING) {
                // Service was killed
                runStatus = ProgramController.State.KILLED.getRunStatus();
            }
            store.setStop(programId, runId.getId(), TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()),
                    runStatus);
        }

        @Override
        public void failed(Service.State from, @Nullable Throwable failure) {
            closeAll(closeables);
            store.setStop(programId, runId.getId(), TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()),
                    ProgramController.State.ERROR.getRunStatus(), failure);
        }
    };
}

From source file:com.google.litecoin.kits.NewWalletAppKit.java

private void startSPV(FileInputStream walletStream) throws Exception {
    try {//w  w  w.j  av a  2s.com
        File chainFile = new File(directory, filePrefix + ".spvchain");
        boolean chainFileExists = chainFile.exists();
        vWalletFile = new File(directory, filePrefix + ".wallet");
        boolean shouldReplayWallet = vWalletFile.exists() && !chainFileExists;

        vStore = new SPVBlockStore(params, chainFile);
        if (!chainFileExists && checkpoints != null) {
            // Ugly hack! We have to create the wallet once here to learn the earliest key time, and then throw it
            // away. The reason is that wallet extensions might need access to peergroups/chains/etc so we have to
            // create the wallet later, but we need to know the time early here before we create the BlockChain
            // object.
            long time = Long.MAX_VALUE;
            if (vWalletFile.exists()) {
                Wallet wallet = new Wallet(params);
                FileInputStream stream = new FileInputStream(vWalletFile);
                new WalletProtobufSerializer().readWallet(WalletProtobufSerializer.parseToProto(stream),
                        wallet);
                time = wallet.getEarliestKeyCreationTime();
            }
            CheckpointManager.checkpoint(params, checkpoints, vStore, time);
        }
        vChain = new BlockChain(params, vStore);
        vPeerGroup = new PeerGroup(params, vChain);
        if (this.userAgent != null) {
            vPeerGroup.setUserAgent(userAgent, version);
        }
        if (vWalletFile.exists()) {
            walletStream = new FileInputStream(vWalletFile);
            vWallet = new Wallet(params);
            addWalletExtensions(); // All extensions must be present before we deserialize
            new WalletProtobufSerializer().readWallet(WalletProtobufSerializer.parseToProto(walletStream),
                    vWallet);
            if (shouldReplayWallet) {
                vWallet.clearTransactions(0);
            }
        } else {
            vWallet = new Wallet(params);
            vWallet.addKey(new ECKey());
            addWalletExtensions();
        }
        if (useAutoSave) {
            vWallet.autosaveToFile(vWalletFile, 1, TimeUnit.SECONDS, null);
        }
        // Set up peer addresses or discovery first, so if wallet extensions try to broadcast a transaction
        // before we're actually connected the broadcast waits for an appropriate number of connections.
        if (peerAddresses != null) {
            for (PeerAddress addr : peerAddresses) {
                vPeerGroup.addAddress(addr);
            }
            peerAddresses = null;
        } else {
            vPeerGroup.addPeerDiscovery(new DnsDiscovery(params));
        }
        vChain.addWallet(vWallet);
        vPeerGroup.addWallet(vWallet);
        onSetupCompleted();

        if (blockingStartup) {
            vPeerGroup.startAndWait();
            // Make sure we shut down cleanly.
            installShutdownHook();
            // TODO: Be able to use the provided download listener when doing a blocking startup.
            final DownloadListener listener = new DownloadListener();
            vPeerGroup.startBlockChainDownload(listener);
            listener.await();
        } else {
            Futures.addCallback(vPeerGroup.start(), new FutureCallback<Service.State>() {
                @Override
                public void onSuccess(Service.State result) {
                    final PeerEventListener l = downloadListener == null ? new DownloadListener()
                            : downloadListener;
                    vPeerGroup.startBlockChainDownload(l);
                }

                @Override
                public void onFailure(Throwable t) {
                    throw new RuntimeException(t);
                }
            });
        }
    } catch (BlockStoreException e) {
        throw new IOException(e);
    } finally {
        if (walletStream != null) {
            walletStream.close();
        }
    }
}