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.twill.internal.appmaster.RunningContainers.java

/**
 * Stops all running services. Only called when the AppMaster stops.
 *//*from  w  w w  . j a  va 2  s . c om*/
void stopAll() {
    containerLock.lock();
    // Stop the runnables one by one in reverse order of start sequence
    List<String> reverseRunnables = new LinkedList<>();
    try {
        Iterators.addAll(reverseRunnables, startSequence.descendingIterator());
    } finally {
        containerLock.unlock();
    }

    List<ListenableFuture<Service.State>> futures = Lists.newLinkedList();
    for (String runnableName : reverseRunnables) {
        LOG.info("Stopping all instances of " + runnableName);

        futures.clear();
        // Parallel stops all running containers of the current runnable.
        containerLock.lock();
        try {
            for (TwillContainerController controller : containers.row(runnableName).values()) {
                futures.add(controller.stop());
            }
        } finally {
            containerLock.unlock();
        }
        // Wait for containers to stop. Assumes the future returned by Futures.successfulAsList won't throw exception.
        // This will block until handleCompleted() is run for the runnables or a timeout occurs.
        Futures.getUnchecked(Futures.successfulAsList(futures));

        LOG.info("Terminated all instances of " + runnableName);
    }

    // When we acquire this lock, all stopped runnables should have been cleaned up by handleCompleted() method
    containerLock.lock();
    try {
        for (Map.Entry<String, Map<String, TwillContainerController>> entry : containers.rowMap().entrySet()) {
            String runnableName = entry.getKey();
            Collection<ContainerInfo> containerInfos = containerStats.get(runnableName);
            for (Map.Entry<String, TwillContainerController> containerControllerEntry : entry.getValue()
                    .entrySet()) {
                for (ContainerInfo containerInfo : containerInfos) {
                    if (containerInfo.getId().equals(containerControllerEntry.getKey())) {
                        // Only call eventHandler.containerStopped if container is not removed by handleCompleted
                        eventHandler.containerStopped(runnableName,
                                containerControllerEntry.getValue().getInstanceId(),
                                containerControllerEntry.getKey(), ContainerExitCodes.ABORTED);
                        break;
                    }
                }
            }
        }
        containers.clear();
        runnableInstances.clear();
        numRetries.clear();
        containerStats.clear();
    } finally {
        containerLock.unlock();
    }
}

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

public void terminate(String reason, Exception cause, boolean join) {
    if (cause == null) {
        LOG.info("Closing source " + this.peerClusterZnode + " because: " + reason);

    } else {/*from  w  ww. j  a  v  a2s .  c  o  m*/
        LOG.error("Closing source " + this.peerClusterZnode + " because an error occurred: " + reason, cause);
    }
    this.sourceRunning = false;
    Collection<ReplicationSourceWorkerThread> workers = workerThreads.values();
    for (ReplicationSourceWorkerThread worker : workers) {
        worker.setWorkerRunning(false);
        worker.interrupt();
    }
    ListenableFuture<Service.State> future = null;
    if (this.replicationEndpoint != null) {
        future = this.replicationEndpoint.stop();
    }
    if (join) {
        for (ReplicationSourceWorkerThread worker : workers) {
            Threads.shutdown(worker, this.sleepForRetries);
            LOG.info("ReplicationSourceWorker " + worker.getName() + " terminated");
        }
        if (future != null) {
            try {
                future.get();
            } catch (Exception e) {
                LOG.warn("Got exception:" + e);
            }
        }
    }
}

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

private void startJoint(FileInputStream walletStream) throws Exception {
    try {/* ww  w . j a  va  2 s . c  o m*/
        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);
        vFPBStore = new PostgresFullPrunedBlockStore(params, fullStoreDepth, hostname, dbName, username,
                password);
        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);

        vChainFull = new FullPrunedBlockChain(params, vFPBStore);
        vPeerGroupFull = new PeerGroup(params, vChainFull);

        if (this.userAgent != null) {
            vPeerGroup.setUserAgent(userAgent, version);
            vPeerGroupFull.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);
                vPeerGroupFull.addAddress(addr);
            }
            peerAddresses = null;
        } else {
            vPeerGroup.addPeerDiscovery(new DnsDiscovery(params));
            vPeerGroupFull.addPeerDiscovery(new DnsDiscovery(params));
        }
        vChain.addWallet(vWallet);
        vPeerGroup.addWallet(vWallet);

        vChainFull.addWallet(vWallet);
        vPeerGroupFull.addWallet(vWallet);

        onSetupCompleted();

        if (blockingStartup) {
            vPeerGroup.startAndWait();
            vPeerGroupFull.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);
            vPeerGroupFull.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);
                }
            });
            Futures.addCallback(vPeerGroupFull.start(), new FutureCallback<Service.State>() {
                @Override
                public void onSuccess(Service.State result) {
                    final PeerEventListener l = downloadListener == null ? new DownloadListener()
                            : downloadListener;
                    vPeerGroupFull.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();
        }
    }
}

From source file:io.bitsquare.btc.WalletService.java

public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler,
        ExceptionHandler exceptionHandler) {
    Log.traceCall();/*from   ww w  .  j  a va2  s .  co  m*/
    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.

    Threading.USER_THREAD = UserThread.getExecutor();

    Timer timeoutTimer = UserThread.runAfter(
            () -> exceptionHandler.handleException(
                    new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT_SEC + " seconds.")),
            STARTUP_TIMEOUT_SEC);

    backupWallet();

    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy()
            : null;
    log.debug("Use socks5Proxy for bitcoinj: " + socks5Proxy);

    // If seed is non-null it means we are restoring from backup.
    walletAppKit = new WalletAppKitBitSquare(params, socks5Proxy, walletDir, "Bitsquare") {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            walletAppKit.wallet().allowSpendingUnconfirmedTransactions();
            final PeerGroup peerGroup = walletAppKit.peerGroup();

            if (params != RegTestParams.get())
                peerGroup.setMaxConnections(11);

            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);

            wallet = walletAppKit.wallet();
            wallet.addEventListener(walletEventListener);

            addressEntryList.onWalletReady(wallet);

            peerGroup.addEventListener(new PeerEventListener() {
                @Override
                public void onPeersDiscovered(Set<PeerAddress> peerAddresses) {
                }

                @Override
                public void onBlocksDownloaded(Peer peer, Block block, FilteredBlock filteredBlock,
                        int blocksLeft) {
                }

                @Override
                public void onChainDownloadStarted(Peer peer, int blocksLeft) {
                }

                @Override
                public void onPeerConnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public void onPeerDisconnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public Message onPreMessageReceived(Peer peer, Message m) {
                    return null;
                }

                @Override
                public void onTransaction(Peer peer, Transaction t) {
                }

                @Nullable
                @Override
                public List<Message> getData(Peer peer, GetDataMessage m) {
                    return null;
                }
            });

            // set after wallet is ready
            tradeWalletService.setWalletAppKit(walletAppKit);
            tradeWalletService.setAddressEntryList(addressEntryList);
            timeoutTimer.stop();

            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };

    // Bloom filters in BitcoinJ are completely broken
    // See: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/
    // Here are a few improvements to fix a few vulnerabilities.

    // Bitsquare's BitcoinJ fork has added a bloomFilterTweak (nonce) setter to reuse the same seed avoiding the trivial vulnerability
    // by getting the real pub keys by intersections of several filters sent at each startup.
    walletAppKit.setBloomFilterTweak(bloomFilterTweak);

    // Avoid the simple attack (see: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/) due to the 
    // default implementation using both pubkey and hash of pubkey. We have set a insertPubKey flag in BasicKeyChain to default false.

    // Default only 266 keys are generated (2 * 100+33). That would trigger new bloom filters when we are reaching 
    // the threshold. To avoid reaching the threshold we create much more keys which are unlikely to cause update of the
    // filter for most users. With lookaheadSize of 500 we get 1333 keys which should be enough for most users to 
    // never need to update a bloom filter, which would weaken privacy.
    walletAppKit.setLookaheadSize(500);

    // Calculation is derived from: https://www.reddit.com/r/Bitcoin/comments/2vrx6n/privacy_in_bitcoinj_android_wallet_multibit_hive/coknjuz
    // No. of false positives (56M keys in the blockchain): 
    // First attempt for FP rate:
    // FP rate = 0,0001;  No. of false positives: 0,0001 * 56 000 000  = 5600
    // We have 1333keys: 1333 / (5600 + 1333) = 0.19 -> 19 % probability that a pub key is in our wallet
    // After tests I found out that the bandwidth consumption varies widely related to the generated filter.
    // About 20- 40 MB for upload and 30-130 MB for download at first start up (spv chain).
    // Afterwards its about 1 MB for upload and 20-80 MB for download.
    // Probably better then a high FP rate would be to include foreign pubKeyHashes which are tested to not be used 
    // in many transactions. If we had a pool of 100 000 such keys (2 MB data dump) to random select 4000 we could mix it with our
    // 1000 own keys and get a similar probability rate as with the current setup but less variation in bandwidth 
    // consumption.

    // For now to reduce risks with high bandwidth consumption we reduce the FP rate by half.
    // FP rate = 0,00005;  No. of false positives: 0,00005 * 56 000 000  = 2800
    // 1333 / (2800 + 1333) = 0.32 -> 32 % probability that a pub key is in our wallet
    walletAppKit.setBloomFilterFalsePositiveRate(0.00005);

    String btcNodes = preferences.getBitcoinNodes();
    log.debug("btcNodes: " + btcNodes);
    boolean usePeerNodes = false;

    // Pass custom seed nodes if set in options
    if (!btcNodes.isEmpty()) {
        String[] nodes = StringUtils.deleteWhitespace(btcNodes).split(",");
        List<PeerAddress> peerAddressList = new ArrayList<>();
        for (String node : nodes) {
            String[] parts = node.split(":");
            if (parts.length == 1) {
                // port not specified.  Use default port for network.
                parts = new String[] { parts[0], Integer.toString(params.getPort()) };
            }
            if (parts.length == 2) {
                // note: this will cause a DNS request if hostname used.
                // note: DNS requests are routed over socks5 proxy, if used.
                // note: .onion hostnames will be unresolved.
                InetSocketAddress addr;
                if (socks5Proxy != null) {
                    try {
                        // proxy remote DNS request happens here.  blocking.
                        addr = new InetSocketAddress(DnsLookupTor.lookup(socks5Proxy, parts[0]),
                                Integer.parseInt(parts[1]));
                    } catch (Exception e) {
                        log.warn("Dns lookup failed for host: {}", parts[0]);
                        addr = null;
                    }
                } else {
                    // DNS request happens here. if it fails, addr.isUnresolved() == true.
                    addr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1]));
                }
                if (addr != null && !addr.isUnresolved()) {
                    peerAddressList.add(new PeerAddress(addr.getAddress(), addr.getPort()));
                }
            }
        }
        if (peerAddressList.size() > 0) {
            PeerAddress peerAddressListFixed[] = new PeerAddress[peerAddressList.size()];
            log.debug("btcNodes parsed: " + Arrays.toString(peerAddressListFixed));

            walletAppKit.setPeerNodes(peerAddressList.toArray(peerAddressListFixed));
            usePeerNodes = true;
        }
    }

    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            try {
                walletAppKit.setPeerNodes(
                        new PeerAddress(InetAddress.getByName(RegTestHost.SERVER_IP), params.getPort()));
                usePeerNodes = true;
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        } else if (regTestHost == RegTestHost.LOCALHOST) {
            walletAppKit.connectToLocalHost(); // You should run a regtest mode bitcoind locally.}
        }
    } else if (params == MainNetParams.get()) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        try {
            walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    } else if (params == TestNet3Params.get()) {
        walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints.testnet"));
    }

    // If operating over a proxy and we haven't set any peer nodes, then
    // we want to use SeedPeers for discovery instead of the default DnsDiscovery.
    // This is only because we do not yet have a Dns discovery class that works
    // reliably over proxy/tor.
    //
    // todo: There should be a user pref called "Use Local DNS for Proxy/Tor"
    // that disables this.  In that case, the default DnsDiscovery class will
    // be used which should work, but is less private.  The aim here is to
    // be private by default when using proxy/tor.  However, the seedpeers
    // could become outdated, so it is important that the user be able to
    // disable it, but should be made aware of the reduced privacy.
    if (socks5Proxy != null && !usePeerNodes) {
        // SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
        walletAppKit.setDiscovery(new Socks5MultiDiscovery(socks5Proxy, params, socks5DiscoverMode));
    }

    walletAppKit.setDownloadListener(downloadListener).setBlockingStartup(false)
            .setUserAgent(userAgent.getName(), userAgent.getVersion()).restoreWalletFromSeed(seed);

    walletAppKit.addListener(new Service.Listener() {
        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletAppKit = null;
            log.error("walletAppKit failed");
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);
    walletAppKit.startAsync();
}

From source file:org.apache.twill.internal.appmaster.RunningContainers.java

private boolean isControllerStopped(TwillContainerController controller) {
    return controller.state() == Service.State.STOPPING || controller.state() == Service.State.TERMINATED;
}

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

private void startFull(FileInputStream walletStream) throws Exception {
    try {/*from  ww  w  .  ja  va 2 s. co  m*/
        File chainFile = new File(directory, filePrefix + ".blockchain");
        boolean chainFileExists = chainFile.exists();
        vWalletFile = new File(directory, filePrefix + ".wallet");
        boolean shouldReplayWallet = vWalletFile.exists() && !chainFileExists;

        if (!isPostgresBdStore) {
            vFPBStore = new H2FullPrunedBlockStore(params, chainFile.getName(), 100);

        } else {
            if (fullStoreDepth == 0 || hostname == null || dbName == null || username == null
                    || password == null) {
                throw new IllegalArgumentException();
            }
            vFPBStore = new PostgresFullPrunedBlockStore(params, fullStoreDepth, hostname, dbName, username,
                    password);
        }

        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, vFPBStore, time);
        }

        vChain = new FullPrunedBlockChain(params, vFPBStore);

        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();
        }
    }
}

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

public AbstractBlockChain chain() {
    checkState(state() == Service.State.STARTING || state() == Service.State.RUNNING,
            "Cannot call until startup is complete");
    return vChain;
}

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

public AbstractBlockChain chainFull() {
    checkState(state() == Service.State.STARTING || state() == Service.State.RUNNING,
            "Cannot call until startup is complete");
    return vChainFull;
}

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

public SPVBlockStore store() {
    checkState(state() == Service.State.STARTING || state() == Service.State.RUNNING,
            "Cannot call until startup is complete");
    return vStore;
}

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

public FullPrunedBlockStore storeFull() {
    checkState(state() == Service.State.STARTING || state() == Service.State.RUNNING,
            "Cannot call until startup is complete");
    return vFPBStore;
}