From 52ebdee98d46e26ab9b4739326c0dc92764f87fe Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 17:33:15 -0500 Subject: [PATCH 1/3] fix(cli): keep wait's spinner out of -o json, reject bad durations and make --verbose work (#48) * fix(cli): keep wait's spinner out of -o json, reject bad durations and make --verbose work wait draws its spinner only for text output on a terminal and clears it before the result; --timeout values that are not a positive number with ms, s, m or h exit 2 with a hint instead of a stack trace; --verbose now echoes each docker command to stderr and prints stack traces for errors. * fix(cli): reject durations that overflow and pin the spinner rule on a terminal A duration is checked for sign before it is converted and the conversion is overflow-checked, so -9223372036854775807s no longer wraps to a positive timeout. wait takes its terminal check through a seam, with tests for json, yaml and text output on a terminal. --- src/main/java/io/floci/cli/FlociCli.java | 2 +- src/main/java/io/floci/cli/GlobalOptions.java | 7 ++ .../io/floci/cli/commands/WaitCommand.java | 33 +++++++- .../io/floci/cli/docker/DockerClient.java | 5 ++ .../java/io/floci/cli/util/Durations.java | 43 +++++++++-- .../cli/unit/DockerClientProcessTest.java | 25 ++++++ .../java/io/floci/cli/unit/DurationsTest.java | 49 ++++++++++++ .../floci/cli/unit/WaitCommandTimingTest.java | 76 +++++++++++++++++++ 8 files changed, 230 insertions(+), 10 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/DurationsTest.java diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index f870f87..146d811 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -68,7 +68,7 @@ public class FlociCli implements Runnable { @Override public int handleExecutionException(Exception ex, CommandLine cmd, ParseResult parseResult) { System.err.println(Ansi.red("Error: ") + ex.getMessage()); - if (Boolean.getBoolean("floci.verbose")) { + if (Boolean.getBoolean(GlobalOptions.VERBOSE_PROPERTY)) { ex.printStackTrace(System.err); } return 1; diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index 2864e56..2d425f6 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -27,6 +27,9 @@ import java.util.regex.Pattern; */ public class GlobalOptions { + /** System property that {@code --verbose} sets; read where no GlobalOptions is at hand. */ + public static final String VERBOSE_PROPERTY = "floci.verbose"; + // The command this mixin belongs to, so hints can tell which flags were actually typed. // Null for commands built by hand (restart's start), which were never parsed. @Spec(Spec.Target.MIXEE) @@ -122,6 +125,10 @@ public class GlobalOptions { if (noColor || !isStdoutTty()) { Ansi.disable(); } + // Read by the exception handler (stack traces) and DockerClient (the commands it runs). + if (verbose) { + System.setProperty(VERBOSE_PROPERTY, "true"); + } return new Printer(System.out, System.err, output, quiet); } diff --git a/src/main/java/io/floci/cli/commands/WaitCommand.java b/src/main/java/io/floci/cli/commands/WaitCommand.java index 4c4a7e2..e79a373 100644 --- a/src/main/java/io/floci/cli/commands/WaitCommand.java +++ b/src/main/java/io/floci/cli/commands/WaitCommand.java @@ -12,6 +12,7 @@ import io.floci.cli.output.Printer; import java.util.Map; import picocli.CommandLine.*; +import java.io.Console; import java.time.Duration; import java.time.Instant; import java.util.concurrent.Callable; @@ -19,6 +20,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.BooleanSupplier; @Command( name = "wait", @@ -42,12 +44,19 @@ public class WaitCommand implements Callable { /** Test seam: {@code docker} answers the container lookup that finds the endpoint. */ public WaitCommand(ProductProfile profile, DockerClient docker) { + this(profile, docker, WaitCommand::interactive); + } + + /** Test seam: {@code terminal} stands in for "stdout is a terminal", which a test run is not. */ + public WaitCommand(ProductProfile profile, DockerClient docker, BooleanSupplier terminal) { this.profile = profile; this.global = new GlobalOptions(profile); this.docker = docker; + this.terminal = terminal; } private final DockerClient docker; + private final BooleanSupplier terminal; @Option(names = {"--timeout"}, description = "Maximum time to wait (e.g. 30s, 2m)", defaultValue = "30s", paramLabel = "") String timeout; @@ -68,7 +77,16 @@ public class WaitCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - long timeoutMillis = Durations.parseDuration(timeout); + long timeoutMillis; + try { + timeoutMillis = Durations.parseDuration(timeout); + } catch (IllegalArgumentException e) { + printer.error(e.getMessage()); + return 2; + } + // Only a person at a terminal watching text output gets the spinner: in -o json/yaml or + // in a pipe its frames would land in the data. + boolean spinner = printer.format() == OutputFormat.text && terminal.getAsBoolean(); // The deadline starts now, so the container lookup below counts against --timeout too. Instant deadline = Instant.now().plusMillis(timeoutMillis); String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline); @@ -79,6 +97,7 @@ public class WaitCommand implements Callable { long delay = FIRST_DELAY_MS; while (Instant.now().isBefore(deadline)) { if (isReady(client, service, requestTimeout(Duration.between(Instant.now(), deadline)))) { + if (spinner) clearSpinner(printer); if (printer.format() != OutputFormat.text) { printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint)); } else { @@ -86,7 +105,7 @@ public class WaitCommand implements Callable { } return 0; } - printSpinner(printer, deadline); + if (spinner) printSpinner(printer, deadline); long remaining = Duration.between(Instant.now(), deadline).toMillis(); if (remaining <= 0) break; try { Thread.sleep(Math.min(delay, remaining)); } catch (InterruptedException e) { @@ -96,6 +115,7 @@ public class WaitCommand implements Callable { delay = nextDelay(delay); } + if (spinner) clearSpinner(printer); printer.error("Timed out waiting for " + profile.displayName() + " after " + timeout + ".\nIs the container running? Try '" + profile.commandPrefix() + " status'."); return 1; @@ -153,6 +173,15 @@ public class WaitCommand implements Callable { } } + private static boolean interactive() { + Console console = System.console(); + return console != null && console.isTerminal(); + } + + private static void clearSpinner(Printer printer) { + printer.print("\r" + " ".repeat(40) + "\r"); + } + private void printSpinner(Printer printer, Instant deadline) { long remaining = Duration.between(Instant.now(), deadline).toSeconds(); printer.print("\r" + Ansi.gray("Waiting... (" + remaining + "s remaining)") + " "); diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 1197268..1de6dd1 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -1,5 +1,7 @@ package io.floci.cli.docker; +import io.floci.cli.GlobalOptions; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -266,6 +268,9 @@ public class DockerClient { } private Process runProcess(String... cmd) throws IOException { + if (Boolean.getBoolean(GlobalOptions.VERBOSE_PROPERTY)) { + System.err.println("+ " + String.join(" ", cmd)); + } if (cmd.length > 0 && "docker".equals(cmd[0])) { cmd = cmd.clone(); cmd[0] = binary; diff --git a/src/main/java/io/floci/cli/util/Durations.java b/src/main/java/io/floci/cli/util/Durations.java index 3e6e4ed..e48e394 100644 --- a/src/main/java/io/floci/cli/util/Durations.java +++ b/src/main/java/io/floci/cli/util/Durations.java @@ -3,15 +3,44 @@ package io.floci.cli.util; /** Parses human-friendly duration strings like {@code 30s}, {@code 2m}, {@code 500ms}. */ public final class Durations { - /** Returns milliseconds; a bare number is seconds; null/blank defaults to 30s. */ + /** + * Returns milliseconds; a bare number is seconds; null/blank defaults to 30s. + * + * @throws IllegalArgumentException for anything else, or a duration that is not positive, with + * a message suitable for printing to the user + */ public static long parseDuration(String s) { if (s == null || s.isBlank()) return 30_000; - s = s.trim().toLowerCase(); - if (s.endsWith("ms")) return Long.parseLong(s.substring(0, s.length() - 2)); - if (s.endsWith("s")) return Long.parseLong(s.substring(0, s.length() - 1)) * 1000; - if (s.endsWith("m")) return Long.parseLong(s.substring(0, s.length() - 1)) * 60_000; - if (s.endsWith("h")) return Long.parseLong(s.substring(0, s.length() - 1)) * 3_600_000; - return Long.parseLong(s) * 1000; + String value = s.trim().toLowerCase(); + long amount; + long unitMillis; + try { + if (value.endsWith("ms")) { amount = number(value, 2); unitMillis = 1; } + else if (value.endsWith("s")) { amount = number(value, 1); unitMillis = 1000; } + else if (value.endsWith("m")) { amount = number(value, 1); unitMillis = 60_000; } + else if (value.endsWith("h")) { amount = number(value, 1); unitMillis = 3_600_000; } + else { amount = number(value, 0); unitMillis = 1000; } + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Invalid duration '" + s + "'.\n" + + "Use a number with ms, s, m or h, for example 30s or 2m."); + } + // Checked before the conversion: a product that overflows can come back positive. + if (amount <= 0) { + throw new IllegalArgumentException("Duration '" + s + "' must be greater than zero.\n" + + "Use a positive value, for example 30s."); + } + long millis; + try { + millis = Math.multiplyExact(amount, unitMillis); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Duration '" + s + "' is too long.\n" + + "Use a smaller value, for example 30s or 2m."); + } + return millis; + } + + private static long number(String value, int suffixLength) { + return Long.parseLong(value.substring(0, value.length() - suffixLength)); } private Durations() {} diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index a90f15f..f753457 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -1,5 +1,6 @@ package io.floci.cli.unit; +import io.floci.cli.GlobalOptions; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; import org.junit.jupiter.api.Test; @@ -9,6 +10,8 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; @@ -203,4 +206,26 @@ class DockerClientProcessTest { assertEquals(List.of("rm", "--", "--rm-everything"), args); } + + /** BL-041: with --verbose set, each docker command is echoed to stderr before it runs. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void verboseEchoesTheDockerCommand() throws Exception { + Path fakeDocker = tempDir.resolve("docker"); + Files.writeString(fakeDocker, "#!/bin/sh\nexit 0\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + System.setProperty(GlobalOptions.VERBOSE_PROPERTY, "true"); + try { + new DockerClient(fakeDocker.toString()).removeContainer("floci-x"); + } finally { + System.clearProperty(GlobalOptions.VERBOSE_PROPERTY); + System.setErr(err); + } + + assertTrue(errBuf.toString().contains("+ docker rm"), errBuf.toString()); + assertTrue(errBuf.toString().contains("floci-x"), errBuf.toString()); + } } diff --git a/src/test/java/io/floci/cli/unit/DurationsTest.java b/src/test/java/io/floci/cli/unit/DurationsTest.java new file mode 100644 index 0000000..06c4f73 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/DurationsTest.java @@ -0,0 +1,49 @@ +package io.floci.cli.unit; + +import io.floci.cli.util.Durations; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-040: durations parse the documented forms and reject everything else with a usable message. */ +class DurationsTest { + + @Test + void parsesEveryDocumentedUnit() { + assertEquals(500, Durations.parseDuration("500ms")); + assertEquals(90_000, Durations.parseDuration("90s")); + assertEquals(120_000, Durations.parseDuration("2m")); + assertEquals(3_600_000, Durations.parseDuration("1h")); + assertEquals(45_000, Durations.parseDuration("45")); + assertEquals(30_000, Durations.parseDuration(null)); + } + + @ParameterizedTest + @ValueSource(strings = {"abc", "10x", "s", "1.5s"}) + void rejectsWhatItCannotRead(String value) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Durations.parseDuration(value)); + assertTrue(e.getMessage().contains("Invalid duration"), e.getMessage()); + } + + @ParameterizedTest + // The last one overflows to +1000 ms when multiplied before the check. + @ValueSource(strings = {"0s", "0", "-1s", "-5", "-9223372036854775807s"}) + void rejectsDurationsThatAreNotPositive(String value) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Durations.parseDuration(value)); + assertTrue(e.getMessage().contains("greater than zero"), e.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {"9223372036854775807s", "9223372036854775807", "9223372036854775m", "2562047788016h"}) + void rejectsDurationsTooLongToRepresent(String value) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Durations.parseDuration(value)); + assertTrue(e.getMessage().contains("too long"), e.getMessage()); + } + + @Test + void theLargestMillisecondValueStillParses() { + assertEquals(Long.MAX_VALUE, Durations.parseDuration("9223372036854775807ms")); + } +} diff --git a/src/test/java/io/floci/cli/unit/WaitCommandTimingTest.java b/src/test/java/io/floci/cli/unit/WaitCommandTimingTest.java index b155122..5a82fa5 100644 --- a/src/test/java/io/floci/cli/unit/WaitCommandTimingTest.java +++ b/src/test/java/io/floci/cli/unit/WaitCommandTimingTest.java @@ -8,11 +8,15 @@ import io.floci.cli.config.ProfileStore; import io.floci.cli.docker.DockerClient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import picocli.CommandLine; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.nio.file.Path; import java.time.Duration; import java.util.Optional; @@ -149,4 +153,76 @@ class WaitCommandTimingTest { server.stop(0); } } + + private record Out(int exit, String out, String err) {} + + private static Out waitWith(String... args) { + return waitWith(false, args); + } + + private static Out waitWith(boolean terminal, String... args) { + DockerClient noContainer = new DockerClient() { + @Override + public Optional inspectContainer(String name) { + return Optional.empty(); + } + }; + PrintStream err = System.err; + PrintStream out = System.out; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, noContainer, () -> terminal)).execute(args); + return new Out(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setErr(err); + System.setOut(out); + } + } + + /** BL-039: on a terminal, -o json and -o yaml still carry no spinner frames while polling. */ + @ParameterizedTest + @ValueSource(strings = {"json", "yaml"}) + void structuredOutputHasNoSpinnerEvenOnATerminal(String format) throws Exception { + Out r = waitWith(true, "--timeout", "300ms", "--endpoint", closedEndpoint(), "-o", format); + + assertEquals(1, r.exit()); + assertFalse(r.out().contains("Waiting"), r.out()); + assertFalse(r.out().contains("\r"), r.out()); + } + + /** The other half: text output on a terminal does draw it, so the test above can fail. */ + @Test + void textOutputOnATerminalShowsTheSpinner() throws Exception { + Out r = waitWith(true, "--timeout", "300ms", "--endpoint", closedEndpoint()); + + assertEquals(1, r.exit()); + assertTrue(r.out().contains("Waiting"), r.out()); + } + + @Test + void textOutputInAPipeHasNoSpinner() throws Exception { + Out r = waitWith(false, "--timeout", "300ms", "--endpoint", closedEndpoint()); + + assertEquals(1, r.exit()); + assertFalse(r.out().contains("Waiting"), r.out()); + } + + // A port that was just bound and released: nothing is listening, so polls are refused at once. + private static String closedEndpoint() throws Exception { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + return "http://127.0.0.1:" + socket.getLocalPort(); + } + } + + /** BL-040: a bad --timeout is a usage error with a hint, not a stack trace. */ + @Test + void anUnreadableTimeoutExitsTwo() { + Out r = waitWith("--timeout", "abc", "--endpoint", "http://127.0.0.1:9"); + + assertEquals(2, r.exit()); + assertTrue(r.err().contains("Invalid duration 'abc'"), r.err()); + } } From f6cec794d71973efebc7991dabe99c723e1541cd Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 17:38:28 -0500 Subject: [PATCH 2/3] fix(restart): keep the instance's port, image, data directory and services (#49) * fix(restart): keep the instance's port, image, data directory and services Without a profile, restart reads the running container's settings (host port, image, the directory mounted at /app/data, its services and resource namespace) before stopping it and starts it with them, instead of falling back to the defaults and moving the instance to the default port without its state. A profile still decides when one is given, and restart now starts the container when none exists instead of failing. A container started without --persist has Docker's anonymous volume at /app/data; restart took that volume's internal path for a persist directory and failed to start again. Only a bind mount is a persist directory now. * fix(restart): stop before the stop when the running container's settings cannot be read A failed or timed-out inspect is no longer treated as a missing container, which removed the instance and started it on the defaults. Adds tests through call() for the missing-container, existing-container and unreadable-settings paths. --- .../io/floci/cli/commands/RestartCommand.java | 54 +++++- .../io/floci/cli/docker/DockerClient.java | 60 ++++++ .../cli/unit/DockerClientProcessTest.java | 43 +++++ .../io/floci/cli/unit/RestartCommandTest.java | 176 +++++++++++++++++- 4 files changed, 328 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 484eb61..ff75cef 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -2,8 +2,10 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; -import io.floci.cli.config.ProfileNotFoundException; import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileNotFoundException; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; import io.floci.cli.output.Printer; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -30,10 +32,18 @@ public class RestartCommand implements Callable { } protected RestartCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers the inspect that recovers the running instance's settings. */ + public RestartCommand(ProductProfile profile, DockerClient docker) { this.profile = profile; this.global = new GlobalOptions(profile); + this.docker = docker; } + private final DockerClient docker; + @Override public Integer call() { Printer printer = global.printer(); @@ -49,6 +59,14 @@ public class RestartCommand implements Callable { // exit code matches a bad --profile at parse time. printer.error(e.getMessage()); return ExitCode.USAGE; + } catch (DockerException e) { + // The container may well be there with settings this restart could not read. Going + // on would remove it and bring it back on the defaults, so stop here instead. + printer.error("Could not read how container '" + global.container + "' was started, so it was left as it is: " + + e.getMessage() + + "\nCheck that Docker is responsive ('docker info'), then re-run '" + + profile.commandPrefix() + " restart" + global.instanceSelector() + "'."); + return 1; } String invalid = start.validationError(); if (invalid != null) { @@ -56,6 +74,12 @@ public class RestartCommand implements Callable { return 2; } + if (!containerExists()) { + // Nothing to stop: start it, rather than failing on the stop. + printer.println("Container '" + global.container + "' not found; starting it."); + return start.call(); + } + int stopResult = buildStopCommand().call(); if (stopResult != 0) return stopResult; @@ -83,7 +107,7 @@ public class RestartCommand implements Callable { * provider, the same precedence and the same interpolation, so one profile cannot mean one * directory on {@code start} and a different one on {@code restart}. */ - public StartCommand buildStartCommand() { + public StartCommand buildStartCommand() throws DockerException { // The outer parse's provider: its memoized profile is the snapshot the globals below were // resolved from, so the start settings cannot come from a newer version of the file. StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile); @@ -93,6 +117,32 @@ public class RestartCommand implements Callable { start.global = global; start.pull = "missing"; start.detach = false; + if (global.profile == null) carryOver(start); return start; } + + // Without a profile, the running container is the only record of how it was started: its + // port, image, data directory and services come back from it, or a restart would quietly + // move the instance to the default port and drop its state. Read before the stop, which + // removes the container. Only a container that does not exist (an empty result) means + // "start with the defaults"; a failed read is thrown, so the caller can stop before the stop. + private void carryOver(StartCommand start) throws DockerException { + docker.inspectRunSettings(global.container, profile.defaultPort()).ifPresent(run -> { + if (run.hostPort() != null) start.port = run.hostPort(); + if (run.image() != null) start.image = run.image(); + if (run.persistSource() != null) start.persistDir = run.persistSource(); + String services = run.env().get(profile.envVar("SERVICES")); + if (services != null) start.services = services; + String namespace = run.env().get(profile.envVar("DOCKER_RESOURCE_NAMESPACE")); + if (namespace != null) start.namespace = namespace; + }); + } + + private boolean containerExists() { + try { + return docker.inspectContainer(global.container).isPresent(); + } catch (DockerException e) { + return true; // let stop report the docker problem + } + } } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 1de6dd1..337a596 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -1,5 +1,7 @@ package io.floci.cli.docker; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.cli.GlobalOptions; import java.io.BufferedReader; @@ -9,7 +11,9 @@ import java.io.InputStreamReader; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -50,6 +54,62 @@ public class DockerClient { public record ImageInfo(String id, String repository, String tag, String digest) {} + /** + * What a container was started with, as {@code restart} needs it back: the image, the host + * port bound to {@code containerPort}, the host directory bind-mounted at {@code /app/data} + * (null for a docker volume), and the environment. Any of them may be absent (null, or an empty map). + */ + public record RunSettings(String image, Integer hostPort, String persistSource, Map env) {} + + private static final ObjectMapper JSON = new ObjectMapper(); + + public Optional inspectRunSettings(String name, int containerPort) throws DockerException { + String out; + try { + out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name); + } catch (DockerException e) { + if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) { + return Optional.empty(); + } + throw e; + } + if (out.isBlank()) return Optional.empty(); + try { + JsonNode c = JSON.readTree(out); + String image = textOrNull(c.path("Config").path("Image")); + Integer hostPort = null; + JsonNode binding = c.path("HostConfig").path("PortBindings").path(containerPort + "/tcp"); + if (binding.isArray() && !binding.isEmpty()) { + String text = binding.get(0).path("HostPort").asText(""); + if (!text.isBlank()) hostPort = Integer.valueOf(text); + } + String persist = null; + for (JsonNode mount : c.path("Mounts")) { + // Only a host directory is a --persist. The images declare /app/data as a volume, + // so without --persist docker mounts an anonymous volume there; its Source is a + // path inside the docker VM, not something start can mount again. + if ("/app/data".equals(mount.path("Destination").asText()) + && "bind".equals(mount.path("Type").asText())) { + persist = textOrNull(mount.path("Source")); + } + } + Map env = new LinkedHashMap<>(); + for (JsonNode entry : c.path("Config").path("Env")) { + String kv = entry.asText(); + int eq = kv.indexOf('='); + if (eq > 0) env.put(kv.substring(0, eq), kv.substring(eq + 1)); + } + return Optional.of(new RunSettings(image, hostPort, persist, Map.copyOf(env))); + } catch (Exception e) { + throw new DockerException("Could not read the settings of container '" + name + "': " + e.getMessage()); + } + } + + private static String textOrNull(JsonNode node) { + String text = node.asText(""); + return text.isBlank() ? null : text; + } + public String dockerVersion() throws DockerException { return run("docker", "version", "--format", "{{.Server.Version}}").trim(); } diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index f753457..fb5d9a9 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -207,6 +207,49 @@ class DockerClientProcessTest { assertEquals(List.of("rm", "--", "--rm-everything"), args); } + /** BL-033: restart reads the image, host port, data mount and environment back from inspect. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void runSettingsAreReadFromTheContainersInspectDocument() throws Exception { + Path json = tempDir.resolve("inspect.json"); + Files.writeString(json, """ + {"Config":{"Image":"floci/floci-gcp:0.9","Env":["FLOCI_GCP_SERVICES=storage","PATH=/usr/bin"]}, + "HostConfig":{"PortBindings":{"4588/tcp":[{"HostIp":"","HostPort":"14588"}]}}, + "Mounts":[{"Type":"bind","Source":"/data/gcp","Destination":"/app/data"}]} + """); + Path fakeDocker = tempDir.resolve("docker"); + Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + + DockerClient.RunSettings run = new DockerClient(fakeDocker.toString()) + .inspectRunSettings("floci-gcp", 4588).orElseThrow(); + + assertEquals("floci/floci-gcp:0.9", run.image()); + assertEquals(14588, run.hostPort()); + assertEquals("/data/gcp", run.persistSource()); + assertEquals("storage", run.env().get("FLOCI_GCP_SERVICES")); + } + + /** Without --persist the image's /app/data volume is mounted; that is not a persist directory. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anAnonymousDataVolumeIsNotAPersistDirectory() throws Exception { + Path json = tempDir.resolve("inspect.json"); + Files.writeString(json, """ + {"Config":{"Image":"floci/floci-oci:latest","Env":[]}, + "HostConfig":{"PortBindings":{"4599/tcp":[{"HostIp":"","HostPort":"4599"}]}}, + "Mounts":[{"Type":"volume","Name":"3c3aef44","Source":"/var/lib/docker/volumes/3c3aef44/_data","Destination":"/app/data"}]} + """); + Path fakeDocker = tempDir.resolve("docker"); + Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + + DockerClient.RunSettings run = new DockerClient(fakeDocker.toString()) + .inspectRunSettings("floci-oci", 4599).orElseThrow(); + + assertNull(run.persistSource()); + } + /** BL-041: with --verbose set, each docker command is echoed to stderr before it runs. */ @Test @DisabledOnOs(OS.WINDOWS) diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index 5c2d6b5..ee85a95 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -3,7 +3,12 @@ package io.floci.cli.unit; import io.floci.cli.FlociCli; import io.floci.cli.ProductProfile; import io.floci.cli.commands.RestartCommand; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.commands.StopCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine; @@ -16,6 +21,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @@ -32,6 +39,21 @@ class RestartCommandTest { Path tempDir; // Through the real wiring, so restart sees the provider the parse used. + /** A restart whose docker lookups answer from {@code settings} (none: no such container). */ + private RestartCommand restartWith(ProductProfile product, DockerClient.RunSettings settings, String... args) { + DockerClient docker = new DockerClient() { + @Override + public Optional inspectRunSettings(String name, int containerPort) { + return Optional.ofNullable(settings); + } + }; + RestartCommand restart = new RestartCommand(product, docker); + new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .parseArgs(args); + return restart; + } + private RestartCommand parse(ProductProfile product, String... args) { List all = new ArrayList<>(); if (product != ProductProfile.AWS) all.add(product.name()); @@ -98,8 +120,8 @@ class RestartCommandTest { } @Test - void withoutAProfileItStillUsesTheProductDefaults() { - List args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET); + void withoutAProfileItStillUsesTheProductDefaults() throws Exception { + List args = restartWith(ProductProfile.GCP, null).buildStartCommand().dockerRunArgs(SOCKET); assertEquals(List.of("-d", "--name", "floci-gcp", "-p", "4588:4588", "-v", "/sock:/sock", "floci/floci-gcp:latest"), args); @@ -153,9 +175,157 @@ class RestartCommandTest { /** BL-029: the stop removes the container, so start needs no pause and no second removal. */ @Test - void theStopItRunsRemovesTheContainer() { + void theStopItRunsRemovesTheContainer() throws Exception { var stop = parse(ProductProfile.AWS).buildStopCommand(); assertEquals(Boolean.TRUE, new CommandLine(stop).getCommandSpec().findOption("--remove").getValue()); } + + /** BL-033: without a profile, the running container is the record of how it was started. */ + @Test + void withoutAProfileTheRunningContainersSettingsCarryOver() throws Exception { + var running = new DockerClient.RunSettings("floci/floci-gcp:0.9", 14588, "/data/gcp", + Map.of("FLOCI_GCP_SERVICES", "storage", "FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE", "team")); + + List args = restartWith(ProductProfile.GCP, running).buildStartCommand().dockerRunArgs(SOCKET); + + assertTrue(args.contains("14588:4588"), args.toString()); + assertTrue(args.contains("/data/gcp:/app/data"), args.toString()); + assertTrue(args.contains("FLOCI_GCP_SERVICES=storage"), args.toString()); + assertTrue(args.contains("FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE=team"), args.toString()); + assertEquals("floci/floci-gcp:0.9", args.get(args.size() - 1)); + } + + /** A profile still decides: carry-over only fills in for a restart without one. */ + @Test + void aProfileWinsOverTheRunningContainersSettings() throws Exception { + writeProfile("pinned", "port: 15000\n"); + var running = new DockerClient.RunSettings("floci/floci:0.9", 14566, "/data/x", Map.of()); + + List args = restartWith(ProductProfile.AWS, running, "--profile", "pinned") + .buildStartCommand().dockerRunArgs(SOCKET); + + assertTrue(args.contains("15000:4566"), args.toString()); + assertFalse(args.contains("/data/x:/app/data"), args.toString()); + } + + /** What a restart did, in order: "stop" and "start" as it ran them. */ + private RestartCommand recordingRestart(DockerClient docker, List ran) { + RestartCommand restart = new RestartCommand(ProductProfile.AWS, docker) { + @Override + public StartCommand buildStartCommand() throws DockerException { + super.buildStartCommand(); // the real one first, so its docker failure still surfaces + return new StartCommand(ProductProfile.AWS) { + @Override + public Integer call() { + ran.add("start"); + return 0; + } + }; + } + + @Override + public StopCommand buildStopCommand() { + return new StopCommand(ProductProfile.AWS) { + @Override + public Integer call() { + ran.add("stop"); + return 0; + } + }; + } + }; + new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .parseArgs(); + return restart; + } + + private record Ran(int exit, String out, String err) {} + + private static Ran run(RestartCommand restart) { + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + return new Ran(restart.call(), outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + /** BL-033: with no container there is nothing to stop, so restart only starts. */ + @Test + void aMissingContainerIsStartedWithoutAStop() { + DockerClient absent = new DockerClient() { + @Override + public Optional inspectRunSettings(String name, int containerPort) { + return Optional.empty(); + } + + @Override + public Optional inspectContainer(String name) { + return Optional.empty(); + } + }; + List ran = new ArrayList<>(); + + Ran r = run(recordingRestart(absent, ran)); + + assertEquals(0, r.exit()); + assertEquals(List.of("start"), ran); + assertTrue(r.out().contains("not found; starting it"), r.out()); + } + + @Test + void anExistingContainerIsStoppedThenStarted() { + DockerClient present = new DockerClient() { + @Override + public Optional inspectRunSettings(String name, int containerPort) { + return Optional.of(new RunSettings("floci/floci:0.9", 14566, null, Map.of())); + } + + @Override + public Optional inspectContainer(String name) { + return Optional.of(new ContainerInfo("abc", name, "floci/floci:0.9", "running", "")); + } + }; + List ran = new ArrayList<>(); + + Ran r = run(recordingRestart(present, ran)); + + assertEquals(0, r.exit()); + assertEquals(List.of("stop", "start"), ran); + } + + /** + * A failed read of the running container's settings is not "no container": restart must stop + * there, or it would remove the instance and bring it back on the default port without its data. + */ + @Test + void settingsThatCannotBeReadFailTheRestartBeforeTheStop() { + DockerClient stalled = new DockerClient() { + @Override + public Optional inspectRunSettings(String name, int containerPort) throws DockerException { + throw new DockerException("'docker container inspect' did not finish within 30s."); + } + + @Override + public Optional inspectContainer(String name) { + return Optional.of(new ContainerInfo("abc", name, "floci/floci:0.9", "running", "")); + } + }; + List ran = new ArrayList<>(); + + Ran r = run(recordingRestart(stalled, ran)); + + assertEquals(1, r.exit()); + assertEquals(List.of(), ran); + assertTrue(r.err().contains("did not finish within 30s"), r.err()); + assertTrue(r.err().contains("floci restart"), r.err()); + } } From 3ca4108498a04b1b52766a42ceea78d259373c21 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 17:55:29 -0500 Subject: [PATCH 3/3] fix(start): mount a relative --persist path as a directory and validate --port and --pull (#50) * fix(start): mount a relative --persist path as a directory and validate --port and --pull --persist ./data is resolved to an absolute path and created before docker run, so state lands in that directory instead of a Docker named volume; --port outside 1-65535 and an unknown --pull policy are rejected with exit 2 (restart checks them before stopping anything). start creates the persist directory itself (preparePersistDir). restart now does that before it stops anything, so an unwritable directory fails the restart with the instance still running, instead of after the container was already removed. * fix(start): leave a remote daemon's persist directory alone and accept pull policies in any locale The persist directory is created only for a local daemon, an invalid path is reported instead of thrown while building the message, and pull policies are lowercased with Locale.ROOT. The permission test is skipped when permissions do not bind the user. * fix(start): check the persist path for a remote daemon before restart stops anything A remote daemon skips only the local directory creation. The path itself is resolved for every daemon, so an unusable one is reported before the stop instead of thrown while building the run arguments afterwards. * test(restart): let the recorded start answer restart's pre-stop checks The recording start used by the call-path tests was never parsed, so the new --pull validation rejected it. It now delegates the checks to the start restart really built. * fix(start): pass a remote daemon's persist path on unchanged A remote daemon's bind source is no longer resolved by the CLI machine's path rules, which turned /srv/data into a drive path on a Windows CLI. Only a local daemon has relative paths resolved. * fix(start): refuse a relative --persist path for a remote daemon A remote daemon cannot resolve a path relative to the CLI's working directory, and docker reads a bare name as a named volume, so the state would land somewhere a later restart does not carry over. * refactor(start): keep bindSource's javadoc on the method --- .../io/floci/cli/commands/RestartCommand.java | 5 + .../io/floci/cli/commands/StartCommand.java | 100 +++++++++++- .../io/floci/cli/unit/RestartCommandTest.java | 48 +++++- .../floci/cli/unit/StartCommandArgsTest.java | 152 ++++++++++++++++++ 4 files changed, 302 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index ff75cef..85b2e11 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -73,6 +73,11 @@ public class RestartCommand implements Callable { printer.error(invalid); return 2; } + String unwritable = start.preparePersistDir(); + if (unwritable != null) { + printer.error(unwritable); + return 1; + } if (!containerExists()) { // Nothing to stop: start it, rather than failing on the stop. diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 3f63e08..aaceb30 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -11,8 +11,12 @@ import picocli.CommandLine; import picocli.CommandLine.*; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.regex.Pattern; @@ -114,9 +118,87 @@ public class StartCommand implements Callable { if (namespace != null && !namespace.isBlank() && !NAMESPACE.matcher(namespace).matches()) { return "Invalid namespace '" + namespace + "'.\nUse letters, digits, '_', '.' and '-', starting with a letter or digit."; } + if (port < 1 || port > 65535) { + return "--port must be between 1 and 65535, but was " + port + ".\nPick a free port, for example " + + (profile.defaultPort() + 10000) + "."; + } + if (pull == null || !PULL_POLICIES.contains(pull.toLowerCase(Locale.ROOT))) { + // Anything else used to fall through to a pull, so a typo silently meant "always". + return "Invalid --pull '" + pull + "'.\nUse always, missing or never."; + } return null; } + private static final List PULL_POLICIES = List.of("always", "missing", "never"); + + /** + * {@code persistDir} as an absolute, normalized path. Docker reads a bind source without a + * leading slash as a named volume, so {@code --persist ./data} would otherwise keep the state + * in an anonymous Docker volume instead of the directory the user named. + */ + public String persistPath() { + return Path.of(persistDir).toAbsolutePath().normalize().toString(); + } + + // Absolute on the daemon's machine, whichever system that is: a leading slash, a drive + // letter with a separator, or a UNC share. + // Not decided by this machine's Path rules, which know only its own file system. + private static final Pattern REMOTE_ABSOLUTE = Pattern.compile("^(/|[A-Za-z]:[\\\\/]|\\\\\\\\)"); + + /** + * The bind source handed to a daemon reached through {@code daemon}. A remote daemon gets + * {@code persistDir} exactly as given: the path names a directory on its machine, and + * resolving it here would apply this machine's rules to it (a Windows CLI turns + * {@code /srv/data} into a drive path). Only a local daemon gets {@link #persistPath()}. + */ + public String bindSource(DockerClient.DockerHost daemon) { + return daemon.kind() == DockerClient.Kind.TCP ? persistDir : persistPath(); + } + + /** + * Creates the state directory, returning why it could not be created, or {@code null}. Done by + * the CLI rather than docker: a bind source docker creates is owned by root on Linux, and the + * emulator then cannot write to it. Restart calls this before it stops anything, so a + * directory that cannot be created leaves the running instance alone. + * + *

An existing directory is accepted as it is, with no write check: the emulator runs as its + * own user (uid 1001) and the AWS image re-owns its data directory at startup, so whether the + * CLI's user can write there says nothing about whether the emulator can. The emulator reports + * a directory it cannot write to itself. + */ + public String preparePersistDir() { + return preparePersistDir(DockerClient.dockerHost()); + } + + /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ + public String preparePersistDir(DockerClient.DockerHost daemon) { + if (persistDir == null || persistDir.isBlank()) return null; + // A remote daemon reads the bind source on its own machine, where this CLI can neither + // create nor check it; it is passed on untouched (bindSource), so nothing here can fail + // on it later either. It does have to be absolute: there is no working directory to + // resolve it against over there, and docker reads a bare name as a named volume. + if (daemon.kind() == DockerClient.Kind.TCP) { + return REMOTE_ABSOLUTE.matcher(persistDir).find() ? null + : "With a remote Docker daemon, --persist must be an absolute path on the daemon's machine, but was '" + + persistDir + "'.\nPass an absolute path, for example /srv/floci-data."; + } + Path path; + try { + path = Path.of(persistPath()); + } catch (InvalidPathException e) { + // Names persistDir as given: resolving it is what failed. + return "Invalid persist directory '" + persistDir + "': " + e.getReason() + + ".\nPass a --persist path that is valid on this system."; + } + try { + Files.createDirectories(path); + return null; + } catch (Exception e) { + return "Could not create the persist directory " + path + ": " + e.getMessage() + + "\nPass a --persist directory you can write to."; + } + } + public String resourceNamespace() { return resourceNamespaceFor(global.container); } @@ -134,12 +216,20 @@ public class StartCommand implements Callable { * the ambient {@code DOCKER_HOST} and so differs per machine. */ public List dockerRunArgs(List socketArgs) { + return dockerRunArgs(socketArgs, LOCAL_DAEMON); + } + + private static final DockerClient.DockerHost LOCAL_DAEMON = + new DockerClient.DockerHost(DockerClient.Kind.UNIX, null, null); + + /** {@link #dockerRunArgs(List)} for a daemon reached through {@code daemon}, which decides the bind source. */ + public List dockerRunArgs(List socketArgs, DockerClient.DockerHost daemon) { List args = new ArrayList<>(); args.addAll(List.of("-d", "--name", global.container)); args.addAll(List.of("-p", port + ":" + profile.defaultPort())); args.addAll(socketArgs); if (persistDir != null && !persistDir.isBlank()) { - args.addAll(List.of("-v", persistDir + ":/app/data")); + args.addAll(List.of("-v", bindSource(daemon) + ":/app/data")); // The server defaults to in-memory storage; enable persistent mode so // state is actually written to the mounted directory and survives restarts. args.addAll(List.of("-e", profile.envVar("STORAGE_MODE") + "=persistent")); @@ -200,6 +290,12 @@ public class StartCommand implements Callable { return 2; } + String unwritable = preparePersistDir(); + if (unwritable != null) { + printer.error(unwritable); + return 1; + } + // Check if container already exists. This is also the first docker call, so a missing // binary shows up here, without a separate `docker --version` probe on every start. try { @@ -232,7 +328,7 @@ public class StartCommand implements Callable { return 1; } - List args = dockerRunArgs(DockerClient.dockerSocketRunArgs()); + List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), DockerClient.dockerHost()); try { printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index ee85a95..d5283ac 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -10,6 +10,8 @@ import io.floci.cli.config.ProfileStore; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine; import picocli.CommandLine.ParseResult; @@ -25,6 +27,7 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** * Restart builds its StartCommand programmatically, so picocli never applies the profile to it. @@ -156,6 +159,37 @@ class RestartCommandTest { } } + /** + * A persist directory that cannot be created fails the restart before the stop, so the running + * instance is left alone instead of being removed and never started again. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anUnwritablePersistDirFailsBeforeTheStop() throws Exception { + Path readOnly = Files.createDirectories(tempDir.resolve("read-only")); + assertTrue(readOnly.toFile().setWritable(false)); + writeProfile("ro", "container: floci-ro-none\npersistDir: " + readOnly.resolve("state") + "\n"); + RestartCommand restart = parse(ProductProfile.AWS, "--profile", "ro"); + + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + try { + // Root writes through the permission bits; the restart would then reach Docker. + assumeFalse(Files.isWritable(readOnly), "permissions do not bind this user (root)"); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + assertEquals(1, restart.call()); + } finally { + System.setOut(out); + System.setErr(err); + readOnly.toFile().setWritable(true); + } + assertTrue(errBuf.toString().contains("Could not create the persist directory"), errBuf.toString()); + assertFalse(outBuf.toString().contains("Stopping"), "nothing was stopped: " + outBuf); + } + /** * One snapshot: restart applies the profile the parse read, not a second read of the file, so * an edit or delete in between cannot mix two versions into one restart. @@ -214,8 +248,20 @@ class RestartCommandTest { RestartCommand restart = new RestartCommand(ProductProfile.AWS, docker) { @Override public StartCommand buildStartCommand() throws DockerException { - super.buildStartCommand(); // the real one first, so its docker failure still surfaces + // The real one first, so its docker failure still surfaces; it also answers the + // checks restart runs before the stop, as only it carries the resolved settings. + StartCommand real = super.buildStartCommand(); return new StartCommand(ProductProfile.AWS) { + @Override + public String validationError() { + return real.validationError(); + } + + @Override + public String preparePersistDir() { + return real.preparePersistDir(); + } + @Override public Integer call() { ran.add("start"); diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java index 34ca95c..fbdfe19 100644 --- a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -3,8 +3,13 @@ package io.floci.cli.unit; import io.floci.cli.FlociCli; import io.floci.cli.commands.StartCommand; import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import picocli.CommandLine.ParseResult; import java.io.ByteArrayOutputStream; @@ -13,6 +18,7 @@ import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Locale; import static org.junit.jupiter.api.Assertions.*; @@ -191,6 +197,152 @@ class StartCommandArgsTest { .dockerRunArgs(SOCKET).contains("FLOCI_BASE_URL=http://floci.internal:14566")); } + /** BL-034: Docker reads "./data:/app/data" as a named volume, so the path goes in absolute. */ + @Test + void aRelativePersistDirIsMountedAsAnAbsoluteBindPath() { + String expected = Path.of("data").toAbsolutePath().normalize() + ":/app/data"; + + List args = parse("start", "--persist", "./data").dockerRunArgs(SOCKET); + + assertTrue(args.contains(expected), args.toString()); + assertFalse(args.contains("./data:/app/data"), args.toString()); + } + + /** BL-035: an out-of-range port or an unknown pull policy is refused before docker runs. */ + @Test + void portAndPullPolicyAreValidated() { + assertNull(parse("start").validationError()); + assertNull(parse("start", "--pull", "ALWAYS").validationError()); + assertTrue(parse("start", "--port", "0").validationError().contains("--port must be between 1 and 65535")); + assertTrue(parse("start", "--port", "70000").validationError().contains("--port must be between 1 and 65535")); + assertTrue(parse("start", "--pull", "alwayz").validationError().contains("Invalid --pull 'alwayz'")); + } + + /** Pull policies are plain ASCII words: a Turkish default locale lowercases "MISSING" with a dotless i. */ + @Test + void pullPolicyDoesNotDependOnTheDefaultLocale() { + Locale before = Locale.getDefault(); + Locale.setDefault(Locale.forLanguageTag("tr-TR")); + try { + assertNull(parse("start", "--pull", "MISSING").validationError()); + } finally { + Locale.setDefault(before); + } + } + + private static final DockerClient.DockerHost LOCAL = + new DockerClient.DockerHost(DockerClient.Kind.UNIX, "/var/run/docker.sock", null); + private static final DockerClient.DockerHost REMOTE = + new DockerClient.DockerHost(DockerClient.Kind.TCP, null, "tcp://build-host:2375"); + + @Test + void aLocalDaemonGetsItsPersistDirCreated() { + Path state = tempDir.resolve("made").resolve("state"); + + assertNull(parse("start", "--persist", state.toString()).preparePersistDir(LOCAL)); + + assertTrue(Files.isDirectory(state)); + } + + /** A remote daemon reads the bind source on its own machine: nothing is created or refused here. */ + @Test + void aRemoteDaemonsPersistDirIsNotCreatedLocally() throws Exception { + Path blocker = Files.writeString(Files.createDirectories(tempDir).resolve("a-file"), "x"); + Path state = blocker.resolve("state"); // cannot exist locally: its parent is a file + + assertNull(parse("start", "--persist", state.toString()).preparePersistDir(REMOTE)); + assertFalse(Files.exists(state)); + assertNotNull(parse("start", "--persist", state.toString()).preparePersistDir(LOCAL)); + } + + /** A path that is not valid on this platform gets the same hint, not an exception from building the message. */ + @Test + void anInvalidPersistPathIsReportedNotThrown() { + String invalid = "data\u0000dir"; // NUL is rejected by every platform's Path + + String error = parse("start", "--persist", invalid).preparePersistDir(LOCAL); + + assertNotNull(error); + assertTrue(error.startsWith("Invalid persist directory"), error); + assertTrue(error.contains("Pass a --persist path"), error); + } + + /** + * A remote daemon's path is its own: an absolute one is passed on as given, never resolved by + * this machine's rules (a Windows CLI would turn /srv/floci-data into a drive path). + */ + @Test + void aRemoteDaemonGetsThePersistPathExactlyAsGiven() { + StartCommand start = parse("start", "--persist", "/srv/floci-data/../state"); + + assertNull(start.preparePersistDir(REMOTE)); + assertEquals("/srv/floci-data/../state", start.bindSource(REMOTE)); + assertTrue(start.dockerRunArgs(SOCKET, REMOTE).contains("/srv/floci-data/../state:/app/data")); + } + + /** Only a local daemon has relative paths resolved against this machine's working directory. */ + @Test + void onlyALocalDaemonHasItsPersistPathResolved() { + StartCommand start = parse("start", "--persist", "./data"); + String resolved = Path.of("data").toAbsolutePath().normalize().toString(); + + assertEquals(resolved, start.bindSource(LOCAL)); + assertTrue(start.dockerRunArgs(SOCKET, LOCAL).contains(resolved + ":/app/data")); + } + + /** + * A remote daemon has no working directory of ours to resolve against, and docker reads a bare + * name as a named volume: a relative path is refused before anything is started or stopped. + */ + @ParameterizedTest + @ValueSource(strings = {"data", "./data", "../state", "C:data"}) + void aRemoteDaemonRefusesARelativePersistPath(String relative) { + String error = parse("start", "--persist", relative).preparePersistDir(REMOTE); + + assertNotNull(error); + assertTrue(error.contains("must be an absolute path on the daemon's machine"), error); + assertTrue(error.contains("'" + relative + "'"), error); + } + + /** Absolute for the daemon's system, whichever it is; this machine's path rules do not decide. */ + @ParameterizedTest + @ValueSource(strings = {"/srv/floci-data", "C:\\floci\\data", "c:/floci/data", "\\\\nas\\share\\floci"}) + void aRemoteDaemonAcceptsAnAbsolutePathOfEitherSystem(String absolute) { + StartCommand start = parse("start", "--persist", absolute); + + assertNull(start.preparePersistDir(REMOTE)); + assertEquals(absolute, start.bindSource(REMOTE)); + } + + /** + * What preparePersistDir accepts, dockerRunArgs can build. Restart runs the check before the + * stop, so a path this machine cannot even parse must not throw afterwards for a remote daemon. + */ + @Test + void aPathThisMachineCannotParseStillBuildsForARemoteDaemon() { + StartCommand start = parse("start", "--persist", "/srv/data\u0000dir"); + + assertNull(start.preparePersistDir(REMOTE)); + assertDoesNotThrow(() -> start.dockerRunArgs(SOCKET, REMOTE)); + assertNotNull(start.preparePersistDir(LOCAL)); + } + + /** + * An existing directory this user cannot write to is left to the emulator, which runs as its + * own user and reports an unwritable data directory itself. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anExistingDirectoryIsAcceptedWithoutAWriteCheck() throws Exception { + Path readOnly = Files.createDirectories(tempDir.resolve("read-only")); + assertTrue(readOnly.toFile().setWritable(false)); + try { + assertNull(parse("start", "--persist", readOnly.toString()).preparePersistDir(LOCAL)); + } finally { + readOnly.toFile().setWritable(true); + } + } + @Test void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() { assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599));