diff --git a/src/main/java/ru/kirillius/mktbk/App.java b/src/main/java/ru/kirillius/mktbk/App.java index 15e1d69..f87bd24 100644 --- a/src/main/java/ru/kirillius/mktbk/App.java +++ b/src/main/java/ru/kirillius/mktbk/App.java @@ -25,7 +25,7 @@ public class App { backupFolder = new File(BACKUP_FOLDER); - if(!backupFolder.exists()){ + if (!backupFolder.exists()) { backupFolder.mkdir(); } @@ -102,7 +102,7 @@ public class App { backupName = suggestion; } - var outputFile = new File(backupFolder,backupName + ".tar.gz"); + var outputFile = new File(backupFolder, backupName + ".tar.gz"); List files; @@ -112,7 +112,7 @@ public class App { throw new RuntimeException("Error loading container file tree", e); } - if(console.confirm("Container can be stopped now. Stop it?")) { + if (console.confirm("Container can be stopped now. Stop it?")) { stopContainer(container); } container = validate(container); @@ -130,6 +130,7 @@ public class App { layerFile.delete(); } SystemLogger.message("Backup is done ", LOG_CONTEXT); + console.pause(); if (!container.isRunning() && console.confirm("Do you want to start container?")) { startContainer(container); } @@ -140,7 +141,14 @@ public class App { SystemLogger.message("Stopping container " + container, LOG_CONTEXT); try { device.getApiConnection().execute("/container/stop .id=" + container.getId()); - Thread.sleep(10000L); + waitWhile(() -> { + try { + updateContainers(); + return validate(container).isRunning(); + } catch (MikrotikApiException e) { + throw new RuntimeException(e); + } + }, 10000L); } catch (MikrotikApiException | InterruptedException e) { throw new RuntimeException("Error stopping container", e); } @@ -159,18 +167,35 @@ public class App { } } + + public interface Functor { + T apply(); + } + + @SuppressWarnings("BusyWait") + private void waitWhile(Functor condition, long timeout) throws InterruptedException { + var startTime = System.currentTimeMillis(); + while (condition.apply()) { + if (System.currentTimeMillis() - startTime > timeout) { + throw new InterruptedException(); + } + Thread.sleep(1000); + } + } + private void startContainer(ContainerMetadata container) { try { if (!container.isRunning()) { SystemLogger.message("Starting container " + container, LOG_CONTEXT); device.getApiConnection().execute("/container/start .id=" + container.getId()); - Thread.sleep(10000L); - updateContainers(); - var id = container.getId(); - container = containers.stream().filter(containerMetadata -> containerMetadata.getId().equals(id)).findFirst().orElse(null); - if (container == null || !container.isRunning()) { - throw new RuntimeException("Something went wrong. Unable to start container."); - } + waitWhile(() -> { + try { + updateContainers(); + return !validate(container).isRunning(); + } catch (MikrotikApiException e) { + throw new RuntimeException(e); + } + }, 10000L); } } catch (Exception e) { throw new RuntimeException(e);