Search in sources :

Example 51 with Service

use of com.google.common.util.concurrent.Service in project cdap by caskdata.

the class AuditPublishTest method init.

@BeforeClass
public static void init() throws Exception {
    cConf = CConfiguration.create();
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, TEMP_FOLDER.newFolder().getAbsolutePath());
    Injector injector = AppFabricTestHelper.getInjector(cConf, new AuditModule().getDistributedModules());
    messagingService = injector.getInstance(MessagingService.class);
    if (messagingService instanceof Service) {
        ((Service) messagingService).startAndWait();
    }
    auditTopic = NamespaceId.SYSTEM.topic(cConf.get(Constants.Audit.TOPIC));
}
Also used : Injector(com.google.inject.Injector) MessagingService(co.cask.cdap.messaging.MessagingService) Service(com.google.common.util.concurrent.Service) AuditModule(co.cask.cdap.data2.audit.AuditModule) MessagingService(co.cask.cdap.messaging.MessagingService) BeforeClass(org.junit.BeforeClass)

Example 52 with Service

use of com.google.common.util.concurrent.Service in project spf4j by zolyfarkas.

the class RestartableServiceImpl method startAsync.

@Override
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED")
public final synchronized Service startAsync() {
    final Service svc = guavaService;
    final State state = svc.state();
    switch(state) {
        case NEW:
            svc.startAsync();
            break;
        case FAILED:
            LOG.warn("Restarting a failed service", svc.failureCause());
            restart();
            break;
        case TERMINATED:
            LOG.info("Restarting a terminated service");
            restart();
            break;
        default:
            throw new IllegalStateException("Service is in invalid state " + state);
    }
    return this;
}
Also used : Service(com.google.common.util.concurrent.Service) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 53 with Service

use of com.google.common.util.concurrent.Service in project spf4j by zolyfarkas.

the class RestartableServiceImpl method restart.

@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED")
private void restart() {
    Service newSvc = supplier.get();
    guavaService = newSvc;
    newSvc.startAsync();
}
Also used : Service(com.google.common.util.concurrent.Service) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 54 with Service

use of com.google.common.util.concurrent.Service in project bisq-core by bisq-network.

the class WalletsSetup method initialize.

// /////////////////////////////////////////////////////////////////////////////////////////
// Lifecycle
// /////////////////////////////////////////////////////////////////////////////////////////
public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
    Log.traceCall();
    // 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 + " seconds.")), STARTUP_TIMEOUT);
    backupWallets();
    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy() : null;
    log.info("Socks5Proxy for bitcoinj: socks5Proxy=" + socks5Proxy);
    walletConfig = new WalletConfig(params, socks5Proxy, walletDir, bisqEnvironment, userAgent, numConnectionForBtc, btcWalletFileName, BSQ_WALLET_FILE_NAME, SPV_CHAIN_FILE_NAME) {

        @Override
        protected void onSetupCompleted() {
            // We are here in the btcj thread Thread[ STARTING,5,main]
            super.onSetupCompleted();
            final PeerGroup peerGroup = walletConfig.peerGroup();
            // 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);
            peerGroup.addConnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            // Map to user thread
            UserThread.execute(() -> {
                addressEntryList.onWalletReady(walletConfig.getBtcWallet());
                timeoutTimer.stop();
                setupCompletedHandlers.stream().forEach(Runnable::run);
            });
            // 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);
        }
    };
    if (params == RegTestParams.get()) {
        walletConfig.setMinBroadcastConnections(1);
        if (regTestHost == RegTestHost.LOCALHOST) {
            walletConfig.setPeerNodesForLocalHost();
        } else if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            walletConfig.setMinBroadcastConnections(1);
            configPeerNodesForRegTestServer();
        } else {
            configPeerNodes(socks5Proxy);
        }
    } else if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
        walletConfig.setMinBroadcastConnections(1);
        walletConfig.setPeerNodesForLocalHost();
    } else {
        configPeerNodes(socks5Proxy);
    }
    walletConfig.setDownloadListener(downloadListener).setBlockingStartup(false);
    // If seed is non-null it means we are restoring from backup.
    walletConfig.setSeed(seed);
    walletConfig.addListener(new Service.Listener() {

        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletConfig = null;
            log.error("Service failure from state: {}; failure={}", from, failure);
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);
    walletConfig.startAsync();
}
Also used : RegTestParams(org.bitcoinj.params.RegTestParams) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) RegTestHost(bisq.core.btc.RegTestHost) StringUtils(org.apache.commons.lang3.StringUtils) InetAddress(java.net.InetAddress) NetworkParameters(org.bitcoinj.core.NetworkParameters) AddressEntryList(bisq.core.btc.AddressEntryList) SimpleIntegerProperty(javafx.beans.property.SimpleIntegerProperty) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) Context(org.bitcoinj.core.Context) PeerGroup(org.bitcoinj.core.PeerGroup) BlockChain(org.bitcoinj.core.BlockChain) ReadOnlyDoubleProperty(javafx.beans.property.ReadOnlyDoubleProperty) Set(java.util.Set) DownloadProgressTracker(org.bitcoinj.core.listeners.DownloadProgressTracker) Collectors(java.util.stream.Collectors) ExceptionHandler(bisq.common.handlers.ExceptionHandler) FileUtil(bisq.common.storage.FileUtil) BooleanProperty(javafx.beans.property.BooleanProperty) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) DeterministicSeed(org.bitcoinj.wallet.DeterministicSeed) AddressEntry(bisq.core.btc.AddressEntry) Preferences(bisq.core.user.Preferences) UserThread(bisq.common.UserThread) ReadOnlyIntegerProperty(javafx.beans.property.ReadOnlyIntegerProperty) SimpleDoubleProperty(javafx.beans.property.SimpleDoubleProperty) Address(org.bitcoinj.core.Address) NotNull(org.jetbrains.annotations.NotNull) ReadOnlyObjectProperty(javafx.beans.property.ReadOnlyObjectProperty) Wallet(org.bitcoinj.wallet.Wallet) Timer(bisq.common.Timer) DoubleProperty(javafx.beans.property.DoubleProperty) Peer(org.bitcoinj.core.Peer) IntegerProperty(javafx.beans.property.IntegerProperty) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) Socks5MultiDiscovery(bisq.network.Socks5MultiDiscovery) PeerAddress(org.bitcoinj.core.PeerAddress) Named(javax.inject.Named) Nullable(javax.annotation.Nullable) BitcoinNodes(bisq.core.btc.BitcoinNodes) ObjectProperty(javafx.beans.property.ObjectProperty) BtcNode(bisq.core.btc.BitcoinNodes.BtcNode) Socks5ProxyProvider(bisq.network.Socks5ProxyProvider) ResultHandler(bisq.common.handlers.ResultHandler) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Log(bisq.common.app.Log) IOException(java.io.IOException) BisqEnvironment(bisq.core.app.BisqEnvironment) BtcOptionKeys(bisq.core.btc.BtcOptionKeys) UnknownHostException(java.net.UnknownHostException) File(java.io.File) Threading(org.bitcoinj.utils.Threading) Service(com.google.common.util.concurrent.Service) TimeUnit(java.util.concurrent.TimeUnit) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) Paths(java.nio.file.Paths) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Timer(bisq.common.Timer) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) PeerGroup(org.bitcoinj.core.PeerGroup) Service(com.google.common.util.concurrent.Service) TimeoutException(java.util.concurrent.TimeoutException)

Example 55 with Service

use of com.google.common.util.concurrent.Service in project incubator-gobblin by apache.

the class DefaultBrokerCache method close.

/**
 * Invalidate all objects at scopes which are descendant of the input scope. Any such invalidated object that is a
 * {@link Closeable} will be closed, and any such object which is a {@link Service} will be shutdown.
 * @throws IOException
 */
public void close(ScopeWrapper<S> scope) throws IOException {
    List<Service> awaitShutdown = Lists.newArrayList();
    for (Map.Entry<RawJobBrokerKey, Object> entry : Maps.filterKeys(this.sharedResourceCache.asMap(), new ScopeIsAncestorFilter(scope)).entrySet()) {
        this.sharedResourceCache.invalidate(entry.getKey());
        if (entry.getValue() instanceof ResourceInstance) {
            Object obj = ((ResourceInstance) entry.getValue()).getResource();
            SharedResourcesBrokerUtils.shutdownObject(obj, log);
            if (obj instanceof Service) {
                awaitShutdown.add((Service) obj);
            }
        }
    }
    for (Service service : awaitShutdown) {
        try {
            service.awaitTerminated(10, TimeUnit.SECONDS);
        } catch (TimeoutException te) {
            log.error("Failed to shutdown {}.", service);
        }
    }
}
Also used : Service(com.google.common.util.concurrent.Service) Map(java.util.Map) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Service (com.google.common.util.concurrent.Service)58 MessagingService (co.cask.cdap.messaging.MessagingService)19 MetricsCollectionService (co.cask.cdap.api.metrics.MetricsCollectionService)16 Test (org.junit.Test)16 AbstractIdleService (com.google.common.util.concurrent.AbstractIdleService)15 IOException (java.io.IOException)13 CountDownLatch (java.util.concurrent.CountDownLatch)9 DatasetService (co.cask.cdap.data2.datafabric.dataset.service.DatasetService)8 Injector (com.google.inject.Injector)7 CConfiguration (co.cask.cdap.common.conf.CConfiguration)6 MetricsQueryService (co.cask.cdap.metrics.query.MetricsQueryService)6 ProgramId (co.cask.cdap.proto.id.ProgramId)6 ArrayList (java.util.ArrayList)6 TimeoutException (java.util.concurrent.TimeoutException)5 RunId (com.continuuity.weave.api.RunId)4 ZKClientService (com.continuuity.weave.zookeeper.ZKClientService)4 ExecutionException (java.util.concurrent.ExecutionException)4 Configuration (org.apache.hadoop.conf.Configuration)4 ProgramContextAware (co.cask.cdap.data.ProgramContextAware)3 StreamService (co.cask.cdap.data.stream.service.StreamService)3