Search in sources :

Example 1 with BlockStoreException

use of org.bitcoinj.store.BlockStoreException in project bitsquare by bitsquare.

the class SeedNodeMain method doExecute.

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    SeedNode.setEnvironment(environment);
    UserThread.execute(() -> seedNode = new SeedNode());
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }
    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}" + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }
            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory)
                    restart(environment);
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);
    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) DEFAULT_USER_DATA_DIR(io.bitsquare.app.BitsquareEnvironment.DEFAULT_USER_DATA_DIR) Executors(java.util.concurrent.Executors) AppOptionKeys(io.bitsquare.app.AppOptionKeys) OptionException(joptsimple.OptionException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) BitsquareExecutable(io.bitsquare.app.BitsquareExecutable) OptionParser(joptsimple.OptionParser) RestartUtil(io.bitsquare.common.util.RestartUtil) Profiler(io.bitsquare.common.util.Profiler) BlockStoreException(org.bitcoinj.store.BlockStoreException) ThreadFactory(java.util.concurrent.ThreadFactory) OptionSet(joptsimple.OptionSet) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) DEFAULT_APP_NAME(io.bitsquare.app.BitsquareEnvironment.DEFAULT_APP_NAME) BlockStoreException(org.bitcoinj.store.BlockStoreException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) UserThread(io.bitsquare.common.UserThread)

Example 2 with BlockStoreException

use of org.bitcoinj.store.BlockStoreException in project bitsquare by bitsquare.

the class BitsquareApp method start.

@Override
public void start(Stage stage) throws IOException {
    BitsquareApp.primaryStage = stage;
    String logPath = Paths.get(env.getProperty(AppOptionKeys.APP_DATA_DIR_KEY), "bitsquare").toString();
    Log.setup(logPath);
    log.info("Log files under: " + logPath);
    Version.printVersion();
    Utilities.printSysInfo();
    Log.setLevel(Level.toLevel(env.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY)));
    UserThread.setExecutor(Platform::runLater);
    UserThread.setTimerClass(UITimer.class);
    shutDownHandler = this::stop;
    // setup UncaughtExceptionHandler
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        // Might come from another thread 
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else if (throwable instanceof ClassCastException && "sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData".equals(throwable.getMessage())) {
            log.warn(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            UserThread.execute(() -> showErrorPopup(throwable, false));
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    try {
        Utilities.checkCryptoPolicySetup();
    } catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) {
        e.printStackTrace();
        UserThread.execute(() -> showErrorPopup(e, true));
    }
    Security.addProvider(new BouncyCastleProvider());
    try {
        // Guice
        bitsquareAppModule = new BitsquareAppModule(env, primaryStage);
        injector = Guice.createInjector(bitsquareAppModule);
        injector.getInstance(InjectorViewFactory.class).setInjector(injector);
        Version.setBtcNetworkId(injector.getInstance(BitsquareEnvironment.class).getBitcoinNetwork().ordinal());
        if (Utilities.isLinux())
            System.setProperty("prism.lcdtext", "false");
        Storage.setDatabaseCorruptionHandler((String fileName) -> {
            corruptedDatabaseFiles.add(fileName);
            if (mainView != null)
                mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
        });
        // load the main view and create the main scene
        CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class);
        mainView = (MainView) viewLoader.load(MainView.class);
        mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
        /* Storage.setDatabaseCorruptionHandler((String fileName) -> {
                corruptedDatabaseFiles.add(fileName);
                if (mainView != null)
                    mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
            });*/
        //740
        scene = new Scene(mainView.getRoot(), 1200, 700);
        Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13);
        scene.getStylesheets().setAll("/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css", "/io/bitsquare/gui/CandleStickChart.css");
        // configure the system tray
        SystemTray.create(primaryStage, shutDownHandler);
        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            stop();
        });
        scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
            if (new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                stop();
            } else if (new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                stop();
            } else if (new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                showEmptyWalletPopup();
            } else if (new KeyCodeCombination(KeyCode.M, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showSendAlertMessagePopup();
            } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showFilterPopup();
            } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showFPSWindow();
            } else if (new KeyCodeCombination(KeyCode.J, KeyCombination.ALT_DOWN).match(keyEvent)) {
                WalletService walletService = injector.getInstance(WalletService.class);
                if (walletService.getWallet() != null)
                    new ShowWalletDataWindow(walletService).information("Wallet raw data").show();
                else
                    new Popup<>().warning("The wallet is not initialized yet").show();
            } else if (new KeyCodeCombination(KeyCode.G, KeyCombination.ALT_DOWN).match(keyEvent)) {
                TradeWalletService tradeWalletService = injector.getInstance(TradeWalletService.class);
                WalletService walletService = injector.getInstance(WalletService.class);
                if (walletService.getWallet() != null)
                    new SpendFromDepositTxWindow(tradeWalletService).information("Emergency wallet tool").show();
                else
                    new Popup<>().warning("The wallet is not initialized yet").show();
            } else if (DevFlags.DEV_MODE && new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) {
                showDebugWindow();
            }
        });
        // configure the primary stage
        primaryStage.setTitle(env.getRequiredProperty(APP_NAME_KEY));
        primaryStage.setScene(scene);
        // 1190
        primaryStage.setMinWidth(1000);
        primaryStage.setMinHeight(620);
        // on windows the title icon is also used as task bar icon in a larger size
        // on Linux no title icon is supported but also a large task bar icon is derived from that title icon
        String iconPath;
        if (Utilities.isOSX())
            iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png";
        else if (Utilities.isWindows())
            iconPath = "/images/task_bar_icon_windows.png";
        else
            iconPath = "/images/task_bar_icon_linux.png";
        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath)));
        // make the UI visible
        primaryStage.show();
        if (!Utilities.isCorrectOSArchitecture()) {
            String osArchitecture = Utilities.getOSArchitecture();
            // We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
            // Needs at least more testing on different machines...
            new Popup<>().warning("You probably have the wrong Bitsquare version for this computer.\n" + "Your computer's architecture is: " + osArchitecture + ".\n" + "The Bitsquare binary you installed is: " + Utilities.getJVMArchitecture() + ".\n" + "Please shut down and re-install the correct version (" + osArchitecture + ").").show();
        }
        UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN, TimeUnit.MINUTES);
    } catch (Throwable throwable) {
        showErrorPopup(throwable, false);
    }
}
Also used : StageStyle(javafx.stage.StageStyle) Popup(io.bitsquare.gui.main.overlays.popups.Popup) LoggerFactory(org.slf4j.LoggerFactory) Security(java.security.Security) View(io.bitsquare.gui.common.view.View) StackPane(javafx.scene.layout.StackPane) KeyCombination(javafx.scene.input.KeyCombination) Application(javafx.application.Application) Parent(javafx.scene.Parent) UITimer(io.bitsquare.gui.common.UITimer) TradeWalletService(io.bitsquare.btc.TradeWalletService) ResultHandler(io.bitsquare.common.handlers.ResultHandler) BlockStoreException(org.bitcoinj.store.BlockStoreException) Pane(javafx.scene.layout.Pane) Font(javafx.scene.text.Font) LimitedKeyStrengthException(io.bitsquare.common.util.LimitedKeyStrengthException) FilterManager(io.bitsquare.filter.FilterManager) KeyEvent(javafx.scene.input.KeyEvent) InjectorViewFactory(io.bitsquare.gui.common.view.guice.InjectorViewFactory) Platform(javafx.application.Platform) List(java.util.List) io.bitsquare.gui.main.overlays.windows(io.bitsquare.gui.main.overlays.windows) Logger(ch.qos.logback.classic.Logger) MainViewModel(io.bitsquare.gui.main.MainViewModel) Environment(org.springframework.core.env.Environment) Dialogs(org.controlsfx.dialog.Dialogs) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EventStreams(org.reactfx.EventStreams) CommonOptionKeys(io.bitsquare.common.CommonOptionKeys) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) Scene(javafx.scene.Scene) MainView(io.bitsquare.gui.main.MainView) DebugView(io.bitsquare.gui.main.debug.DebugView) P2PService(io.bitsquare.p2p.P2PService) ArrayList(java.util.ArrayList) TradeManager(io.bitsquare.trade.TradeManager) CachingViewLoader(io.bitsquare.gui.common.view.CachingViewLoader) WalletService(io.bitsquare.btc.WalletService) SystemTray(io.bitsquare.gui.SystemTray) APP_NAME_KEY(io.bitsquare.app.AppOptionKeys.APP_NAME_KEY) KeyCode(javafx.scene.input.KeyCode) Modality(javafx.stage.Modality) Utilities(io.bitsquare.common.util.Utilities) Label(javafx.scene.control.Label) UserThread(io.bitsquare.common.UserThread) ImageUtil(io.bitsquare.gui.util.ImageUtil) IOException(java.io.IOException) ViewLoader(io.bitsquare.gui.common.view.ViewLoader) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Injector(com.google.inject.Injector) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) TimeUnit(java.util.concurrent.TimeUnit) Level(ch.qos.logback.classic.Level) Stage(javafx.stage.Stage) Paths(java.nio.file.Paths) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) Guice(com.google.inject.Guice) Profiler(io.bitsquare.common.util.Profiler) Storage(io.bitsquare.storage.Storage) Image(javafx.scene.image.Image) AlertManager(io.bitsquare.alert.AlertManager) Platform(javafx.application.Platform) TradeWalletService(io.bitsquare.btc.TradeWalletService) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Image(javafx.scene.image.Image) TradeWalletService(io.bitsquare.btc.TradeWalletService) WalletService(io.bitsquare.btc.WalletService) CachingViewLoader(io.bitsquare.gui.common.view.CachingViewLoader) LimitedKeyStrengthException(io.bitsquare.common.util.LimitedKeyStrengthException) Popup(io.bitsquare.gui.main.overlays.popups.Popup) InjectorViewFactory(io.bitsquare.gui.common.view.guice.InjectorViewFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BlockStoreException(org.bitcoinj.store.BlockStoreException) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) Scene(javafx.scene.Scene) UserThread(io.bitsquare.common.UserThread)

Example 3 with BlockStoreException

use of org.bitcoinj.store.BlockStoreException in project bitsquare by bitsquare.

the class MainViewModel method initWalletService.

private void initWalletService() {
    Log.traceCall();
    ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>();
    btcInfoBinding = EasyBind.combine(walletService.downloadPercentageProperty(), walletService.numPeersProperty(), walletServiceException, (downloadPercentage, numPeers, exception) -> {
        String result = "";
        if (exception == null) {
            double percentage = (double) downloadPercentage;
            int peers = (int) numPeers;
            String numPeersString = "Bitcoin network peers: " + peers;
            btcSyncProgress.set(percentage);
            if (percentage == 1) {
                result = numPeersString + " / synchronized with " + btcNetworkAsString;
                btcSplashSyncIconId.set("image-connection-synced");
            } else if (percentage > 0.0) {
                result = numPeersString + " / synchronizing with " + btcNetworkAsString + ": " + formatter.formatToPercentWithSymbol(percentage);
            } else {
                result = numPeersString + " / connecting to " + btcNetworkAsString;
            }
        } else {
            result = "Bitcoin network peers: " + numBtcPeers + " / connecting to " + btcNetworkAsString + " failed";
            if (exception instanceof TimeoutException) {
                walletServiceErrorMsg.set("Connecting to the bitcoin network failed because of a timeout.");
            } else if (exception.getCause() instanceof BlockStoreException) {
                log.error(exception.getMessage());
                // Ugly, but no other way to cover that specific case
                if (exception.getMessage().equals("Store file is already locked by another process"))
                    new Popup().warning("Bitsquare is already running. You cannot run two instances of Bitsquare.").closeButtonText("Shut down").onClose(BitsquareApp.shutDownHandler::run).show();
                else
                    new Popup().error("Cannot open wallet because of an exception:\n" + exception.getMessage()).show();
            } else if (exception.getMessage() != null) {
                walletServiceErrorMsg.set("Connection to the bitcoin network failed because of an error:" + exception.getMessage());
            } else {
                walletServiceErrorMsg.set("Connection to the bitcoin network failed because of an error:" + exception.toString());
            }
        }
        return result;
    });
    btcInfoBinding.subscribe((observable, oldValue, newValue) -> {
        btcInfo.set(newValue);
    });
    walletService.initialize(null, () -> {
        numBtcPeers = walletService.numPeersProperty().get();
        if (walletService.getWallet().isEncrypted()) {
            if (p2pNetWorkReady.get())
                splashP2PNetworkAnimationVisible.set(false);
            walletPasswordWindow.onAesKey(aesKey -> {
                walletService.setAesKey(aesKey);
                tradeWalletService.setAesKey(aesKey);
                walletInitialized.set(true);
            }).hideCloseButton().show();
        } else {
            walletInitialized.set(true);
        }
    }, walletServiceException::set);
}
Also used : Clock(io.bitsquare.common.Clock) OpenOffer(io.bitsquare.trade.offer.OpenOffer) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Transaction(org.bitcoinj.core.Transaction) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) ViewModel(io.bitsquare.gui.common.model.ViewModel) LoggerFactory(org.slf4j.LoggerFactory) TradeCurrency(io.bitsquare.locale.TradeCurrency) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) DisputeManager(io.bitsquare.arbitration.DisputeManager) BalanceWithConfirmationTextField(io.bitsquare.gui.components.BalanceWithConfirmationTextField) Trade(io.bitsquare.trade.Trade) GUIUtil(io.bitsquare.gui.util.GUIUtil) DevFlags(io.bitsquare.app.DevFlags) PaymentAccount(io.bitsquare.payment.PaymentAccount) NotificationCenter(io.bitsquare.gui.main.overlays.notifications.NotificationCenter) ListChangeListener(javafx.collections.ListChangeListener) Navigation(io.bitsquare.gui.Navigation) TradeWalletService(io.bitsquare.btc.TradeWalletService) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) AddressEntry(io.bitsquare.btc.AddressEntry) WalletPasswordWindow(io.bitsquare.gui.main.overlays.windows.WalletPasswordWindow) FilterManager(io.bitsquare.filter.FilterManager) Subscription(org.fxmisc.easybind.Subscription) Collectors(java.util.stream.Collectors) PrivateNotificationManager(io.bitsquare.alert.PrivateNotificationManager) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener) Preferences(io.bitsquare.user.Preferences) CryptoCurrencyAccount(io.bitsquare.payment.CryptoCurrencyAccount) Dispute(io.bitsquare.arbitration.Dispute) BalanceTextField(io.bitsquare.gui.components.BalanceTextField) Address(org.bitcoinj.core.Address) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) io.bitsquare.common.crypto(io.bitsquare.common.crypto) PrivateNotification(io.bitsquare.alert.PrivateNotification) Version(io.bitsquare.app.Version) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) java.util(java.util) P2PService(io.bitsquare.p2p.P2PService) SetChangeListener(javafx.collections.SetChangeListener) FXCollections(javafx.collections.FXCollections) BitsquareApp(io.bitsquare.app.BitsquareApp) AddBitcoinNodesWindow(io.bitsquare.gui.main.overlays.windows.AddBitcoinNodesWindow) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) OKPayAccount(io.bitsquare.payment.OKPayAccount) TradeManager(io.bitsquare.trade.TradeManager) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) TacWindow(io.bitsquare.gui.main.overlays.windows.TacWindow) Alert(io.bitsquare.alert.Alert) DisplayAlertMessageWindow(io.bitsquare.gui.main.overlays.windows.DisplayAlertMessageWindow) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) javafx.beans.property(javafx.beans.property) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) TxIdTextField(io.bitsquare.gui.components.TxIdTextField) Wallet(org.bitcoinj.core.Wallet) TimeUnit(java.util.concurrent.TimeUnit) EasyBind(org.fxmisc.easybind.EasyBind) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ChangeListener(javafx.beans.value.ChangeListener) AlertManager(io.bitsquare.alert.AlertManager) BlockStoreException(org.bitcoinj.store.BlockStoreException) Popup(io.bitsquare.gui.main.overlays.popups.Popup) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with BlockStoreException

use of org.bitcoinj.store.BlockStoreException in project bitsquare by bitsquare.

the class StatisticsMain method doExecute.

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    Statistics.setEnvironment(environment);
    UserThread.execute(() -> statistics = new Statistics());
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }
    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}" + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }
            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory) {
                    log.error("\n\n############################################################\n" + "We shut down as we are over our memory limit. usedMemoryInMB: {}" + "\n############################################################\n\n", finalUsedMemoryInMB);
                    System.exit(EXIT_FAILURE);
                }
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);
    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) DEFAULT_USER_DATA_DIR(io.bitsquare.app.BitsquareEnvironment.DEFAULT_USER_DATA_DIR) Executors(java.util.concurrent.Executors) AppOptionKeys(io.bitsquare.app.AppOptionKeys) OptionException(joptsimple.OptionException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) BitsquareExecutable(io.bitsquare.app.BitsquareExecutable) OptionParser(joptsimple.OptionParser) RestartUtil(io.bitsquare.common.util.RestartUtil) Profiler(io.bitsquare.common.util.Profiler) BlockStoreException(org.bitcoinj.store.BlockStoreException) ThreadFactory(java.util.concurrent.ThreadFactory) OptionSet(joptsimple.OptionSet) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) DEFAULT_APP_NAME(io.bitsquare.app.BitsquareEnvironment.DEFAULT_APP_NAME) BlockStoreException(org.bitcoinj.store.BlockStoreException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) UserThread(io.bitsquare.common.UserThread)

Aggregations

UserThread (io.bitsquare.common.UserThread)4 BlockStoreException (org.bitcoinj.store.BlockStoreException)4 LoggerFactory (org.slf4j.LoggerFactory)4 Profiler (io.bitsquare.common.util.Profiler)3 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)2 AlertManager (io.bitsquare.alert.AlertManager)2 AppOptionKeys (io.bitsquare.app.AppOptionKeys)2 BitsquareEnvironment (io.bitsquare.app.BitsquareEnvironment)2 DEFAULT_APP_NAME (io.bitsquare.app.BitsquareEnvironment.DEFAULT_APP_NAME)2 DEFAULT_USER_DATA_DIR (io.bitsquare.app.BitsquareEnvironment.DEFAULT_USER_DATA_DIR)2 BitsquareExecutable (io.bitsquare.app.BitsquareExecutable)2 ArbitratorManager (io.bitsquare.arbitration.ArbitratorManager)2 TradeWalletService (io.bitsquare.btc.TradeWalletService)2 WalletService (io.bitsquare.btc.WalletService)2 RestartUtil (io.bitsquare.common.util.RestartUtil)2 FilterManager (io.bitsquare.filter.FilterManager)2 IOException (java.io.IOException)2 ExceptionUtils (org.apache.commons.lang3.exception.ExceptionUtils)2 Logger (org.slf4j.Logger)2 Level (ch.qos.logback.classic.Level)1