From 804e3559362daf37f8f3f8011df4f0824a7045fd Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 08:58:31 -0500 Subject: [PATCH 1/3] fix(completion): offer only bash and zsh, the shells a script is generated for (#59) The help listed fish and powershell, which only produced an error; an unsupported shell is now a usage error (exit 2) with nothing on stdout. Container details are read from docker's inspect JSON instead of a pipe-delimited template, which a value containing the delimiter could shift. Signed-off-by: Hector Ventura --- README.md | 2 + .../floci/cli/commands/CompletionCommand.java | 10 +-- .../io/floci/cli/docker/DockerClient.java | 70 +++++++++++------- .../floci/cli/unit/CompletionCommandTest.java | 72 +++++++++++++++++++ .../cli/unit/DockerClientProcessTest.java | 72 +++++++++++++++++++ 5 files changed, 198 insertions(+), 28 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/CompletionCommandTest.java diff --git a/README.md b/README.md index 9f1d2d4..4931f54 100644 --- a/README.md +++ b/README.md @@ -844,6 +844,8 @@ floci completion bash >> ~/.bashrc floci completion zsh >> ~/.zshrc ``` +Completion scripts are generated for bash and zsh. Any other shell name is a usage error (exit 2). + ### `floci update` Self-update the CLI in place: downloads the release binary from GitHub, verifies its diff --git a/src/main/java/io/floci/cli/commands/CompletionCommand.java b/src/main/java/io/floci/cli/commands/CompletionCommand.java index b22f662..a70de55 100644 --- a/src/main/java/io/floci/cli/commands/CompletionCommand.java +++ b/src/main/java/io/floci/cli/commands/CompletionCommand.java @@ -21,7 +21,9 @@ public class CompletionCommand implements Callable { @Spec Model.CommandSpec spec; - @Parameters(index = "0", description = "Shell type: bash, zsh, fish, powershell", paramLabel = "bash|zsh|fish|powershell") + // Only the shells a script is generated for: picocli writes bash completion, which zsh loads + // through bashcompinit. Listing fish and powershell here promised scripts that do not exist. + @Parameters(index = "0", description = "Shell type: bash or zsh", paramLabel = "bash|zsh") String shell; @Override @@ -36,13 +38,13 @@ public class CompletionCommand implements Callable { case "bash" -> AutoComplete.bash("floci", root); case "zsh" -> AutoComplete.bash("floci", root); // zsh is bash-compatible; picocli bash script works for zsh too default -> { - printer.error("Shell '" + shell + "' not supported. Supported: bash, zsh\n" + - "For fish and powershell, track https://github.com/floci-io/floci-cli/issues"); + printer.error("Shell '" + shell + "' is not supported.\nUse bash or zsh."); yield null; } }; - if (script == null) return 1; + // A value the command cannot accept, like any other bad argument. + if (script == null) return ExitCode.USAGE; System.out.print(script); return 0; } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index b07b146..56a748c 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -67,18 +67,10 @@ public class DockerClient { private static final ObjectMapper JSON = new ObjectMapper(); public Optional inspectRunSettings(String name, int containerPort) throws DockerException { - String out; + Optional document = inspectDocument(name); + if (document.isEmpty()) return Optional.empty(); 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); + JsonNode c = document.get(); String image = textOrNull(c.path("Config").path("Image")); Integer hostPort = null; JsonNode binding = c.path("HostConfig").path("PortBindings").path(containerPort + "/tcp"); @@ -133,26 +125,56 @@ public class DockerClient { } public Optional inspectContainer(String name) throws DockerException { + Optional document = inspectDocument(name); + if (document.isEmpty()) return Optional.empty(); + JsonNode c = document.get(); + String reported = c.path("Name").asText("").replaceFirst("^/", ""); + return Optional.of(new ContainerInfo( + c.path("Id").asText(""), + reported.isBlank() ? name : reported, + c.path("Config").path("Image").asText(""), + c.path("State").path("Status").asText(""), + publishedPorts(c.path("NetworkSettings").path("Ports")))); + } + + /** + * The published ports of an inspect document as {@code "14566->4566/tcp 18080->8080/tcp"}: + * host port, then the container side. A port that is exposed but not published has no + * binding and is left out. + */ + public static String publishedPorts(JsonNode ports) { + StringBuilder published = new StringBuilder(); + for (var port : ports.properties()) { + JsonNode bindings = port.getValue(); + if (!bindings.isArray() || bindings.isEmpty()) continue; + String hostPort = bindings.get(0).path("HostPort").asText(""); + if (hostPort.isBlank()) continue; + if (!published.isEmpty()) published.append(' '); + published.append(hostPort).append("->").append(port.getKey()); + } + return published.toString(); + } + + // The container's whole inspect document, or empty when there is no such container. One + // JSON read serves every caller; a field-by-field Go template had to be split on a + // delimiter, which a value could contain. + private Optional inspectDocument(String name) throws DockerException { + String out; try { - String out = run("docker", "container", "inspect", - "--format", - "{{.Id}}|{{.Name}}|{{.Config.Image}}|{{.State.Status}}|" + - "{{range $p, $b := .NetworkSettings.Ports}}{{if $b}}{{(index $b 0).HostPort}}->{{$p}} {{end}}{{end}}", - "--", name); - if (out.isBlank()) return Optional.empty(); - String[] parts = out.trim().split("\\|", -1); - return Optional.of(new ContainerInfo( - parts.length > 0 ? parts[0] : "", // id - parts.length > 1 ? parts[1].replaceFirst("^/", "") : name, - parts.length > 2 ? parts[2] : "", // image - parts.length > 3 ? parts[3] : "", // status - parts.length > 4 ? parts[4].trim() : "")); // ports + 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 { + return Optional.of(JSON.readTree(out)); + } catch (Exception e) { + throw new DockerException("Could not read the details of container '" + name + "': " + e.getMessage() + + "\n" + CHECK_DOCKER); + } } public boolean isImagePresent(String image) throws DockerException { diff --git a/src/test/java/io/floci/cli/unit/CompletionCommandTest.java b/src/test/java/io/floci/cli/unit/CompletionCommandTest.java new file mode 100644 index 0000000..7a5403d --- /dev/null +++ b/src/test/java/io/floci/cli/unit/CompletionCommandTest.java @@ -0,0 +1,72 @@ +package io.floci.cli.unit; + +import io.floci.cli.FlociCli; +import io.floci.cli.config.ProfileStore; +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.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-054: completion offers the shells it can generate a script for, and only those. */ +class CompletionCommandTest { + + @TempDir + Path tempDir; + + private record Run(int exit, String out, String err) {} + + private Run run(String... args) { + 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 { + int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void theHelpListsOnlyTheShellsThatWork() { + CommandLine completion = FlociCli.buildCommandLine(new ProfileStore(tempDir)).getSubcommands().get("completion"); + + assertEquals("bash|zsh", completion.getCommandSpec().positionalParameters().get(0).paramLabel()); + String usage = completion.getUsageMessage(CommandLine.Help.Ansi.OFF); + assertFalse(usage.contains("fish"), usage); + assertFalse(usage.contains("powershell"), usage); + } + + @ParameterizedTest + @ValueSource(strings = {"bash", "zsh", "BASH"}) + void aSupportedShellGetsAScript(String shell) { + Run r = run("completion", shell); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("floci"), "a completion script for the floci command"); + assertEquals("", r.err()); + } + + /** A shell there is no script for is a usage error, and nothing is written to stdout to be sourced. */ + @ParameterizedTest + @ValueSource(strings = {"fish", "powershell", "nushell"}) + void anUnsupportedShellIsAUsageError(String shell) { + Run r = run("completion", shell); + + assertEquals(2, r.exit()); + assertEquals("", r.out()); + assertTrue(r.err().contains("Shell '" + shell + "' is not supported."), r.err()); + assertTrue(r.err().contains("Use bash or zsh."), r.err()); + } +} diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index fb5d9a9..2dea2c7 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -1,5 +1,7 @@ package io.floci.cli.unit; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.cli.GlobalOptions; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; @@ -271,4 +273,74 @@ class DockerClientProcessTest { assertTrue(errBuf.toString().contains("+ docker rm"), errBuf.toString()); assertTrue(errBuf.toString().contains("floci-x"), errBuf.toString()); } + + private DockerClient dockerPrinting(String inspectJson) throws Exception { + Path json = Files.createTempFile(tempDir, "inspect", ".json"); + Files.writeString(json, inspectJson); + Path fakeDocker = Files.createTempFile(tempDir, "docker", ""); + Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n"); + assertTrue(fakeDocker.toFile().setExecutable(true)); + return new DockerClient(fakeDocker.toString()); + } + + /** BL-046: container details come from the inspect document, not from a delimiter-split template. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void containerDetailsAreReadFromTheInspectDocument() throws Exception { + DockerClient docker = dockerPrinting(""" + {"Id":"0123abcd","Name":"/floci-team-b","Config":{"Image":"floci/floci:1.6.0"}, + "State":{"Status":"running"}, + "NetworkSettings":{"Ports":{"4566/tcp":[{"HostIp":"0.0.0.0","HostPort":"14566"},{"HostIp":"::","HostPort":"14566"}], + "8080/tcp":null}}} + """); + + DockerClient.ContainerInfo info = docker.inspectContainer("floci-team-b").orElseThrow(); + + assertEquals("0123abcd", info.id()); + assertEquals("floci-team-b", info.name()); + assertEquals("floci/floci:1.6.0", info.image()); + assertEquals("running", info.state()); + assertEquals("14566->4566/tcp", info.ports()); + } + + /** A value with the old delimiter in it cannot shift the fields any more. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aPipeInAValueDoesNotShiftTheFields() throws Exception { + DockerClient docker = dockerPrinting(""" + {"Id":"0123abcd","Name":"/floci","Config":{"Image":"registry.local/team|floci:latest"}, + "State":{"Status":"exited"},"NetworkSettings":{"Ports":{}}} + """); + + DockerClient.ContainerInfo info = docker.inspectContainer("floci").orElseThrow(); + + assertEquals("registry.local/team|floci:latest", info.image()); + assertEquals("exited", info.state()); + assertEquals("", info.ports()); + } + + @Test + void publishedPortsListEveryBindingAndSkipWhatIsNotPublished() throws Exception { + JsonNode ports = new ObjectMapper().readTree(""" + {"4566/tcp":[{"HostIp":"","HostPort":"14566"}],"8080/tcp":null,"9000/tcp":[], + "4510/tcp":[{"HostIp":"","HostPort":"24510"}]} + """); + + assertEquals("14566->4566/tcp 24510->4510/tcp", DockerClient.publishedPorts(ports)); + assertEquals("", DockerClient.publishedPorts(new ObjectMapper().readTree("{}"))); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void aMissingContainerIsEmptyAndGarbageIsReportedWithANextStep() throws Exception { + Path missing = Files.createTempFile(tempDir, "docker", ""); + Files.writeString(missing, "#!/bin/sh\necho 'Error response from daemon: No such container: floci' >&2\nexit 1\n"); + assertTrue(missing.toFile().setExecutable(true)); + + assertTrue(new DockerClient(missing.toString()).inspectContainer("floci").isEmpty()); + + DockerException e = assertThrows(DockerException.class, () -> dockerPrinting("not json").inspectContainer("floci")); + assertTrue(e.getMessage().contains("Could not read the details of container 'floci'"), e.getMessage()); + assertTrue(e.getMessage().contains("docker info"), e.getMessage()); + } } From 4a9a9b5a4a22cb1ea84133812fe2dec7f3c6eb81 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 08:59:58 -0500 Subject: [PATCH 2/3] feat(cli): structured output for start, stop and restart, and a status exit code scripts can use (#60) * feat(cli): structured output for start, stop and restart, and a status exit code scripts can use start, stop and restart print one document with -o json or -o yaml and keep progress off stdout. status exits 1 when the instance is not up (it always exited 0). logs stays plain text and says so when -o is passed. Signed-off-by: Hector Ventura * feat(cli): report the container's real state after start and stop start reads the state back, so a container that exited during the readiness wait is not reported as running, and stop reports a container docker removed on its own (--rm) as removed. The tests now reject anything after the one document on stdout. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- README.md | 11 + .../io/floci/cli/commands/LogsCommand.java | 6 + .../io/floci/cli/commands/RestartCommand.java | 9 +- .../io/floci/cli/commands/StartCommand.java | 74 +++- .../io/floci/cli/commands/StatusCommand.java | 27 +- .../io/floci/cli/commands/StopCommand.java | 62 ++- .../io/floci/cli/commands/WaitCommand.java | 8 +- .../io/floci/cli/docker/DockerClient.java | 17 +- .../io/floci/cli/unit/ActionOutputTest.java | 400 ++++++++++++++++++ .../io/floci/cli/unit/StartPreflightTest.java | 5 + 10 files changed, 588 insertions(+), 31 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/ActionOutputTest.java diff --git a/README.md b/README.md index 4931f54..fab9051 100644 --- a/README.md +++ b/README.md @@ -459,16 +459,27 @@ floci stop # graceful stop (10s timeout) floci stop --timeout 30 # wait up to 30s before force-kill floci stop --timeout -1 # never force-kill: wait for the container to exit floci stop --remove # also remove the container after stopping +floci stop -o json # {"container", "state", "stopped", "removed"} ``` +`start`, `stop` and `restart` print one document with `-o json` or `-o yaml` and nothing else on +stdout: the progress lines are left out and docker's pull progress goes to stderr. `start` and +`restart` report `container`, `id`, `image`, `endpoint`, `state` and `ready` (`ready` is absent +with `--detach`). `logs` prints the container's own output and stays plain text. + ### `floci status` / `floci gcp status` / `floci az status` / `floci oci status` ```sh floci status # auto-detects endpoint from container port mapping floci status --container myfloci # target a specific container floci status -o json # structured output +floci status >/dev/null && echo up # exit 0: the instance is up, exit 1: it is not ``` +`status` exits 0 when the server answers and its container, if there is one, is running, and 1 +otherwise, in every output format. An instance with no local container (a remote `--endpoint`, a +Compose service under another name) counts as up when it answers. + ### `floci env` Prints AWS environment variables pointing at the running Floci instance. The default diff --git a/src/main/java/io/floci/cli/commands/LogsCommand.java b/src/main/java/io/floci/cli/commands/LogsCommand.java index b2ad0f2..af0f752 100644 --- a/src/main/java/io/floci/cli/commands/LogsCommand.java +++ b/src/main/java/io/floci/cli/commands/LogsCommand.java @@ -4,6 +4,7 @@ import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; @@ -58,6 +59,11 @@ public class LogsCommand implements Callable { return 1; } + if (printer.format() != OutputFormat.text) { + // Logs are the container's own output, line by line; there is no document to build. + printer.warn("logs prints the container's output as plain text; -o " + printer.format() + " is ignored."); + } + if (service != null) { printer.warn("--service filtering is not yet supported. Showing all container logs."); } diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 85b2e11..a3754e9 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -6,6 +6,7 @@ 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.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -81,7 +82,9 @@ public class RestartCommand implements Callable { if (!containerExists()) { // Nothing to stop: start it, rather than failing on the stop. - printer.println("Container '" + global.container + "' not found; starting it."); + if (printer.format() == OutputFormat.text) { + printer.println("Container '" + global.container + "' not found; starting it."); + } return start.call(); } @@ -97,8 +100,10 @@ public class RestartCommand implements Callable { * that follows needs neither a pause nor a second inspect-and-remove of its own. */ public StopCommand buildStopCommand() { - StopCommand stop = new StopCommand(profile); + StopCommand stop = new StopCommand(profile, docker); stop.global = global; + // The start that follows reports the restart; one structured document, not two. + stop.embedded = true; stop.remove = true; stop.timeout = 10; return stop; diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 7ab7887..ce907ab 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -10,6 +10,7 @@ import io.floci.cli.doctor.CheckStatus; import io.floci.cli.doctor.checks.DockerSocketCheck; import io.floci.cli.doctor.checks.PortAvailableCheck; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine; import picocli.CommandLine.*; @@ -19,10 +20,13 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Callable; +import java.util.function.Consumer; import java.util.regex.Pattern; @Command( @@ -295,6 +299,10 @@ public class StartCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + // Structured output is one document on stdout: the progress lines a person reads are + // left out, and docker's own pull progress goes to stderr. + boolean structured = printer.format() != OutputFormat.text; + Consumer progress = structured ? line -> { } : printer::println; String invalid = validationError(); if (invalid != null) { @@ -323,7 +331,7 @@ public class StartCommand implements Callable { return 1; } // Remove stopped container so we can start fresh - printer.println(Ansi.gray("Removing stopped container '" + global.container + "'...")); + progress.accept(Ansi.gray("Removing stopped container '" + global.container + "'...")); docker.removeContainer(global.container); } } catch (DockerException e) { @@ -350,8 +358,12 @@ public class StartCommand implements Callable { // Pull image if needed try { - printer.println(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); - docker.pull(image, pull); + progress.accept(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); + if (structured) { + docker.pull(image, pull, System.err); + } else { + docker.pull(image, pull); + } } catch (DockerException e) { printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never' to skip pulling."); return 1; @@ -359,32 +371,66 @@ public class StartCommand implements Callable { List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), daemon); + String id; try { - printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); - String id = docker.startContainer(args); - printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); + progress.accept("Starting " + Ansi.gold(profile.displayName()) + " container..."); + id = docker.startContainer(args); + progress.accept(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); } catch (DockerException e) { printer.error("Failed to start container: " + e.getMessage(), "Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port."); return 1; } + // The endpoint of the port actually bound, keeping whatever host the endpoint already + // names — a profile or --endpoint may well point somewhere else. + String endpoint = withPort(global.endpoint, port); + if (detach) { - printer.println(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness.")); + progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness.")); + if (structured) printer.structured(result(id, endpoint, null)); return 0; } - // Point the readiness poll at the port actually bound, keeping whatever host the - // endpoint already names — a profile or --endpoint may well point somewhere else. - global.endpoint = withPort(global.endpoint, port); + global.endpoint = endpoint; // Wait for readiness - printer.println(Ansi.gray("Waiting for " + profile.displayName() + " to be ready...")); + progress.accept(Ansi.gray("Waiting for " + profile.displayName() + " to be ready...")); WaitCommand wait = new WaitCommand(profile); wait.global = global; - wait.knownEndpoint = global.endpoint; - wait.timeout = "30s"; - return wait.call(); + wait.knownEndpoint = endpoint; + wait.timeout = readinessTimeout(); + wait.embedded = true; + int exit = wait.call(); + if (structured) printer.structured(result(id, endpoint, exit == 0)); + return exit; + } + + /** How long start waits for the emulator to answer. A seam: tests do not wait half a minute. */ + protected String readinessTimeout() { + return "30s"; + } + + // What -o json/yaml reports for a start: 'ready' is left out when --detach did not wait for it. + private Map result(String id, String endpoint, Boolean ready) { + Map result = new LinkedHashMap<>(); + result.put("container", global.container); + result.put("id", id); + result.put("image", image); + result.put("endpoint", endpoint); + result.put("state", stateNow()); + if (ready != null) result.put("ready", ready); + return result; + } + + // Read back, not assumed: a container that crashed while start waited for it has exited, and + // a script must not be told it is running. "unknown" when docker cannot say. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse("removed"); + } catch (DockerException e) { + return "unknown"; + } } /** diff --git a/src/main/java/io/floci/cli/commands/StatusCommand.java b/src/main/java/io/floci/cli/commands/StatusCommand.java index ba901c8..598e1e4 100644 --- a/src/main/java/io/floci/cli/commands/StatusCommand.java +++ b/src/main/java/io/floci/cli/commands/StatusCommand.java @@ -32,14 +32,21 @@ public class StatusCommand implements Callable { } protected StatusCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers the container lookup. */ + public StatusCommand(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(); - DockerClient docker = new DockerClient(); // Gather container info String containerState = "not found"; @@ -80,9 +87,10 @@ public class StatusCommand implements Callable { data.put("version", serverVersion); data.put("edition", serverEdition); + int exit = exitCode(containerState, reachable); if (printer.format() != OutputFormat.text) { printer.structured(data); - return 0; + return exit; } printer.println(Ansi.bold(profile.displayName() + " Status")); @@ -107,7 +115,20 @@ public class StatusCommand implements Callable { printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start' to launch " + profile.displayName() + ".")); } - return 0; + return exit; + } + + /** + * 0 when the instance is up, 1 when it is not, so a script can ask. Up means the server + * answers and its container, if there is one, is running. An instance with no container here + * (a remote endpoint, a Compose service under another name), or whose container docker could + * not look up, is up when it answers. + */ + public static int exitCode(String containerState, boolean reachable) { + // A lookup that failed ("error: ...") says nothing about the container either way. + boolean containerDown = !"running".equals(containerState) && !"not found".equals(containerState) + && !containerState.startsWith("error:"); + return reachable && !containerDown ? 0 : 1; } } diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java index 1af7136..2d75e6e 100644 --- a/src/main/java/io/floci/cli/commands/StopCommand.java +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -5,10 +5,14 @@ import io.floci.cli.ProductProfile; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; +import java.util.function.Consumer; @Command( name = "stop", @@ -27,10 +31,24 @@ public class StopCommand implements Callable { } protected StopCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers every docker call this stop makes. */ + public StopCommand(ProductProfile profile, DockerClient docker) { this.profile = profile; this.global = new GlobalOptions(profile); + this.docker = docker; } + private final DockerClient docker; + + /** + * Set by {@code restart}, whose start reports the outcome: this stop then prints no structured + * document of its own, so stdout carries exactly one. + */ + boolean embedded; + @Option(names = {"--remove", "-r"}, description = "Remove the container after stopping") boolean remove; @@ -40,7 +58,8 @@ public class StopCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - DockerClient docker = new DockerClient(); + boolean structured = printer.format() != OutputFormat.text; + Consumer progress = structured ? line -> { } : printer::println; try { var info = docker.inspectContainer(global.container); @@ -49,11 +68,12 @@ public class StopCommand implements Callable { return 1; } if (!"running".equals(info.get().state())) { - printer.println(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); + progress.accept(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); if (remove) { docker.removeContainer(global.container); - printer.println("Container removed."); + progress.accept("Container removed."); } + report(printer, structured, remove ? "removed" : info.get().state(), false, remove); return 0; } } catch (DockerException e) { @@ -62,24 +82,52 @@ public class StopCommand implements Callable { } try { - printer.println("Stopping " + Ansi.gold(profile.displayName()) + " container '" + global.container + "'..."); + progress.accept("Stopping " + Ansi.gold(profile.displayName()) + " container '" + global.container + "'..."); docker.stopContainer(global.container, timeout); - printer.println(Ansi.green("Stopped.")); + progress.accept(Ansi.green("Stopped.")); } catch (DockerException e) { printer.error("Failed to stop container: " + e.withNextStep(DockerClient.CHECK_DOCKER)); return 1; } - if (remove) { + // What is left of it: a container run with docker's --rm is gone the moment it stops, + // whatever --remove said, so the result is read back rather than assumed. + String state = stateNow(); + boolean gone = state == null; + if (remove && !gone) { try { docker.removeContainer(global.container); - printer.println("Container removed."); + gone = true; } catch (DockerException e) { printer.error("Failed to remove container: " + e.withNextStep(DockerClient.CHECK_DOCKER)); return 1; } } + if (remove) progress.accept("Container removed."); + report(printer, structured, gone ? "removed" : state, true, gone); return 0; } + + // The container's state as docker has it now; null when it no longer exists. A lookup that + // fails after a stop that succeeded is reported as the state the stop leaves behind. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse(null); + } catch (DockerException e) { + return "exited"; + } + } + + // What -o json/yaml reports for a stop: the state the container was left in, whether this + // call is what stopped it, and whether it was removed. + private void report(Printer printer, boolean structured, String state, boolean stopped, boolean removed) { + if (!structured || embedded) return; + Map result = new LinkedHashMap<>(); + result.put("container", global.container); + result.put("state", state); + result.put("stopped", stopped); + result.put("removed", removed); + printer.structured(result); + } } diff --git a/src/main/java/io/floci/cli/commands/WaitCommand.java b/src/main/java/io/floci/cli/commands/WaitCommand.java index a9ed3a0..030db5a 100644 --- a/src/main/java/io/floci/cli/commands/WaitCommand.java +++ b/src/main/java/io/floci/cli/commands/WaitCommand.java @@ -70,6 +70,12 @@ public class WaitCommand implements Callable { */ String knownEndpoint; + /** + * Set by {@code start}, which reports the outcome in its own structured result: this wait + * then prints no document of its own, so stdout carries exactly one. + */ + boolean embedded; + static final long FIRST_DELAY_MS = 25; static final long MAX_DELAY_MS = 500; static final Duration MAX_REQUEST_TIMEOUT = Duration.ofSeconds(10); @@ -99,7 +105,7 @@ public class WaitCommand implements Callable { 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)); + if (!embedded) printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint)); } else { printer.println(Ansi.green(profile.displayName() + " is ready") + " (" + effectiveEndpoint + ")"); } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 56a748c..0d0e264 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -8,6 +8,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.PrintStream; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -208,9 +209,17 @@ public class DockerClient { } public void pull(String image, String policy) throws DockerException { + pull(image, policy, System.out); + } + + /** + * {@link #pull(String, String)} with docker's progress written to {@code progress}. A command + * printing structured output sends it to stderr, so stdout stays one parseable document. + */ + public void pull(String image, String policy, PrintStream progress) throws DockerException { if ("never".equalsIgnoreCase(policy)) return; if ("missing".equalsIgnoreCase(policy) && isImagePresent(image)) return; - runStreaming("docker", "pull", "--", image); + runStreaming(progress, "docker", "pull", "--", image); } public String startContainer(List args) throws DockerException { @@ -249,7 +258,7 @@ public class DockerClient { if (since != null && !since.isBlank()) { cmd.add("--since"); cmd.add(since); } cmd.add("--"); cmd.add(name); - runStreaming(cmd.toArray(String[]::new)); + runStreaming(System.out, cmd.toArray(String[]::new)); } private String run(String... cmd) throws DockerException { @@ -304,7 +313,7 @@ public class DockerClient { return words.toString(); } - private void runStreaming(String... cmd) throws DockerException { + private void runStreaming(PrintStream stdout, String... cmd) throws DockerException { Process proc = null; boolean finished = false; try { @@ -312,7 +321,7 @@ public class DockerClient { proc = started; Thread out = new Thread(() -> { try (var reader = new BufferedReader(new InputStreamReader(started.getInputStream()))) { - reader.lines().forEach(System.out::println); + reader.lines().forEach(stdout::println); } catch (IOException ignored) {} }); Thread err = new Thread(() -> { diff --git a/src/test/java/io/floci/cli/unit/ActionOutputTest.java b/src/test/java/io/floci/cli/unit/ActionOutputTest.java new file mode 100644 index 0000000..85fe29f --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ActionOutputTest.java @@ -0,0 +1,400 @@ +package io.floci.cli.unit; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MappingIterator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.RestartCommand; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.commands.StatusCommand; +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.DockerClient.DockerHost; +import io.floci.cli.docker.DockerClient.Kind; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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.CsvSource; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * BL-056 and BL-057: start, stop and restart print one structured document with -o json/yaml and + * nothing else on stdout, and status says through its exit code whether the instance is up. + */ +class ActionOutputTest { + + // A remote daemon, so start does not probe the local port its own stub server listens on. + private static final DockerHost REMOTE = new DockerHost(Kind.TCP, null, "tcp://build-host:2375"); + // One document and nothing after it: a second value on stdout fails the parse. + private static final ObjectMapper JSON = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + + /** The single YAML document on {@code stdout}; fails when there are several, or none. */ + private static JsonNode oneYamlDocument(String stdout) throws Exception { + List documents = new ArrayList<>(); + try (MappingIterator all = YAML.readerFor(JsonNode.class).readValues(stdout)) { + all.forEachRemaining(documents::add); + } + assertEquals(1, documents.size(), "exactly one YAML document on stdout: " + stdout); + assertTrue(documents.get(0).isObject(), stdout); + return documents.get(0); + } + + @TempDir + Path tempDir; + + private HttpServer emulator; + private int port; + + @BeforeEach + void startEmulatorStub() throws Exception { + emulator = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + emulator.createContext("/", exchange -> { + byte[] body = "{\"version\":\"1.6.0\",\"edition\":\"community\",\"services\":[\"s3\"]}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + exchange.close(); + }); + emulator.start(); + port = emulator.getAddress().getPort(); + } + + @AfterEach + void stopEmulatorStub() { + emulator.stop(0); + } + + /** A docker that holds one container (or none) and records what was asked of it. */ + private static class FakeDocker extends DockerClient { + final List calls = new ArrayList<>(); + String state; // null: no such container + String ports = ""; + + FakeDocker(String state) { + this.state = state; + } + + @Override + public DockerHost daemonHost() { + return REMOTE; + } + + @Override + public Optional inspectContainer(String name) { + return state == null ? Optional.empty() + : Optional.of(new ContainerInfo("abc123", name, "floci/floci:latest", state, ports)); + } + + @Override + public Optional inspectRunSettings(String name, int containerPort) { + return Optional.empty(); + } + + @Override + public void pull(String image, String policy) { + calls.add("pull:stdout"); + System.out.println("latest: Pulling from floci/floci"); + } + + @Override + public void pull(String image, String policy, PrintStream progress) { + calls.add("pull:" + (progress == System.err ? "stderr" : "other")); + progress.println("latest: Pulling from floci/floci"); + } + + @Override + public String startContainer(List args) { + calls.add("run"); + state = "running"; + return "0123456789abcdef0123"; + } + + @Override + public void stopContainer(String name, int timeout) { + calls.add("stop"); + state = "exited"; + } + + @Override + public void removeContainer(String name) { + calls.add("rm"); + state = null; + } + } + + private record Run(int exit, String out, String err) {} + + private Run execute(Callable command, String... args) { + 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 { + int exit = new CommandLine(command) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + private String[] startArgs(String... more) { + List args = new ArrayList<>(List.of("--port", String.valueOf(port), "--container", "floci-actions")); + args.addAll(List.of(more)); + return args.toArray(String[]::new); + } + + // ---- start ----------------------------------------------------------------------------------- + + @Test + void startPrintsOneJsonDocumentAndKeepsProgressOffStdout() throws Exception { + FakeDocker docker = new FakeDocker(null); + + Run r = execute(new StartCommand(ProductProfile.AWS, docker), startArgs("-o", "json", "--pull", "always")); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); // fails if anything but the document is on stdout + assertEquals("floci-actions", json.path("container").asText()); + assertEquals("0123456789abcdef0123", json.path("id").asText()); + assertEquals("floci/floci:latest", json.path("image").asText()); + assertEquals("http://localhost:" + port, json.path("endpoint").asText()); + assertEquals("running", json.path("state").asText()); + assertTrue(json.path("ready").asBoolean()); + assertEquals(List.of("pull:stderr", "run"), docker.calls); + assertTrue(r.err().contains("Pulling from"), "docker's pull progress goes to stderr: " + r.err()); + assertFalse(r.out().contains("Starting"), r.out()); + } + + @Test + void aDetachedStartReportsNoReadiness() throws Exception { + Run r = execute(new StartCommand(ProductProfile.AWS, new FakeDocker(null)), startArgs("-o", "json", "--detach")); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("running", json.path("state").asText()); + assertFalse(json.has("ready"), "readiness was not waited for: " + r.out()); + } + + @Test + void startInYamlIsOneDocumentToo() throws Exception { + Run r = execute(new StartCommand(ProductProfile.AWS, new FakeDocker(null)), startArgs("-o", "yaml", "--detach")); + + assertEquals(0, r.exit(), r.err()); + JsonNode yaml = oneYamlDocument(r.out()); + assertEquals("floci-actions", yaml.path("container").asText()); + assertEquals("running", yaml.path("state").asText()); + assertEquals(5, yaml.size(), "container, id, image, endpoint, state: " + r.out()); + } + + @Test + void anythingExtraOnStdoutFailsTheseTests() { + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\n{\"b\":2}\n")); + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\nStarting...\n")); + assertThrows(AssertionError.class, () -> oneYamlDocument("a: 1\n---\nb: 2\n")); + } + + /** A container that died while start waited for it is reported as it is, not as running. */ + @Test + void aContainerThatExitedDuringTheWaitIsNotReportedRunning() throws Exception { + emulator.stop(0); // nothing answers the readiness poll + FakeDocker docker = new FakeDocker(null) { + @Override + public String startContainer(List args) { + String id = super.startContainer(args); + state = "exited"; // it crashed right after docker run returned + return id; + } + }; + StartCommand start = new StartCommand(ProductProfile.AWS, docker) { + @Override + protected String readinessTimeout() { + return "300ms"; + } + }; + + Run r = execute(start, startArgs("-o", "json")); + + assertEquals(1, r.exit()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("exited", json.path("state").asText()); + assertFalse(json.path("ready").asBoolean()); + } + + /** Text output is what it was: the progress lines, and docker's pull output on stdout. */ + @Test + void startInTextStillNarrates() { + FakeDocker docker = new FakeDocker(null); + + Run r = execute(new StartCommand(ProductProfile.AWS, docker), startArgs("--detach", "--pull", "always")); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("Container started"), r.out()); + assertTrue(r.out().contains("Detached."), r.out()); + assertEquals(List.of("pull:stdout", "run"), docker.calls); + assertFalse(r.out().contains("\"container\""), r.out()); + } + + // ---- stop ------------------------------------------------------------------------------------ + + @ParameterizedTest + @CsvSource({"false, exited, stop", "true, removed, stop;rm"}) + void stopReportsWhatItDid(boolean remove, String state, String calls) throws Exception { + FakeDocker docker = new FakeDocker("running"); + List args = new ArrayList<>(List.of("-o", "json", "--container", "floci-actions")); + if (remove) args.add("--remove"); + + Run r = execute(new StopCommand(ProductProfile.AWS, docker), args.toArray(String[]::new)); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("floci-actions", json.path("container").asText()); + assertEquals(state, json.path("state").asText()); + assertTrue(json.path("stopped").asBoolean()); + assertEquals(remove, json.path("removed").asBoolean()); + assertEquals(List.of(calls.split(";")), docker.calls); + } + + /** A container run with docker's --rm is gone once it stops, whatever --remove said. */ + @ParameterizedTest + @CsvSource({"false", "true"}) + void aContainerDockerRemovesItselfIsReportedRemoved(boolean remove) throws Exception { + FakeDocker docker = new FakeDocker("running") { + @Override + public void stopContainer(String name, int timeout) { + calls.add("stop"); + state = null; // --rm: docker removed it + } + }; + List args = new ArrayList<>(List.of("-o", "json")); + if (remove) args.add("--remove"); + + Run r = execute(new StopCommand(ProductProfile.AWS, docker), args.toArray(String[]::new)); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("removed", json.path("state").asText()); + assertTrue(json.path("removed").asBoolean()); + assertEquals(List.of("stop"), docker.calls, "nothing left to remove"); + } + + @Test + void stoppingAContainerThatIsNotRunningSaysSo() throws Exception { + Run r = execute(new StopCommand(ProductProfile.AWS, new FakeDocker("exited")), "-o", "json"); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("exited", json.path("state").asText()); + assertFalse(json.path("stopped").asBoolean()); + assertFalse(json.path("removed").asBoolean()); + } + + @Test + void stopInTextStillNarrates() { + Run r = execute(new StopCommand(ProductProfile.AWS, new FakeDocker("running")), "--remove"); + + assertTrue(r.out().contains("Stopped."), r.out()); + assertTrue(r.out().contains("Container removed."), r.out()); + } + + // ---- restart --------------------------------------------------------------------------------- + + /** A restart is a stop and a start, but its structured output is the one document of the start. */ + @Test + void restartPrintsOneDocument() throws Exception { + FakeDocker docker = new FakeDocker("running"); + docker.ports = port + "->4566/tcp"; + RestartCommand restart = new RestartCommand(ProductProfile.AWS, docker) { + @Override + public StartCommand buildStartCommand() { + StartCommand start = new StartCommand(ProductProfile.AWS, docker); + new CommandLine(start).parseArgs(startArgs("-o", "json")); + return start; + } + }; + + Run r = execute(restart, "-o", "json", "--container", "floci-actions"); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("running", json.path("state").asText()); + assertTrue(json.path("ready").asBoolean()); + assertEquals(List.of("stop", "rm", "pull:stderr", "run"), docker.calls); + } + + // ---- status ---------------------------------------------------------------------------------- + + @ParameterizedTest + @CsvSource({ + "running, true, 0", + "running, false, 1", + "exited, false, 1", + "exited, true, 1", // something else answers there; this container is down + "not found, true, 0", // a remote endpoint, or a Compose service under another name + "not found, false, 1", + "'error: Cannot connect to the Docker daemon', true, 0", + "'error: Cannot connect to the Docker daemon', false, 1"}) + void statusExitCodeSaysWhetherTheInstanceIsUp(String state, boolean reachable, int exit) { + assertEquals(exit, StatusCommand.exitCode(state, reachable)); + } + + @Test + void statusOfARunningInstanceExitsZero() throws Exception { + FakeDocker docker = new FakeDocker("running"); + docker.ports = port + "->4566/tcp"; + + Run json = execute(new StatusCommand(ProductProfile.AWS, docker), "-o", "json"); + Run text = execute(new StatusCommand(ProductProfile.AWS, docker)); + + assertEquals(0, json.exit(), json.err()); + assertTrue(JSON.readTree(json.out()).path("reachable").asBoolean()); + assertEquals(0, text.exit()); + assertTrue(text.out().contains("Reachable: yes"), text.out()); + } + + @Test + void statusOfAnInstanceThatIsDownExitsOneInEveryFormat() throws Exception { + int closed; + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + closed = socket.getLocalPort(); + } + FakeDocker docker = new FakeDocker(null); + String endpoint = "http://127.0.0.1:" + closed; + + Run json = execute(new StatusCommand(ProductProfile.AWS, docker), "-o", "json", "--endpoint", endpoint); + Run text = execute(new StatusCommand(ProductProfile.AWS, docker), "--endpoint", endpoint); + + assertEquals(1, json.exit()); + assertFalse(JSON.readTree(json.out()).path("reachable").asBoolean()); + assertEquals("not found", JSON.readTree(json.out()).path("state").asText()); + assertEquals(1, text.exit()); + assertTrue(text.out().contains("floci start"), text.out()); + } +} diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 0930b69..0e8fd82 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -60,6 +60,11 @@ class StartPreflightTest { calls.add("pull"); } + @Override + public void pull(String image, String policy, PrintStream progress) { + calls.add("pull"); + } + @Override public String startContainer(List args) { runArgs.addAll(args); From 6b063825161dfbb5030972d62439e9af4f389632 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 09:01:14 -0500 Subject: [PATCH 3/3] feat(config): validate Compose files by their structure, with -o json and three more checks (#61) * feat(config): validate Compose files by their structure, with -o json and three more checks config validate now parses the Compose file and checks the emulator's own service: any host port mapped to the emulator port is accepted (5566:4566 was rejected), -o json and -o yaml report the findings, and it flags a read-only or file-bound data volume, a data volume without persistent storage mode (and the reverse), and an image tag older than the supported minimum. Signed-off-by: Hector Ventura * feat(config): check the socket target, TCP mappings and bind types, and report unparsable files as JSON The socket has to land at /var/run/docker.sock in the container, a UDP mapping no longer counts, a long-form bind with a bare name is checked as a path, an env_file makes the storage mode unknown, and a file that cannot be parsed still gets a structured report. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- README.md | 15 + .../cli/commands/config/ComposeCheck.java | 267 +++++++++++ .../config/ConfigValidateCommand.java | 86 ++-- .../cli/doctor/checks/ImageVersionCheck.java | 3 +- .../io/floci/cli/unit/ConfigValidateTest.java | 452 ++++++++++++++++++ 5 files changed, 791 insertions(+), 32 deletions(-) create mode 100644 src/main/java/io/floci/cli/commands/config/ComposeCheck.java create mode 100644 src/test/java/io/floci/cli/unit/ConfigValidateTest.java diff --git a/README.md b/README.md index fab9051..acf3a88 100644 --- a/README.md +++ b/README.md @@ -729,6 +729,21 @@ Each product tree has its own `config show|validate|profile` (`floci gcp config uses that product's defaults; `config default-product` is available through bare `floci config` and `floci aws config`, but not through the GCP, Azure, or OCI config trees. +`config validate` reads the Compose file and checks the service that runs the emulator (found by +its image; a file with a single service is checked whatever its image is): + +| Check | Result when it fails | +|---|---| +| The emulator port is mapped over TCP (`"4566:4566"`, `"5566:4566"`, `"127.0.0.1:5566:4566"`, a range, or the long form; any host port works) | error | +| A socket is mounted at `/var/run/docker.sock` in the container (the host side may be any socket) | error where the product needs it, otherwise a warning | +| The volume at `/app/data` is writable and not bound to a file | error | +| A volume at `/app/data` comes with `_STORAGE_MODE=persistent`, and the other way round | warning | +| The image tag is not older than the oldest version this CLI supports (AWS tree) | warning | + +It exits 1 when there is an error and 0 otherwise. `-o json` and `-o yaml` print +`file`, `service`, `valid`, `errors` and `warnings`, also for a file that cannot be parsed. An +`env_file` is not read, so nothing is said about a storage mode it may set. + #### Profiles Profiles are stored in `~/.floci/profiles/.yaml`. Pass `--profile ` to any command to diff --git a/src/main/java/io/floci/cli/commands/config/ComposeCheck.java b/src/main/java/io/floci/cli/commands/config/ComposeCheck.java new file mode 100644 index 0000000..18e6520 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ComposeCheck.java @@ -0,0 +1,267 @@ +package io.floci.cli.commands.config; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.cli.ProductProfile; +import io.floci.cli.doctor.checks.ImageVersionCheck; +import io.floci.cli.update.Version; + +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * What {@code config validate} finds in a Compose file. It reads the parsed document and looks + * at the one service that runs the product's emulator, so a port or a volume on some other + * service is never taken for the emulator's. + */ +public final class ComposeCheck { + + /** The directory the emulator keeps its state in, inside the container. */ + static final String DATA_DIR = "/app/data"; + + private ComposeCheck() {} + + /** + * The findings for one file. {@code service} is the Compose service that was checked, or null + * when none could be told apart as the emulator's. + */ + public record Report(String service, List errors, List warnings) { + + public boolean valid() { + return errors.isEmpty(); + } + } + + /** Where the emulator looks for the Docker socket, inside the container. */ + static final String DOCKER_SOCK = "/var/run/docker.sock"; + + /** + * A volume entry, from either the short {@code src:dst[:mode]} or the long form. {@code bind} + * is true when the source is a path on the host rather than a named volume. + */ + record Mount(String source, String target, boolean readOnly, boolean bind) {} + + /** + * @param baseDir the Compose file's directory, against which relative bind sources resolve + */ + public static Report analyze(JsonNode compose, ProductProfile profile, boolean dockerSockRequired, + String dockerSockNeededFor, Path baseDir) { + List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); + JsonNode services = compose.path("services"); + if (!services.isObject() || services.isEmpty()) { + errors.add("No services found: a Compose file needs a 'services' section with the " + + profile.displayName() + " service in it"); + return new Report(null, errors, warnings); + } + + String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1); + Map.Entry found = null; + for (Map.Entry service : services.properties()) { + String repository = repositoryOf(service.getValue().path("image").asText("")); + if (repository.equals(profile.image()) || repository.equals("docker.io/" + profile.image()) + || repository.equals(ghcrImage)) { + found = service; + break; + } + } + if (found == null) { + warnings.add(profile.displayName() + " image reference not detected — ensure your service uses " + + profile.image() + " or " + ghcrImage); + // With one service there is no doubt which one is meant (a locally built image, a + // mirror); with several, checking the wrong one would only mislead. + if (services.size() != 1) { + return new Report(null, errors, warnings); + } + found = services.properties().iterator().next(); + } + + JsonNode service = found.getValue(); + List mounts = mounts(service.path("volumes")); + Map environment = environment(service.path("environment")); + int port = profile.defaultPort(); + + // The container side is what the emulator opens; the host side may be any socket (Podman's, + // a rootless Docker's), so only the target is checked. + if (mounts.stream().noneMatch(m -> DOCKER_SOCK.equals(stripTrailingSlash(m.target())))) { + (dockerSockRequired ? errors : warnings) + .add("Missing " + DOCKER_SOCK + " volume mount — required for " + dockerSockNeededFor); + } + + // With host networking the container's ports are the host's; there is nothing to map. + if (!"host".equals(service.path("network_mode").asText("")) && !publishes(service.path("ports"), port)) { + errors.add("No port mapping for " + port + " found — " + profile.displayName() + " listens on " + port + + " inside the container; map any host port to it, for example \"" + port + ":" + port + "\""); + } + + Mount data = mounts.stream().filter(m -> DATA_DIR.equals(stripTrailingSlash(m.target()))).findFirst().orElse(null); + String storageVar = profile.envVar("STORAGE_MODE"); + String storageMode = environment.get(storageVar); + // A value Compose will substitute (${MODE:-persistent}) cannot be judged from here, and + // neither can one an env_file may set: the file is not read. + boolean storageKnown = storageMode == null + ? service.path("env_file").isMissingNode() || service.path("env_file").isNull() + : !storageMode.contains("${"); + if (data != null && storageKnown && !"persistent".equalsIgnoreCase(storageMode)) { + warnings.add("A volume is mounted at " + DATA_DIR + " but " + storageVar + " is not 'persistent' — " + + "the emulator keeps its state in memory by default, so the volume stays empty"); + } + if (data == null && "persistent".equalsIgnoreCase(storageMode)) { + warnings.add(storageVar + " is 'persistent' but nothing is mounted at " + DATA_DIR + + " — the state is lost when the container is removed"); + } + if (data != null) { + if (data.readOnly()) { + errors.add("The volume at " + DATA_DIR + " is mounted read-only — the emulator cannot save its state there"); + } + String notADirectory = fileWhereADirectoryIsNeeded(data, baseDir); + if (notADirectory != null) { + errors.add("The volume at " + DATA_DIR + " is bound to " + notADirectory + ", which is a file, not a directory"); + } + } + + String tag = tagOf(service.path("image").asText("")); + // The minimum is the AWS emulator's; the other emulators are versioned on their own lines. + if ("aws".equals(profile.name()) && Version.isValid(tag) + && !ImageVersionCheck.meetsMinimum(tag, ImageVersionCheck.MIN_VERSION)) { + warnings.add("Image tag " + tag + " is older than " + ImageVersionCheck.MIN_VERSION + + ", the oldest version this CLI supports — use a newer tag"); + } + + return new Report(found.getKey(), errors, warnings); + } + + /** {@code registry/name:tag@digest} without its tag and digest. */ + public static String repositoryOf(String image) { + String reference = image.strip(); + int digest = reference.indexOf('@'); + if (digest >= 0) reference = reference.substring(0, digest); + int colon = reference.lastIndexOf(':'); + // A colon before the last slash is a registry port, not a tag. + return colon > reference.lastIndexOf('/') ? reference.substring(0, colon) : reference; + } + + /** The tag of an image reference, or an empty string when it has none. */ + public static String tagOf(String image) { + String reference = image.strip(); + int digest = reference.indexOf('@'); + if (digest >= 0) reference = reference.substring(0, digest); + int colon = reference.lastIndexOf(':'); + return colon > reference.lastIndexOf('/') ? reference.substring(colon + 1) : ""; + } + + /** + * Whether one of a service's {@code ports} entries reaches {@code port} inside the container, + * whatever the host side is: {@code 4566}, {@code "4566:4566"}, {@code "5566:4566"}, + * {@code "127.0.0.1:5566:4566/tcp"}, a range that contains it, or the long form's {@code target}. + */ + public static boolean publishes(JsonNode ports, int port) { + for (JsonNode entry : ports) { + if (entry.isObject()) { + if (entry.path("target").asInt(-1) == port && isTcp(entry.path("protocol").asText(""))) return true; + continue; + } + String text = entry.asText("").strip(); + int slash = text.indexOf('/'); + String protocol = slash >= 0 ? text.substring(slash + 1) : ""; + if (slash >= 0) text = text.substring(0, slash); + String container = text.substring(text.lastIndexOf(':') + 1); + if (isTcp(protocol) && inRange(container, port)) return true; + } + return false; + } + + // The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. An + // entry without a protocol is TCP, as Compose reads it. + private static boolean isTcp(String protocol) { + return protocol.isBlank() || "tcp".equalsIgnoreCase(protocol.strip()); + } + + private static boolean inRange(String spec, int port) { + try { + int dash = spec.indexOf('-'); + if (dash < 0) return Integer.parseInt(spec.strip()) == port; + return Integer.parseInt(spec.substring(0, dash).strip()) <= port + && port <= Integer.parseInt(spec.substring(dash + 1).strip()); + } catch (NumberFormatException e) { + return false; // a ${VARIABLE} or something else that is not a number + } + } + + static List mounts(JsonNode volumes) { + List mounts = new ArrayList<>(); + for (JsonNode entry : volumes) { + if (entry.isObject()) { + // In the long form the type says what the source is; a bind's is a host path + // even when it is a bare name like 'data'. + mounts.add(new Mount(entry.path("source").asText(""), entry.path("target").asText(""), + entry.path("read_only").asBoolean(false), "bind".equals(entry.path("type").asText("")))); + continue; + } + String text = entry.asText(""); + // A Windows source (C:\data:/app/data) has a colon of its own after the drive letter. + int from = startsWithDrive(text) ? 2 : 0; + int first = text.indexOf(':', from); + if (first < 0) { + mounts.add(new Mount("", text, false, false)); // an anonymous volume: only the container path + continue; + } + String source = text.substring(0, first); + String rest = text.substring(first + 1); + int second = rest.indexOf(':'); + String target = second < 0 ? rest : rest.substring(0, second); + String mode = second < 0 ? "" : rest.substring(second + 1); + // In the short form a source is a host path when it looks like one; a bare name is a + // named volume. + boolean bind = source.startsWith("/") || source.startsWith(".") || source.startsWith("~") + || startsWithDrive(source); + mounts.add(new Mount(source, target, List.of(mode.split(",")).contains("ro"), bind)); + } + return mounts; + } + + private static boolean startsWithDrive(String text) { + return text.length() > 2 && Character.isLetter(text.charAt(0)) && text.charAt(1) == ':' + && (text.charAt(2) == '\\' || text.charAt(2) == '/'); + } + + /** A service's {@code environment}, from either the mapping or the {@code KEY=value} list form. */ + static Map environment(JsonNode environment) { + Map values = new LinkedHashMap<>(); + if (environment.isObject()) { + for (Map.Entry entry : environment.properties()) { + values.put(entry.getKey(), entry.getValue().asText("")); + } + } else { + for (JsonNode entry : environment) { + String text = entry.asText(""); + int equals = text.indexOf('='); + if (equals > 0) values.put(text.substring(0, equals), text.substring(equals + 1)); + } + } + return values; + } + + private static String stripTrailingSlash(String path) { + return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path; + } + + // Best effort: only a bind source that already exists on this machine can be looked at. A + // named volume, a ${VARIABLE}, a home-relative path Compose expands itself, or a path that + // is not there yet says nothing. + private static String fileWhereADirectoryIsNeeded(Mount mount, Path baseDir) { + if (!mount.bind() || mount.source().isBlank() || mount.source().contains("${") || mount.source().startsWith("~")) { + return null; + } + try { + Path path = baseDir.resolve(mount.source()).normalize(); + return Files.isRegularFile(path) ? path.toString() : null; + } catch (InvalidPathException e) { + return null; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java index b8c2915..2bb9c71 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -1,18 +1,22 @@ package io.floci.cli.commands.config; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.Callable; -import java.util.regex.Pattern; @Command( name = "validate", @@ -21,6 +25,8 @@ import java.util.regex.Pattern; ) public class ConfigValidateCommand implements Callable { + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + protected final ProductProfile profile; private final boolean dockerSockRequired; private final String dockerSockNeededFor; @@ -61,50 +67,68 @@ public class ConfigValidateCommand implements Callable { return 1; } - printer.println(Ansi.bold("Validating") + " " + composeFile); + JsonNode compose = null; + String unreadable = null; + try { + compose = YAML.readTree(content); + if (compose == null || !compose.isObject()) { + unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping"; + } + } catch (IOException e) { + String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable"); + unreadable = "Could not read " + composeFile + " as YAML: " + reason; + } + if (unreadable != null) { + // Structured output always carries the report, so a script reading it gets 'valid: false' + // and the reason rather than nothing. + if (printer.format() != OutputFormat.text) { + printer.structured(document(composeFile, new ComposeCheck.Report(null, List.of(unreadable), List.of()))); + } else { + printer.error(unreadable, "Fix the file's syntax, or pass another with --file."); + } + return 1; + } + + Path baseDir = composeFile.toAbsolutePath().getParent(); + ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir); + + if (printer.format() != OutputFormat.text) { + printer.structured(document(composeFile, report)); + return report.valid() ? 0 : 1; + } + + printer.println(Ansi.bold("Validating") + " " + composeFile + + (report.service() == null ? "" : Ansi.gray(" (service: " + report.service() + ")"))); printer.println(""); - List issues = new ArrayList<>(); - List warnings = new ArrayList<>(); - - // Check for docker.sock mount (an error where the product needs it for core services) - if (!content.contains("/var/run/docker.sock")) { - (dockerSockRequired ? issues : warnings) - .add("Missing /var/run/docker.sock volume mount — required for " + dockerSockNeededFor); - } - - // Check port mapping - int port = profile.defaultPort(); - if (!Pattern.compile(port + "\\s*:\\s*" + port).matcher(content).find()) { - issues.add("Port mapping " + port + ":" + port + " not found — " + profile.displayName() - + " listens on " + port + " by default"); - } - - // Check for the product image - String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1); - if (!content.contains(profile.image()) && !content.contains(ghcrImage)) { - warnings.add(profile.displayName() + " image reference not detected — ensure your service uses " - + profile.image() + " or " + ghcrImage); - } - - for (String issue : issues) { + for (String issue : report.errors()) { printer.println(" " + Ansi.red("✗") + " " + issue); } - for (String warn : warnings) { + for (String warn : report.warnings()) { printer.println(" " + Ansi.yellow("⚠") + " " + warn); } - if (issues.isEmpty() && warnings.isEmpty()) { + if (report.errors().isEmpty() && report.warnings().isEmpty()) { printer.println(" " + Ansi.green("✓") + " Compose file looks good"); } printer.println(""); - if (!issues.isEmpty()) { - printer.println(issues.size() + " error(s) found."); + if (!report.valid()) { + printer.println(report.errors().size() + " error(s) found."); return 1; } return 0; } + private static Map document(Path composeFile, ComposeCheck.Report report) { + Map out = new LinkedHashMap<>(); + out.put("file", composeFile.toString()); + out.put("service", report.service()); + out.put("valid", report.valid()); + out.put("errors", report.errors()); + out.put("warnings", report.warnings()); + return out; + } + private Path resolveComposeFile() { if (file != null) return Path.of(file); for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) { diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java index 6cc1936..f267a41 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -15,7 +15,8 @@ public class ImageVersionCheck implements Check { private final String image; private final DockerClient docker; - private static final String MIN_VERSION = "1.5.0"; + /** The oldest server version this CLI supports. */ + public static final String MIN_VERSION = "1.5.0"; public ImageVersionCheck() { this("floci/floci"); diff --git a/src/test/java/io/floci/cli/unit/ConfigValidateTest.java b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java new file mode 100644 index 0000000..4b7144c --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java @@ -0,0 +1,452 @@ +package io.floci.cli.unit; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.floci.cli.FlociCli; +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.config.ComposeCheck; +import io.floci.cli.config.ProfileStore; +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 java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-055: config validate reads the Compose file's structure and checks the emulator's own service. */ +class ConfigValidateTest { + + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + private static final String NEEDED_FOR = "Lambda, EC2"; + + @TempDir + Path tempDir; + + private ComposeCheck.Report aws(String compose) throws Exception { + return ComposeCheck.analyze(YAML.readTree(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir); + } + + private static String service(String ports, String extra) { + return """ + services: + floci: + image: floci/floci:latest + ports: + - %s + volumes: + - /var/run/docker.sock:/var/run/docker.sock + %s""".formatted(ports, extra); + } + + @Test + void aCompleteServiceHasNothingToReport() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", "")); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + assertEquals(List.of(), r.warnings()); + assertTrue(r.valid()); + } + + /** Any host port works: only the container side has to be the emulator's port. */ + @ParameterizedTest + @ValueSource(strings = {"\"4566:4566\"", "\"5566:4566\"", "\"127.0.0.1:5566:4566\"", "\"5566:4566/tcp\"", + "4566", "\"4566\"", "\"14510-14600:4510-4600\"", "{target: 4566, published: 5566}", + "{target: 4566, published: \"5566\", protocol: tcp}"}) + void everyWayOfMappingTheEmulatorPortIsAccepted(String ports) throws Exception { + assertEquals(List.of(), aws(service(ports, "")).errors(), ports); + } + + @ParameterizedTest + @ValueSource(strings = {"\"4566:8080\"", "\"8080:8080\"", "\"45660:45660\"", "8080", "{target: 8080, published: 4566}", + "\"${HOST_PORT}:${CONTAINER_PORT}\""}) + void aMappingThatDoesNotReachTheEmulatorPortIsAnError(String ports) throws Exception { + List errors = aws(service(ports, "")).errors(); + + assertEquals(1, errors.size(), errors.toString()); + assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0)); + } + + /** The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. */ + @ParameterizedTest + @ValueSource(strings = {"\"4566:4566/udp\"", "{target: 4566, published: 5566, protocol: udp}", "\"5566:4566/sctp\""}) + void aMappingThatIsNotTcpIsAnError(String ports) throws Exception { + List errors = aws(service(ports, "")).errors(); + + assertEquals(1, errors.size(), errors.toString()); + assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0)); + } + + @ParameterizedTest + @ValueSource(strings = {"\"4566:4566/TCP\"", "{target: 4566, published: 5566, protocol: tcp}", "{target: 4566}"}) + void tcpIsAcceptedHoweverItIsSpelled(String ports) throws Exception { + assertEquals(List.of(), aws(service(ports, "")).errors(), ports); + } + + /** What matters is where the socket lands in the container; the host side may be any socket. */ + @ParameterizedTest + @ValueSource(strings = {"/run/user/1000/podman/podman.sock:/var/run/docker.sock", "/var/run/docker.sock:/var/run/docker.sock:ro", + "{type: bind, source: /var/run/docker.sock, target: /var/run/docker.sock}"}) + void aSocketMountedAtTheExpectedPathIsAccepted(String volume) throws Exception { + assertEquals(List.of(), aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors()); + } + + @ParameterizedTest + @ValueSource(strings = {"./notdocker.sock:/tmp/notdocker.sock", "/var/run/docker.sock:/tmp/docker.sock", + "{type: bind, source: /var/run/docker.sock, target: /run/docker.sock}"}) + void aSocketMountedSomewhereElseDoesNotCount(String volume) throws Exception { + List errors = aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors(); + + assertEquals(1, errors.size(), errors.toString()); + assertTrue(errors.get(0).startsWith("Missing /var/run/docker.sock volume mount"), errors.get(0)); + } + + @Test + void hostNetworkingNeedsNoPortMapping() throws Exception { + ComposeCheck.Report r = aws(""" + services: + floci: + image: floci/floci:latest + network_mode: host + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + """); + + assertEquals(List.of(), r.errors()); + } + + /** Another service's port or socket mount must not satisfy the emulator's checks. */ + @Test + void onlyTheEmulatorsOwnServiceCounts() throws Exception { + ComposeCheck.Report r = aws(""" + services: + proxy: + image: nginx + ports: ["4566:4566"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + floci: + image: ghcr.io/floci-io/floci:1.6.0 + """); + + assertEquals("floci", r.service()); + assertEquals(2, r.errors().size(), r.errors().toString()); + assertTrue(r.errors().get(0).contains("docker.sock"), r.errors().toString()); + assertTrue(r.errors().get(1).contains("No port mapping for 4566"), r.errors().toString()); + } + + @Test + void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception { + JsonNode compose = YAML.readTree(""" + services: + gcp: + image: floci/floci-gcp:latest + ports: ["4588:4588"] + """); + + ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.GCP, false, "Cloud Run", tempDir); + + assertTrue(r.valid()); + assertEquals(1, r.warnings().size()); + assertTrue(r.warnings().get(0).contains("docker.sock"), r.warnings().toString()); + } + + @Test + void theLongVolumeFormIsRead() throws Exception { + ComposeCheck.Report r = aws(""" + services: + floci: + image: floci/floci + ports: ["4566:4566"] + volumes: + - type: bind + source: /var/run/docker.sock + target: /var/run/docker.sock + """); + + assertEquals(List.of(), r.errors()); + } + + // ---- storage mode and the data volume ---------------------------------------------------- + + @Test + void aDataVolumeWithoutPersistentStorageIsFlagged() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./data:/app/data\n")); + + assertTrue(r.valid()); + assertEquals(1, r.warnings().size(), r.warnings().toString()); + assertTrue(r.warnings().get(0).contains("FLOCI_STORAGE_MODE is not 'persistent'"), r.warnings().get(0)); + } + + @ParameterizedTest + @ValueSource(strings = {""" + environment: + FLOCI_STORAGE_MODE: persistent + """, """ + environment: + - FLOCI_STORAGE_MODE=persistent + """, """ + environment: + FLOCI_STORAGE_MODE: ${MODE:-memory} + """}) + void aDataVolumeWithPersistentStorageIsFine(String environment) throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", " - floci-data:/app/data\n" + environment)); + + assertEquals(List.of(), r.warnings(), environment); + } + + /** An env_file may set the storage mode; it is not read, so nothing is claimed about it. */ + @ParameterizedTest + @ValueSource(strings = {" env_file: .env\n", " env_file:\n - .env\n - .env.local\n"}) + void anEnvFileMakesTheStorageModeUnknown(String envFile) throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./state:/app/data\n" + envFile)); + + assertEquals(List.of(), r.warnings(), envFile); + } + + /** A mode the file itself spells out is still judged, env_file or not. */ + @Test + void anExplicitStorageModeIsJudgedEvenWithAnEnvFile() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", + " - ./state:/app/data\n env_file: .env\n environment: {FLOCI_STORAGE_MODE: memory}\n")); + + assertEquals(1, r.warnings().size(), r.warnings().toString()); + } + + @Test + void persistentStorageWithoutADataVolumeIsFlagged() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", " environment:\n FLOCI_STORAGE_MODE: persistent\n")); + + assertEquals(1, r.warnings().size(), r.warnings().toString()); + assertTrue(r.warnings().get(0).contains("nothing is mounted at /app/data"), r.warnings().get(0)); + } + + @Test + void theStorageVariableIsTheProductsOwn() throws Exception { + JsonNode compose = YAML.readTree(""" + services: + oci: + image: floci/floci-oci:latest + ports: ["4599:4599"] + volumes: ["./state:/app/data", "/var/run/docker.sock:/var/run/docker.sock"] + environment: + FLOCI_STORAGE_MODE: persistent + """); + + ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.OCI, true, "Functions", tempDir); + + assertTrue(r.warnings().get(0).contains("FLOCI_OCI_STORAGE_MODE is not 'persistent'"), r.warnings().toString()); + } + + @ParameterizedTest + @ValueSource(strings = {" - ./data:/app/data:ro\n", " - floci-data:/app/data/:ro,z\n", + " - {type: bind, source: ./data, target: /app/data, read_only: true}\n"}) + void aReadOnlyDataVolumeIsAnError(String volume) throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", volume + " environment: {FLOCI_STORAGE_MODE: persistent}\n")); + + assertEquals(1, r.errors().size(), r.errors().toString()); + assertTrue(r.errors().get(0).contains("mounted read-only"), r.errors().get(0)); + } + + @Test + void aDataVolumeBoundToAFileIsAnError() throws Exception { + Files.writeString(tempDir.resolve("data"), "not a directory"); + + ComposeCheck.Report r = aws(service("\"4566:4566\"", + " - ./data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n")); + + assertEquals(1, r.errors().size(), r.errors().toString()); + assertTrue(r.errors().get(0).contains("which is a file, not a directory"), r.errors().get(0)); + } + + /** In the long form the type says the source is a host path, even when it is a bare name. */ + @Test + void aLongFormBindToAFileIsAnErrorEvenWithABareName() throws Exception { + Files.writeString(tempDir.resolve("data"), "not a directory"); + + ComposeCheck.Report bind = aws(service("\"4566:4566\"", + " - {type: bind, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n")); + ComposeCheck.Report named = aws(service("\"4566:4566\"", + " - {type: volume, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n")); + ComposeCheck.Report shortNamed = aws(service("\"4566:4566\"", + " - data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n")); + + assertEquals(1, bind.errors().size(), bind.errors().toString()); + assertTrue(bind.errors().get(0).contains("which is a file, not a directory"), bind.errors().get(0)); + assertEquals(List.of(), named.errors(), "a named volume called 'data' is not the file"); + assertEquals(List.of(), shortNamed.errors(), "nor is the short form's bare name"); + } + + /** A directory, a path that does not exist yet and a named volume say nothing against the mount. */ + @ParameterizedTest + @ValueSource(strings = {"./state", "./not-there-yet", "floci-data", "${DATA_DIR}"}) + void otherDataSourcesAreNotJudged(String source) throws Exception { + Files.createDirectories(tempDir.resolve("state")); + + ComposeCheck.Report r = aws(service("\"4566:4566\"", + " - " + source + ":/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n")); + + assertEquals(List.of(), r.errors(), source); + } + + // ---- image --------------------------------------------------------------------------------- + + @Test + void anImageOlderThanTheSupportedMinimumIsFlagged() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", "floci/floci:1.4.2")); + + assertTrue(r.valid()); + assertEquals(1, r.warnings().size(), r.warnings().toString()); + assertTrue(r.warnings().get(0).contains("Image tag 1.4.2 is older than 1.5.0"), r.warnings().get(0)); + } + + @ParameterizedTest + @ValueSource(strings = {"floci/floci", "floci/floci:latest", "floci/floci:1.5.0", "floci/floci:2.0.1", + "ghcr.io/floci-io/floci:1.6.0", "docker.io/floci/floci:1.6.0", "floci/floci:1.6.0@sha256:abc", "floci/floci:nightly"}) + void supportedOrUnversionedImagesAreNotFlagged(String image) throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", image)); + + assertEquals("floci", r.service(), image); + assertEquals(List.of(), r.warnings(), image); + } + + @Test + void repositoriesAndTagsAreSplitAtTheRightColon() { + assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci:1.6.0")); + assertEquals("1.6.0", ComposeCheck.tagOf("registry.local:5000/floci/floci:1.6.0")); + assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci")); + assertEquals("", ComposeCheck.tagOf("registry.local:5000/floci/floci")); + } + + /** One service and no recognisable image (built locally, mirrored): it is still the one to check. */ + @Test + void aSingleServiceIsCheckedEvenWithoutARecognisedImage() throws Exception { + ComposeCheck.Report r = aws(""" + services: + emulator: + build: . + """); + + assertEquals("emulator", r.service()); + assertEquals(2, r.errors().size(), r.errors().toString()); + assertTrue(r.warnings().get(0).contains("image reference not detected"), r.warnings().toString()); + } + + /** Several services and none recognisable: checking one at random would only mislead. */ + @Test + void severalServicesWithoutARecognisedImageAreNotGuessedAt() throws Exception { + ComposeCheck.Report r = aws(""" + services: + web: {image: nginx} + db: {image: postgres} + """); + + assertNull(r.service()); + assertEquals(List.of(), r.errors()); + assertEquals(1, r.warnings().size()); + } + + @Test + void aFileWithoutServicesIsAnError() throws Exception { + ComposeCheck.Report r = aws("version: '3'\n"); + + assertFalse(r.valid()); + assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString()); + } + + // ---- the command --------------------------------------------------------------------------- + + private record Run(int exit, String out, String err) {} + + private Run run(String... args) { + 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 { + int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir.resolve("profiles"))).execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void jsonOutputCarriesTheFindingsAndTheExitCode() throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), """ + services: + floci: + image: floci/floci:1.4.0 + ports: ["4566:8080"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + """); + + Run r = run("config", "validate", "-f", file.toString(), "-o", "json"); + + assertEquals(1, r.exit()); + JsonNode json = new ObjectMapper().readTree(r.out()); + assertEquals(file.toString(), json.path("file").asText()); + assertEquals("floci", json.path("service").asText()); + assertFalse(json.path("valid").asBoolean()); + assertEquals(1, json.path("errors").size()); + assertEquals(1, json.path("warnings").size()); + assertFalse(r.out().contains("Validating"), "no text banner in structured output"); + } + + @Test + void aValidFileExitsZeroInEveryTree() throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), """ + services: + gcp: + image: floci/floci-gcp:latest + ports: ["14588:4588"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + """); + + Run text = run("gcp", "config", "validate", "-f", file.toString()); + Run yaml = run("gcp", "config", "validate", "-f", file.toString(), "-o", "yaml"); + + assertEquals(0, text.exit(), text.out() + text.err()); + assertTrue(text.out().contains("Compose file looks good"), text.out()); + assertEquals(0, yaml.exit()); + assertTrue(yaml.out().contains("valid: true"), yaml.out()); + } + + @Test + void aFileThatIsNotYamlIsReportedWithANextStep() throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), "services: [unterminated\n"); + + Run r = run("config", "validate", "-f", file.toString()); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("as YAML"), r.err()); + assertTrue(r.err().contains("pass another with --file"), r.err()); + } + + /** A script reading the report gets one for a file that cannot be parsed too. */ + @ParameterizedTest + @ValueSource(strings = {"services: [unterminated\n", "- just\n- a list\n", "plain text\n"}) + void aFileThatCannotBeReadStillGetsAStructuredReport(String content) throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), content); + + Run r = run("config", "validate", "-f", file.toString(), "-o", "json"); + + assertEquals(1, r.exit()); + JsonNode json = new ObjectMapper().readTree(r.out()); + assertEquals(file.toString(), json.path("file").asText()); + assertTrue(json.path("service").isNull(), r.out()); + assertFalse(json.path("valid").asBoolean()); + assertEquals(1, json.path("errors").size()); + assertTrue(json.path("errors").get(0).asText().startsWith("Could not read "), r.out()); + assertEquals(0, json.path("warnings").size()); + assertEquals("", r.err()); + } +}