From 885e49f81ac6bdcfed4f2a9e814f7c2ba7062783 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 21:10:58 -0500 Subject: [PATCH 1/4] fix(reset): reset the server a profile or FLOCI_ENDPOINT names, not a local container of the default name (#64) * fix(reset): reset the server a profile or FLOCI_ENDPOINT names, not a local container of the default name With no container selected, an endpoint that came from a profile or the environment was replaced by the port of a container running locally under the default name, so reset --yes could wipe the wrong instance. Such an endpoint is now used as given, like a typed one. Signed-off-by: Hector Ventura * fix(reset): reset nothing when the configured endpoint and a running default container are different servers A profile carries a container name next to its endpoint, and every created profile is seeded with the default one. Using the endpoint outright could then reset a server other than a container the profile also names. When the two disagree neither is picked; the user says which with --endpoint or --container. Signed-off-by: Hector Ventura * fix(reset): require a configured container to be running and to agree with a configured endpoint A container that a profile or FLOCI_CONTAINER supplies is selected even when it has the default name, so a missing or stopped one resets nothing instead of falling back to the endpoint. A configured container and endpoint must be the same server. For a remote Docker host the published port is on the daemon's machine, so the endpoint is compared with that host, and a remote container without an endpoint is not reset through localhost. Signed-off-by: Hector Ventura * fix(reset): treat a Docker daemon on this machine reached over TCP as local tcp://127.0.0.1:2375 is this machine's daemon, so its published ports are local and a reset goes ahead as with a socket. The README sentence about exiting 1 now covers only the cases where reset refuses. Signed-off-by: Hector Ventura * fix(reset): keep a Docker daemon reached over SSH remote, loopback address or not ssh://user@127.0.0.1:2222 is a forwarded port to a VM or another machine. Treating it as local would let reset --yes go to localhost on this machine. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- README.md | 19 +- .../io/floci/cli/commands/ResetCommand.java | 173 +++++++-- .../io/floci/cli/unit/ResetCommandTest.java | 333 ++++++++++++++++++ 3 files changed, 499 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 8ae4af0..aa9bc92 100644 --- a/README.md +++ b/README.md @@ -724,9 +724,20 @@ It calls the emulator's `POST /state/reset`. The AWS, GCP and OCI emulat server without it (currently floci-az) the command says reset is not available and exits 1. Without `--yes` and with no terminal to ask on, it exits 2. -Reset never guesses which server to wipe. An `--endpoint` you type is used as given. A container you -select (`--container`, a profile, or `FLOCI_CONTAINER`) has to be running: if it is missing or -stopped, nothing is reset and the command exits 1 instead of falling back to the default instance. +Reset never guesses which server to wipe: + +- An `--endpoint` you type is used as given. +- A container you select (`--container`, a profile's `container`, or `FLOCI_CONTAINER`) has to be + running. If it is missing or stopped, nothing is reset. +- An endpoint a profile or `FLOCI_ENDPOINT` supplies is used when no container is selected. A + container that happens to run locally under the default name never takes its place. +- When both a container and an endpoint are configured, they have to be the same server. If they + are not, nothing is reset and you are asked to pass `--endpoint` or `--container`. +- A container on a remote Docker host (`DOCKER_HOST=tcp://other-host:...` or `ssh://...`) is only + reset through an endpoint, since its published port is not on this machine. A daemon on this + machine reached over TCP (`tcp://127.0.0.1:2375`) is local. + +When reset refuses to choose a server, the command exits 1 without sending anything. ### `floci config` @@ -936,7 +947,7 @@ Where a command's codes carry a specific meaning a script can rely on: | `update` | updated, or already up to date | the update failed, or `--version` is not a release version; the binary is unchanged | bad flag | | `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed | `--port`, `--pull` or the namespace is not valid | | `stop` | stopped, or was not running | no such container, or Docker failed | bad flag or profile | -| `reset` | state reset | declined, not available on this server, or no running instance to reset | no terminal to ask on and no `--yes` | +| `reset` | state reset | declined, not available on this server, no running instance to reset, or the configuration names two different servers | no terminal to ask on and no `--yes` | | `config validate` | no errors (warnings allowed) | errors found, or the file cannot be read | bad flag | | `config profile ...` | done | not found, already exists, cannot be read, `--port` is out of range, or (for `edit`) no editor is set, the editor failed or the file no longer parses | the profile name is not valid | | `config default-product` | saved | not `aws`, `gcp`, `az` or `oci`, or the file cannot be written | bad flag | diff --git a/src/main/java/io/floci/cli/commands/ResetCommand.java b/src/main/java/io/floci/cli/commands/ResetCommand.java index d1aec6f..232f091 100644 --- a/src/main/java/io/floci/cli/commands/ResetCommand.java +++ b/src/main/java/io/floci/cli/commands/ResetCommand.java @@ -2,6 +2,7 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; +import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; import io.floci.cli.http.FlociException; @@ -11,12 +12,16 @@ import io.floci.cli.output.Glyphs; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import picocli.CommandLine.Model.CommandSpec; import java.io.Console; +import java.net.URI; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; +import java.util.function.UnaryOperator; @Command( name = "reset", @@ -43,14 +48,24 @@ public class ResetCommand implements Callable { /** Test seam: {@code docker} answers the container lookup and {@code prompt} the confirmation. */ public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt) { + this(profile, docker, prompt, System::getenv); + } + + /** Test seam: {@code env} answers whether {@code _CONTAINER} selected the container. */ + public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt, UnaryOperator env) { this.profile = profile; - this.global = new GlobalOptions(profile); + this.global = new GlobalOptions(profile, env); this.docker = docker; this.prompt = prompt; + this.env = env; } private final DockerClient docker; private final Prompt prompt; + private final UnaryOperator env; + + @Spec + CommandSpec spec; /** The person at the terminal, when there is one. */ public interface Prompt { @@ -82,16 +97,28 @@ public class ResetCommand implements Callable { /** * Where this reset acts. Reset deletes data, so unlike the read-only commands it never - * guesses: an {@code --endpoint} the user typed is used as given, and a container the user - * chose must be found running. Falling back to the configured endpoint, as - * {@link GlobalOptions#resolvedEndpoint} does, is right only for the default container: there - * the configured endpoint names the same default instance. + * guesses. In order: + *
    + *
  1. A typed {@code --endpoint} is used as given.
  2. + *
  3. A typed {@code --container} must be found running, and is reset.
  4. + *
  5. A container that a profile or {@code _CONTAINER} supplies must be found + * running too. If the profile or environment also names an endpoint other than the + * default, the two have to be the same server.
  6. + *
  7. With no container supplied, an endpoint from a profile or the environment is used, + * unless a container of the default name runs here and is a different server.
  8. + *
  9. With nothing selected at all, the default container is looked up, falling back to + * the default endpoint, which names the same default instance.
  10. + *
+ * Whenever two things that were configured point at different servers, nothing is reset. */ public Target target() { if (global.typed("--endpoint")) return new Target(global.endpoint, null); - boolean chosen = global.typed("--container") || !profile.defaultContainer().equals(global.container); + boolean typedContainer = global.typed("--container"); + boolean chosen = typedContainer || containerSupplied(); + boolean endpointNamed = namesAServer(global.endpoint, profile); String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check it, or pass --endpoint to name the server to reset."; + Optional info; try { info = docker.inspectContainer(global.container); @@ -99,26 +126,128 @@ public class ResetCommand implements Callable { if (chosen) { return new Target(null, "Could not look up container '" + global.container + "': " + e.getMessage() + how); } - info = Optional.empty(); - } - if (info.isEmpty()) { - return chosen - ? new Target(null, "Container '" + global.container + "' not found, so nothing was reset." + how) - : new Target(global.endpoint, null); - } - if (chosen && !"running".equals(info.get().state())) { - return new Target(null, "Container '" + global.container + "' is not running (state: " - + info.get().state() + "), so nothing was reset." + how); + info = Optional.empty(); // nothing known to contradict what was configured } + boolean running = info.isPresent() && "running".equals(info.get().state()); // By the emulator's own port inside the container, which never changes; the configured // endpoint names the host port, and that differs on every instance but the default one. - Optional published = GlobalOptions.publishedEndpoint(info.get().ports(), profile.defaultPort()); - if (chosen && published.isEmpty()) { - // No port to find it by: the configured endpoint may well be another instance. - return new Target(null, "Container '" + global.container - + "' publishes no port for the emulator, so nothing was reset." + how); + Optional published = running + ? GlobalOptions.publishedEndpoint(info.get().ports(), profile.defaultPort()) + : Optional.empty(); + + if (chosen) { + if (info.isEmpty()) { + return new Target(null, "Container '" + global.container + "' not found, so nothing was reset." + how); + } + if (!running) { + return new Target(null, "Container '" + global.container + "' is not running (state: " + + info.get().state() + "), so nothing was reset." + how); + } + if (published.isEmpty()) { + // No port to find it by: the configured endpoint may well be another instance. + return new Target(null, "Container '" + global.container + + "' publishes no port for the emulator, so nothing was reset." + how); + } } - return new Target(published.orElse(global.endpoint), null); + if (published.isEmpty()) { + // Nothing runs here under that name: the configured endpoint is all there is. + return new Target(global.endpoint, null); + } + + DockerClient.DockerHost daemon = docker.daemonHost(); + boolean remote = isRemote(daemon); + if (endpointNamed && !typedContainer) { + // A container and an endpoint were both configured: they have to be one server. + if (sameServer(published.get(), global.endpoint, daemon)) return new Target(global.endpoint, null); + return new Target(null, "The configured endpoint is " + global.endpoint + ", but container '" + + global.container + "' is running at " + whereItRuns(published.get(), daemon) + + ". They are different servers, so nothing was reset." + + "\nPass --endpoint or --container to say which one to reset."); + } + if (remote) { + // The port was published on the daemon's machine. 'localhost' here would be this + // one, and whatever answers on that port here is not the container that was found. + return new Target(null, "Container '" + global.container + "' runs on the remote Docker host " + + daemon.raw() + ", so its address is not known here and nothing was reset." + + "\nPass --endpoint with the address the emulator is reached at."); + } + return new Target(published.get(), null); + } + + // Whether something other than the default name picked the container: a profile that sets + // one (every created profile does), _CONTAINER, or simply a different name. + private boolean containerSupplied() { + if (!profile.defaultContainer().equals(global.container)) return true; + if (env.apply(profile.envVar("CONTAINER")) != null) return true; + return global.profile != null + && ProfileDefaultValueProvider.of(spec).resolved().map(p -> p.container != null).orElse(false); + } + + private static String whereItRuns(String published, DockerClient.DockerHost daemon) { + return isRemote(daemon) + ? "port " + URI.create(published).getPort() + " of the remote Docker host " + daemon.raw() + : published; + } + + /** + * Whether the daemon runs on another machine. Docker reached over TCP usually does, but + * {@code tcp://127.0.0.1:2375} is this machine's daemon on a socket of another kind, and its + * published ports are local like any other's. SSH is always remote: a loopback address there + * ({@code ssh://user@127.0.0.1:2222}) is a forwarded port to a VM or another machine, not a + * daemon on this one. + */ + public static boolean isRemote(DockerClient.DockerHost daemon) { + if (daemon.kind() != DockerClient.Kind.TCP) return false; + try { + URI address = URI.create(daemon.raw()); + if ("ssh".equalsIgnoreCase(address.getScheme())) return true; + String host = address.getHost(); + return host == null || !thisMachine(host); + } catch (IllegalArgumentException | NullPointerException e) { + return true; // cannot tell: the careful answer + } + } + + private static boolean thisMachine(String host) { + String name = host.toLowerCase(Locale.ROOT); + return name.equals("localhost") || name.equals("127.0.0.1") || name.equals("[::1]") || name.equals("::1") + || name.equals("0.0.0.0") || name.equals("localhost.floci.io"); + } + + /** + * Whether {@code configured} is the server a container publishes at {@code published} + * ({@code http://localhost:} as docker reports it). The port has to match. For a daemon + * on this machine the configured host has to mean this machine; for a remote one it has to be + * the daemon's host, since that is where the port was published. + */ + public static boolean sameServer(String published, String configured, DockerClient.DockerHost daemon) { + try { + URI there = URI.create(withoutTrailingSlashes(configured)); + if (URI.create(published).getPort() != there.getPort()) return false; + String host = there.getHost() == null ? "" : there.getHost(); + if (isRemote(daemon)) { + String daemonHost = URI.create(daemon.raw()).getHost(); + return daemonHost != null && daemonHost.equalsIgnoreCase(host); + } + return thisMachine(host); + } catch (IllegalArgumentException | NullPointerException e) { + return false; + } + } + + /** + * Whether {@code endpoint} is something other than the product's default, that is, whether a + * profile or the environment pointed this command at a particular server. A trailing slash + * does not make it a different one. + */ + public static boolean namesAServer(String endpoint, ProductProfile product) { + return endpoint != null && !withoutTrailingSlashes(endpoint).equals(product.defaultEndpoint()); + } + + private static String withoutTrailingSlashes(String url) { + String trimmed = url.strip(); + while (trimmed.endsWith("/")) trimmed = trimmed.substring(0, trimmed.length() - 1); + return trimmed; } @Override diff --git a/src/test/java/io/floci/cli/unit/ResetCommandTest.java b/src/test/java/io/floci/cli/unit/ResetCommandTest.java index 38288e1..2a33485 100644 --- a/src/test/java/io/floci/cli/unit/ResetCommandTest.java +++ b/src/test/java/io/floci/cli/unit/ResetCommandTest.java @@ -7,12 +7,15 @@ import io.floci.cli.commands.ResetCommand; 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 io.floci.cli.docker.DockerException; 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 org.junit.jupiter.params.provider.ValueSource; import picocli.CommandLine; @@ -20,11 +23,13 @@ import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; 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 java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; @@ -127,7 +132,14 @@ class ResetCommandTest { // ---- which server a reset acts on ------------------------------------------------------- + private static final DockerHost LOCAL = new DockerHost(Kind.UNIX, "/var/run/docker.sock", null); + private static DockerClient dockerWith(String name, String state, String ports) { + return dockerWith(name, state, ports, LOCAL); + } + + /** A docker reached through {@code daemon} that holds one container. */ + private static DockerClient dockerWith(String name, String state, String ports, DockerHost daemon) { return new DockerClient() { @Override public Optional inspectContainer(String asked) { @@ -135,6 +147,11 @@ class ResetCommandTest { ? Optional.of(new ContainerInfo("abc", name, "floci/floci:latest", state, ports)) : Optional.empty(); } + + @Override + public DockerHost daemonHost() { + return daemon; + } }; } @@ -167,6 +184,322 @@ class ResetCommandTest { assertNull(target.error()); } + private ResetCommand.Target targetWithProfile(DockerClient docker, String yaml, String... args) throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("p.yaml"), yaml); + ResetCommand reset = new ResetCommand(ProductProfile.AWS, docker, NOBODY); + List all = new ArrayList<>(List.of("--profile", "p")); + all.addAll(List.of(args)); + new CommandLine(reset) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .parseArgs(all.toArray(String[]::new)); + return reset.target(); + } + + /** + * BL-084: an endpoint from a profile names a server, and a container that happens to run + * locally under the default name must never take its place. A created profile also carries + * that default container name, so when the two are different servers nothing is reset. + */ + @Test + void anEndpointFromAProfileIsNeverReplacedByTheLocalDefaultContainer() throws Exception { + DockerClient local = dockerWith("floci", "running", "4566->4566/tcp"); + + ResetCommand.Target target = targetWithProfile(local, "container: floci\nendpoint: http://remote-host:4566\n"); + + assertNull(target.endpoint(), "neither server is picked"); + assertTrue(target.error().contains("The configured endpoint is http://remote-host:4566"), target.error()); + assertTrue(target.error().contains("container 'floci' is running at http://localhost:4566"), target.error()); + assertTrue(target.error().contains("so nothing was reset."), target.error()); + assertTrue(target.error().contains("Pass --endpoint or --container "), target.error()); + } + + /** The same holds with the container name left out of the profile, or a local port that differs. */ + @ParameterizedTest + @ValueSource(strings = {"endpoint: http://remote-host:4566\n", "endpoint: http://localhost:14566\n", + "container: floci\nendpoint: http://localhost:14566\nport: 14566\n"}) + void aRunningDefaultContainerThatIsAnotherServerStopsTheReset(String yaml) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "4566->4566/tcp"), yaml); + + assertNull(target.endpoint(), yaml); + assertTrue(target.error().contains("They are different servers, so nothing was reset."), target.error()); + } + + /** No local container to contradict it: the endpoint the profile names is the server. */ + @ParameterizedTest + @CsvSource({"something-else, running, ''", "floci, exited, ''", "floci, running, '18080->8080/tcp'"}) + void anEndpointFromAProfileIsUsedWhenNoLocalContainerContradictsIt(String name, String state, String ports) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith(name, state, ports), "endpoint: http://remote-host:4566\n"); + + assertNull(target.error(), target.error()); + assertEquals("http://remote-host:4566", target.endpoint()); + } + + /** The endpoint and the running container are one server: the profile is consistent, reset goes ahead. */ + @ParameterizedTest + @ValueSource(strings = {"http://localhost:14566", "http://127.0.0.1:14566", "http://localhost.floci.io:14566", "http://localhost:14566/"}) + void anEndpointThatIsTheRunningContainerIsUsed(String endpoint) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp"), + "container: floci\nport: 14566\nendpoint: " + endpoint + "\n"); + + assertNull(target.error(), target.error()); + assertEquals(endpoint, target.endpoint()); + } + + @Test + void forALocalDaemonTheSameServerIsTheSamePortOnThisMachine() { + assertTrue(ResetCommand.sameServer("http://localhost:4566", "http://127.0.0.1:4566", LOCAL)); + assertTrue(ResetCommand.sameServer("http://localhost:4566", "https://localhost:4566/", LOCAL)); + assertFalse(ResetCommand.sameServer("http://localhost:4566", "http://localhost:14566", LOCAL)); + assertFalse(ResetCommand.sameServer("http://localhost:4566", "http://remote-host:4566", LOCAL)); + assertFalse(ResetCommand.sameServer("http://localhost:4566", "not a url", LOCAL)); + } + + /** A remote daemon publishes the port on its own machine: that host, not this one, is the server's. */ + @ParameterizedTest + @CsvSource({ + "ssh://deploy@remote-host, http://remote-host:14566, true", + "tcp://remote-host:2375, http://remote-host:14566, true", + "tcp://remote-host:2375, http://REMOTE-HOST:14566/, true", + "ssh://deploy@remote-host, http://localhost:14566, false", + "ssh://deploy@remote-host, http://other-host:14566, false", + "ssh://deploy@remote-host, http://remote-host:4566, false"}) + void forARemoteDaemonTheSameServerIsTheSamePortOnTheDaemonsHost(String dockerHost, String endpoint, boolean same) { + DockerHost remote = DockerClient.parseDockerHost(dockerHost, null, "Linux"); + + assertEquals(same, ResetCommand.sameServer("http://localhost:14566", endpoint, remote)); + } + + /** Docker on this machine reached over TCP is local: its published ports are this machine's. */ + @ParameterizedTest + @CsvSource({ + "tcp://127.0.0.1:2375, false", + "tcp://localhost:2375, false", + "tcp://[::1]:2376, false", + "unix:///var/run/docker.sock, false", + "tcp://remote-host:2375, true", + "ssh://deploy@remote-host, true", + "ssh://user@127.0.0.1:2222, true", + "ssh://localhost, true", + "tcp://192.168.1.20:2375, true"}) + void onlyADaemonOnAnotherMachineIsRemote(String dockerHost, boolean remote) { + assertEquals(remote, ResetCommand.isRemote(DockerClient.parseDockerHost(dockerHost, null, "Linux"))); + } + + @Test + void aLocalTcpDaemonResetsItsContainerLikeASocketOne() throws Exception { + DockerHost localTcp = DockerClient.parseDockerHost("tcp://127.0.0.1:2375", null, "Linux"); + + ResetCommand.Target plain = targetOf(dockerWith("floci", "running", "4566->4566/tcp", localTcp)); + ResetCommand.Target withProfile = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp", localTcp), + "container: floci\nport: 14566\nendpoint: http://localhost:14566\n"); + + assertEquals("http://localhost:4566", plain.endpoint()); + assertNull(withProfile.error(), withProfile.error()); + assertEquals("http://localhost:14566", withProfile.endpoint()); + assertTrue(ResetCommand.sameServer("http://localhost:14566", "http://localhost:14566", localTcp)); + } + + /** SSH to a loopback address is a forwarded port to somewhere else: never reset through localhost. */ + @Test + void anSshDaemonOnALoopbackAddressIsStillRemote() { + DockerHost forwarded = DockerClient.parseDockerHost("ssh://user@127.0.0.1:2222", null, "Linux"); + + ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp", forwarded)); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("runs on the remote Docker host ssh://user@127.0.0.1:2222"), target.error()); + } + + /** A profile for an instance on a remote Docker host: its endpoint and its container are one server. */ + @Test + void aRemoteInstanceWhoseEndpointMatchesIsReset() throws Exception { + DockerHost remote = DockerClient.parseDockerHost("ssh://deploy@remote-host", null, "Linux"); + + ResetCommand.Target target = targetWithProfile(dockerWith("floci", "running", "14566->4566/tcp", remote), + "container: floci\nport: 14566\nendpoint: http://remote-host:14566\n"); + + assertNull(target.error(), target.error()); + assertEquals("http://remote-host:14566", target.endpoint()); + } + + /** On a remote daemon 'localhost:' is this machine, not the container: without an endpoint nothing is reset. */ + @ParameterizedTest + @ValueSource(strings = {"floci", "floci-b"}) + void aRemoteContainerWithoutAnEndpointResetsNothing(String container) { + DockerHost remote = DockerClient.parseDockerHost("tcp://remote-host:2375", null, "Linux"); + List args = container.equals("floci") ? List.of() : List.of("--container", container); + + ResetCommand.Target target = targetOf(dockerWith(container, "running", "4566->4566/tcp", remote), args.toArray(String[]::new)); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("runs on the remote Docker host tcp://remote-host:2375"), target.error()); + assertTrue(target.error().contains("Pass --endpoint "), target.error()); + } + + /** + * A profile that names a container, even one with the default name, has selected it: when it is + * not running, the profile's endpoint is not a fallback and nothing is reset. + */ + @ParameterizedTest + @CsvSource({"something-else, running, not found", "floci, exited, is not running"}) + void aContainerFromAProfileMustBeRunningEvenWithTheDefaultName(String name, String state, String reason) throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith(name, state, ""), + "container: floci\nendpoint: http://remote-host:4566\n"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("Container 'floci' " + reason), target.error()); + assertTrue(target.error().contains("so nothing was reset."), target.error()); + } + + /** The environment selects a container the same way a profile does. */ + @Test + void aContainerFromTheEnvironmentMustBeRunningToo() { + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("something-else", "running", ""), NOBODY, + Map.of("FLOCI_CONTAINER", "floci", "FLOCI_ENDPOINT", "http://remote-host:4566")::get); + new CommandLine(reset).parseArgs(); + + ResetCommand.Target target = reset.target(); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("Container 'floci' not found, so nothing was reset."), target.error()); + } + + /** FLOCI_ENDPOINT alone names a server, like an endpoint-only profile. */ + @Test + void anEndpointFromTheEnvironmentIsUsedAsGiven() { + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("something-else", "running", ""), NOBODY, + Map.of("FLOCI_ENDPOINT", "http://remote-host:4566")::get); + new CommandLine(reset).parseArgs(); + + assertEquals("http://remote-host:4566", reset.target().endpoint()); + } + + /** When docker cannot be asked, nothing contradicts the endpoint the user configured. */ + @Test + void aDockerFailureDoesNotOverrideAConfiguredEndpoint() throws Exception { + DockerClient broken = new DockerClient() { + @Override + public Optional inspectContainer(String name) throws DockerException { + throw new DockerException("Cannot connect to the Docker daemon"); + } + }; + + assertEquals("http://remote-host:4566", targetWithProfile(broken, "endpoint: http://remote-host:4566\n").endpoint()); + } + + /** A profile's container and its endpoint have to be one server, whatever the container is called. */ + @Test + void aProfileWhoseContainerAndEndpointDisagreeResetsNothing() throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"), + "container: floci-b\nendpoint: http://localhost:14566\n"); + + assertNull(target.endpoint()); + assertTrue(target.error().contains("container 'floci-b' is running at http://localhost:24566"), target.error()); + assertTrue(target.error().contains("They are different servers, so nothing was reset."), target.error()); + } + + /** A profile made by 'config profile create --container --port' keeps the default endpoint: no conflict. */ + @Test + void aProfileWithTheDefaultEndpointIsFoundThroughItsContainer() throws Exception { + ResetCommand.Target target = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"), + "container: floci-b\nport: 24566\nendpoint: http://localhost:4566\n"); + + assertNull(target.error(), target.error()); + assertEquals("http://localhost:24566", target.endpoint()); + } + + /** A typed flag wins over the profile's endpoint, as everywhere else. */ + @Test + void typedFlagsWinOverAProfilesEndpoint() throws Exception { + String yaml = "endpoint: http://remote-host:4566\n"; + + ResetCommand.Target typedEndpoint = targetWithProfile(dockerWith("floci", "running", "4566->4566/tcp"), yaml, + "--endpoint", "http://other-host:4566"); + ResetCommand.Target typedContainer = targetWithProfile(dockerWith("floci-b", "running", "24566->4566/tcp"), yaml, + "--container", "floci-b"); + + assertEquals("http://other-host:4566", typedEndpoint.endpoint()); + assertEquals("http://localhost:24566", typedContainer.endpoint()); + } + + /** The environment's endpoint counts the same way; what matters is that it is not the default. */ + @ParameterizedTest + @CsvSource({ + "http://remote-host:4566, true", + "http://localhost:14566, true", + "https://localhost:4566, true", + "http://localhost:4566, false", + "http://localhost:4566/, false", + "' http://localhost:4566// ', false"}) + void anEndpointOtherThanTheDefaultNamesAServer(String endpoint, boolean names) { + assertEquals(names, ResetCommand.namesAServer(endpoint, ProductProfile.AWS)); + } + + @Test + void eachProductHasItsOwnDefaultEndpoint() { + assertFalse(ResetCommand.namesAServer("http://localhost:4588", ProductProfile.GCP)); + assertTrue(ResetCommand.namesAServer("http://localhost:4566", ProductProfile.GCP)); + assertFalse(ResetCommand.namesAServer(null, ProductProfile.OCI)); + } + + /** End to end with --yes: the request goes to the profile's server, not to the local container's port. */ + @Test + void yesWithAProfileEndpointPostsToThatEndpoint() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("p.yaml"), "endpoint: http://127.0.0.1:" + server.getAddress().getPort() + "\n"); + // A stopped container of the default name does not contradict the profile's endpoint. + ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("floci", "exited", ""), NOBODY); + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + System.setErr(new PrintStream(errBuf)); + int exit; + try { + exit = new CommandLine(reset) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .execute("--yes", "--profile", "p"); + } finally { + System.setOut(out); + System.setErr(err); + } + + assertEquals(0, exit, errBuf.toString()); + assertEquals(List.of("POST /_floci/state/reset"), requests); + } + + /** End to end with --yes: two different servers, no request at all. */ + @Test + void yesWithAContradictingLocalContainerSendsNothing() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("p.yaml"), "endpoint: http://127.0.0.1:" + server.getAddress().getPort() + "\n"); + int elsewhere; + try (ServerSocket socket = new ServerSocket(0)) { + elsewhere = socket.getLocalPort(); + } + ResetCommand reset = new ResetCommand(ProductProfile.AWS, + dockerWith("floci", "running", elsewhere + "->4566/tcp"), NOBODY); + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + System.setErr(new PrintStream(errBuf)); + int exit; + try { + exit = new CommandLine(reset) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .execute("--yes", "--profile", "p"); + } finally { + System.setOut(out); + System.setErr(err); + } + + assertEquals(1, exit); + assertEquals(List.of(), requests, "nothing was reset"); + assertTrue(errBuf.toString().contains("They are different servers"), errBuf.toString()); + } + @Test void theDefaultContainerIsFoundThroughItsPortMapping() { ResetCommand.Target target = targetOf(dockerWith("floci", "running", "14566->4566/tcp")); From 68d28d49ef410b07c31b067f4d465958c730986d Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 21:12:20 -0500 Subject: [PATCH 2/4] fix(config): accept Compose files that use YAML anchors and merge keys in config validate (#65) * fix(config): accept Compose files that use YAML anchors and merge keys in config validate config validate read the file without resolving anchors, aliases or merge keys, so a service built from an anchor looked empty and a valid file got two errors and exit 1. The file is now read with its anchors resolved, the way Compose reads it. snakeyaml was already on the classpath through Jackson's YAML module and is now declared, since it is used directly. Signed-off-by: Hector Ventura * fix(config): bound alias expansion and read Compose scalars as YAML 1.2 in config validate A few nested aliases can describe millions of values; the reader now stops at 100000 and reports the file instead of using up memory. Only true and false are booleans, so a service named on, off, yes or no keeps its name. Signed-off-by: Hector Ventura * fix(config): report a self-referencing alias instead of overflowing the stack in config validate A recursive alias is a collection that contains itself. The reader now stops at 64 levels of nesting and reports the file, so the command still prints its validation report. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- pom.xml | 8 + .../config/ConfigValidateCommand.java | 6 +- .../floci/cli/commands/config/YamlTree.java | 126 +++++++ .../io/floci/cli/unit/ConfigValidateTest.java | 320 +++++++++++++++++- 4 files changed, 452 insertions(+), 8 deletions(-) create mode 100644 src/main/java/io/floci/cli/commands/config/YamlTree.java diff --git a/pom.xml b/pom.xml index 4fee441..fc2aace 100644 --- a/pom.xml +++ b/pom.xml @@ -50,6 +50,14 @@ jackson-dataformat-yaml ${jackson.version} + + + org.yaml + snakeyaml + 2.3 + 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 d792f94..af11486 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -1,8 +1,6 @@ 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; @@ -26,8 +24,6 @@ import java.util.concurrent.Callable; ) 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; @@ -71,7 +67,7 @@ public class ConfigValidateCommand implements Callable { JsonNode compose = null; String unreadable = null; try { - compose = YAML.readTree(content); + compose = YamlTree.read(content); if (compose == null || !compose.isObject()) { unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping"; } diff --git a/src/main/java/io/floci/cli/commands/config/YamlTree.java b/src/main/java/io/floci/cli/commands/config/YamlTree.java new file mode 100644 index 0000000..4f27ae1 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/YamlTree.java @@ -0,0 +1,126 @@ +package io.floci.cli.commands.config; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.representer.Representer; +import org.yaml.snakeyaml.resolver.Resolver; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Reads a YAML document into a tree with its anchors, aliases and merge keys resolved, the way a + * YAML consumer such as Compose sees it. Jackson's own {@code readTree} leaves them unresolved: + * {@code volumes: *common} arrives as the string "common" and {@code <<: *base} as a field named + * {@code <<}, so a service built from an anchor looks empty. Its parser also drops anchors on + * scalars ({@code image: &img ...}), so they cannot be resolved on top of it either; SnakeYAML, + * which Jackson's YAML module is built on, does all three. + */ +public final class YamlTree { + + /** + * The most nodes a document may have once its aliases are expanded. An alias costs nothing in + * the file and a whole copy in the tree, so a few nested aliases describe millions of nodes; + * no Compose file comes near this, and stopping here keeps such a file from using up memory. + */ + static final int MAX_NODES = 100_000; + + /** + * The deepest nesting a document may have. A recursive alias ({@code x: &a [*a]}) is a list + * that contains itself: without a limit, copying it would recurse until the stack overflows, + * long before the node budget is spent. Real Compose files are a handful of levels deep. + */ + static final int MAX_DEPTH = 64; + + private static final JsonNodeFactory NODES = JsonNodeFactory.instance; + + private YamlTree() {} + + /** + * Scalar typing as Compose reads it (YAML 1.2): only {@code true} and {@code false} are + * booleans. SnakeYAML's default follows YAML 1.1, where {@code yes}, {@code no}, {@code on} + * and {@code off} are booleans too, which would rename a service called {@code on} to + * {@code true}. Timestamps are left as text for the same reason: nothing here wants a date. + */ + private static final class ComposeResolver extends Resolver { + + private static final Pattern TRUE_OR_FALSE = Pattern.compile("^(?:true|True|TRUE|false|False|FALSE)$"); + + @Override + protected void addImplicitResolvers() { + addImplicitResolver(Tag.BOOL, TRUE_OR_FALSE, "tTfF"); + addImplicitResolver(Tag.INT, INT, "-+0123456789"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.MERGE, MERGE, "<"); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + } + } + + /** + * The first document of {@code yaml}; a missing node for an empty one. + * + * @throws IOException when the text is not YAML, expands to more than {@link #MAX_NODES} + * nodes or nests deeper than {@link #MAX_DEPTH}, with a one-line reason + */ + public static JsonNode read(String yaml) throws IOException { + Object first; + try { + // SafeConstructor builds only maps, lists and scalars, never arbitrary classes. + LoaderOptions options = new LoaderOptions(); + DumperOptions unused = new DumperOptions(); + Yaml reader = new Yaml(new SafeConstructor(options), new Representer(unused), unused, options, new ComposeResolver()); + Iterator documents = reader.loadAll(yaml).iterator(); + first = documents.hasNext() ? documents.next() : null; + } catch (YAMLException | IllegalArgumentException e) { + String reason = e.getMessage() == null ? "not valid YAML" : e.getMessage().lines().findFirst().orElse("not valid YAML"); + throw new IOException(reason); + } + return first == null ? NODES.missingNode() : tree(first, new int[] {MAX_NODES}, 0); + } + + // SnakeYAML hands back shared objects for aliases; the tree gets a copy at each use, counted + // against the budget so the copying cannot run away. + private static JsonNode tree(Object value, int[] budget, int depth) throws IOException { + if (depth > MAX_DEPTH) { + throw new IOException("the document is nested more than " + MAX_DEPTH + + " levels deep, or an alias refers to itself"); + } + if (--budget[0] < 0) { + throw new IOException("the document has more than " + MAX_NODES + " values once its aliases are expanded"); + } + if (value == null) return NODES.nullNode(); + if (value instanceof Map map) { + ObjectNode object = NODES.objectNode(); + for (Map.Entry entry : map.entrySet()) { + object.set(String.valueOf(entry.getKey()), tree(entry.getValue(), budget, depth + 1)); + } + return object; + } + if (value instanceof Collection items) { + ArrayNode array = NODES.arrayNode(); + for (Object item : items) { + array.add(tree(item, budget, depth + 1)); + } + return array; + } + if (value instanceof Boolean flag) return NODES.booleanNode(flag); + if (value instanceof Integer number) return NODES.numberNode(number); + if (value instanceof Long number) return NODES.numberNode(number); + if (value instanceof BigInteger number) return NODES.numberNode(number); + if (value instanceof Double number) return NODES.numberNode(number); + return NODES.textNode(String.valueOf(value)); + } +} diff --git a/src/test/java/io/floci/cli/unit/ConfigValidateTest.java b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java index 4b7144c..0c32a49 100644 --- a/src/test/java/io/floci/cli/unit/ConfigValidateTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigValidateTest.java @@ -6,6 +6,7 @@ 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.commands.config.YamlTree; import io.floci.cli.config.ProfileStore; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -13,6 +14,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; @@ -30,7 +32,7 @@ class ConfigValidateTest { Path tempDir; private ComposeCheck.Report aws(String compose) throws Exception { - return ComposeCheck.analyze(YAML.readTree(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir); + return ComposeCheck.analyze(YamlTree.read(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir); } private static String service(String ports, String extra) { @@ -142,7 +144,7 @@ class ConfigValidateTest { @Test void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception { - JsonNode compose = YAML.readTree(""" + JsonNode compose = YamlTree.read(""" services: gcp: image: floci/floci-gcp:latest @@ -228,7 +230,7 @@ class ConfigValidateTest { @Test void theStorageVariableIsTheProductsOwn() throws Exception { - JsonNode compose = YAML.readTree(""" + JsonNode compose = YamlTree.read(""" services: oci: image: floci/floci-oci:latest @@ -359,6 +361,318 @@ class ConfigValidateTest { assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString()); } + // ---- anchors, aliases and merge keys --------------------------------------------------------- + + /** BL-085: a service built from an anchor with a merge key is read the way Compose reads it. */ + @Test + void aServiceBuiltFromAnAnchorIsReadInFull() throws Exception { + ComposeCheck.Report r = aws(""" + x-floci: &floci + image: floci/floci:latest + ports: + - "4566:4566" + volumes: + - /var/run/docker.sock:/var/run/docker.sock + services: + floci: + <<: *floci + """); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + assertEquals(List.of(), r.warnings()); + } + + @Test + void anAliasedListIsReadAsTheList() throws Exception { + ComposeCheck.Report r = aws(""" + x-volumes: &v + - /var/run/docker.sock:/var/run/docker.sock + x-ports: &p ["5566:4566"] + services: + floci: + image: floci/floci:latest + ports: *p + volumes: *v + """); + + assertEquals(List.of(), r.errors()); + } + + /** A key written in the service wins over the one a merge brings in, wherever '<<' stands. */ + @Test + void anExplicitKeyOverridesTheMergedOne() throws Exception { + ComposeCheck.Report r = aws(""" + x-base: &base + image: nginx + ports: ["8080:8080"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + services: + floci: + image: floci/floci:latest + ports: ["4566:4566"] + <<: *base + """); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + } + + @Test + void aMergeOfSeveralMappingsTakesTheEarlierOneFirst() throws Exception { + JsonNode tree = YamlTree.read(""" + a: &a {x: 1, y: 1} + b: &b {y: 2, z: 2} + c: + <<: [*a, *b] + z: 3 + """); + + assertEquals(1, tree.path("c").path("x").asInt()); + assertEquals(1, tree.path("c").path("y").asInt()); + assertEquals(3, tree.path("c").path("z").asInt()); + assertFalse(tree.path("c").has("<<")); + } + + /** An alias is a copy: what is checked for one service does not leak into the anchor's owner. */ + @Test + void anAnchoredServiceCanBeReusedByAnother() throws Exception { + ComposeCheck.Report r = aws(""" + services: + floci: &main + image: floci/floci:latest + ports: ["4566:4566"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + floci-b: + <<: *main + ports: ["14566:4566"] + """); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + } + + @Test + void scalarsKeepTheirTypesAndPlainDocumentsReadAsBefore() throws Exception { + JsonNode tree = YamlTree.read(""" + name: floci + port: 4566 + ratio: 1.5 + enabled: true + nothing: null + tag: "1.6.0" + list: [1, "two", {three: 3}] + anchored: &s shared + again: *s + """); + + assertEquals("floci", tree.path("name").asText()); + assertTrue(tree.path("port").isIntegralNumber()); + assertEquals(4566, tree.path("port").asInt()); + assertEquals(1.5, tree.path("ratio").asDouble()); + assertTrue(tree.path("enabled").isBoolean()); + assertTrue(tree.path("nothing").isNull()); + assertTrue(tree.path("tag").isTextual()); + assertEquals(3, tree.path("list").get(2).path("three").asInt()); + assertEquals("shared", tree.path("again").asText()); + } + + /** + * Sixteen levels, three aliases each: 48 aliases, under the parser's own limit, and 43 million + * values once expanded. The reader stops at its budget instead of building that tree. + */ + @Test + void aFileThatExpandsToMillionsOfValuesIsRefusedQuickly() { + StringBuilder bomb = new StringBuilder("x-0: &l0 [a, b, c]\n"); + for (int level = 1; level <= 16; level++) { + bomb.append("x-").append(level).append(": &l").append(level) + .append(" [*l").append(level - 1).append(", *l").append(level - 1).append(", *l").append(level - 1).append("]\n"); + } + bomb.append("services:\n floci:\n image: floci/floci:latest\n"); + + long start = System.nanoTime(); + IOException e = assertThrows(IOException.class, () -> YamlTree.read(bomb.toString())); + long elapsedMs = (System.nanoTime() - start) / 1_000_000; + + assertTrue(e.getMessage().contains("once its aliases are expanded"), e.getMessage()); + assertTrue(elapsedMs < 5_000, "took " + elapsedMs + " ms"); + } + + @Test + void theCommandReportsSuchAFileInsteadOfRunningOutOfMemory() throws Exception { + StringBuilder bomb = new StringBuilder("x-0: &l0 [a, b, c]\n"); + for (int level = 1; level <= 16; level++) { + bomb.append("x-").append(level).append(": &l").append(level) + .append(" [*l").append(level - 1).append(", *l").append(level - 1).append(", *l").append(level - 1).append("]\n"); + } + Path file = Files.writeString(tempDir.resolve("compose.yml"), bomb + "services: {}\n"); + + Run r = run("config", "validate", "-f", file.toString(), "-o", "json"); + + assertEquals(1, r.exit()); + JsonNode json = new ObjectMapper().readTree(r.out()); + assertFalse(json.path("valid").asBoolean()); + assertTrue(json.path("errors").get(0).asText().contains("once its aliases are expanded"), r.out()); + } + + /** + * An alias that refers to itself is a collection containing itself. It is reported like any + * other unreadable file, not left to overflow the stack. + */ + @ParameterizedTest + @ValueSource(strings = {"x: &a [*a]\n", "x: &a {self: *a}\n", "x: &a [[[*a]]]\nservices: {}\n"}) + void aRecursiveAliasIsReportedNotFollowed(String yaml) { + IOException e = assertThrows(IOException.class, () -> YamlTree.read(yaml)); + + assertTrue(e.getMessage().contains("an alias refers to itself"), e.getMessage()); + } + + @Test + void theCommandReportsARecursiveAlias() throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), "x-loop: &a [*a]\nservices: {}\n"); + + Run json = run("config", "validate", "-f", file.toString(), "-o", "json"); + Run text = run("config", "validate", "-f", file.toString()); + + assertEquals(1, json.exit()); + assertFalse(new ObjectMapper().readTree(json.out()).path("valid").asBoolean()); + assertTrue(json.out().contains("an alias refers to itself"), json.out()); + assertEquals(1, text.exit()); + assertTrue(text.err().contains("an alias refers to itself"), text.err()); + assertFalse(text.err().contains("StackOverflow"), text.err()); + } + + /** Ordinary nesting, well past what a Compose file uses, is still read. */ + @Test + void deepButFiniteNestingIsRead() throws Exception { + StringBuilder yaml = new StringBuilder("a: "); + yaml.append("[".repeat(40)).append("x").append("]".repeat(40)).append("\n"); + + assertTrue(YamlTree.read(yaml.toString()).path("a").isArray()); + } + + /** A real Compose file with many aliases stays far below the budget. */ + @Test + void manyOrdinaryAliasesAreFine() throws Exception { + StringBuilder compose = new StringBuilder("x-env: &env {A: 1, B: 2, C: 3}\nservices:\n"); + for (int i = 0; i < 40; i++) { + compose.append(" svc").append(i).append(":\n image: busybox\n environment: *env\n"); + } + compose.append(" floci:\n image: floci/floci:latest\n ports: [\"4566:4566\"]\n" + + " volumes: [\"/var/run/docker.sock:/var/run/docker.sock\"]\n"); + + ComposeCheck.Report r = aws(compose.toString()); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + } + + /** + * Compose reads YAML 1.2, where only true and false are booleans. A service or key called + * on, off, yes or no keeps its spelling instead of turning into true or false. + */ + @ParameterizedTest + @ValueSource(strings = {"on", "off", "yes", "no", "y", "n", "On", "NO"}) + void aServiceNamedLikeAYaml11BooleanKeepsItsName(String name) throws Exception { + ComposeCheck.Report r = aws(""" + services: + %s: + image: floci/floci:latest + ports: ["4566:4566"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + """.formatted(name)); + + assertEquals(name, r.service()); + assertEquals(List.of(), r.errors()); + } + + @Test + void onlyTrueAndFalseAreBooleans() throws Exception { + JsonNode tree = YamlTree.read(""" + a: true + b: False + c: yes + d: off + e: 2024-01-01 + f: 0x1F + g: ~ + """); + + assertTrue(tree.path("a").isBoolean() && tree.path("a").asBoolean()); + assertTrue(tree.path("b").isBoolean() && !tree.path("b").asBoolean()); + assertEquals("yes", tree.path("c").asText()); + assertTrue(tree.path("c").isTextual()); + assertEquals("off", tree.path("d").asText()); + assertEquals("2024-01-01", tree.path("e").asText()); + assertTrue(tree.path("f").isIntegralNumber()); + assertTrue(tree.path("g").isNull()); + } + + /** read_only written as true still makes a data volume read-only. */ + @Test + void aBooleanValueIsStillABoolean() throws Exception { + ComposeCheck.Report r = aws(service("\"4566:4566\"", + " - {type: bind, source: ./data, target: /app/data, read_only: true}\n 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 anAliasWithoutItsAnchorIsAParseError() { + assertThrows(IOException.class, () -> YamlTree.read("services:\n floci: *missing\n")); + } + + @Test + void anEmptyDocumentIsMissing() throws Exception { + assertTrue(YamlTree.read("").isMissingNode()); + assertTrue(YamlTree.read("# only a comment\n").isMissingNode()); + } + + /** An anchor on a plain value, such as a shared image tag, resolves like any other. */ + @Test + void anAnchorOnAScalarResolves() throws Exception { + ComposeCheck.Report r = aws(""" + x-image: &image floci/floci:1.6.0 + x-port: &port "4566:4566" + services: + floci: + image: *image + ports: [*port] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] + """); + + assertEquals("floci", r.service()); + assertEquals(List.of(), r.errors()); + assertEquals(List.of(), r.warnings()); + } + + /** Through the command: the file from the report exits 0. */ + @Test + void theCommandAcceptsAComposeFileWithAnchors() throws Exception { + Path file = Files.writeString(tempDir.resolve("compose.yml"), """ + x-floci: &floci + image: floci/floci:latest + volumes: &sock + - /var/run/docker.sock:/var/run/docker.sock + services: + floci: + <<: *floci + ports: ["4566:4566"] + worker: + image: busybox + volumes: *sock + """); + + Run r = run("config", "validate", "-f", file.toString(), "-o", "json"); + + assertEquals(0, r.exit(), r.out() + r.err()); + JsonNode json = new ObjectMapper().readTree(r.out()); + assertTrue(json.path("valid").asBoolean(), r.out()); + assertEquals("floci", json.path("service").asText()); + assertEquals(0, json.path("errors").size()); + } + // ---- the command --------------------------------------------------------------------------- private record Run(int exit, String out, String err) {} From 188aa23edcf68ad3b53c83abbbc4598b2678bfe7 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 21:17:28 -0500 Subject: [PATCH 3/4] fix(cli): keep the next step when an error's cause has several lines (#67) A failed docker run with more than one line of output lost its 'floci doctor' hint, and a profile or Compose file that does not parse was reported with the parser's source-location line instead of what to do. Causes are now shown as one line, and docker's own output always gets its next step. Signed-off-by: Hector Ventura --- .../io/floci/cli/commands/StartCommand.java | 6 ++-- .../config/ConfigDefaultProductCommand.java | 3 +- .../commands/config/ConfigProfileCommand.java | 14 ++++---- .../config/ConfigValidateCommand.java | 6 ++-- .../floci/cli/commands/config/YamlTree.java | 4 +-- .../floci/cli/config/GlobalConfigStore.java | 6 ++-- .../config/ProfileDefaultValueProvider.java | 3 +- .../io/floci/cli/config/ProfileStore.java | 9 ++---- src/main/java/io/floci/cli/util/Causes.java | 23 +++++++++++++ .../java/io/floci/cli/unit/CausesTest.java | 32 +++++++++++++++++++ .../io/floci/cli/unit/ConfigCommandsTest.java | 29 +++++++++++++++++ .../io/floci/cli/unit/MissingProfileTest.java | 15 +++++++++ .../io/floci/cli/unit/StartPreflightTest.java | 27 +++++++++++++++- 13 files changed, 149 insertions(+), 28 deletions(-) create mode 100644 src/main/java/io/floci/cli/util/Causes.java create mode 100644 src/test/java/io/floci/cli/unit/CausesTest.java diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index ce907ab..1066d1e 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -377,8 +377,10 @@ public class StartCommand implements Callable { 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."); + // withNextStep, not the two-argument error: docker's own output is often several + // lines, which must not be taken for a next step. + printer.error("Failed to start container: " + e.withNextStep( + "Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port.")); return 1; } diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java index 28343d8..728858b 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -4,6 +4,7 @@ import io.floci.cli.GlobalOptions; import io.floci.cli.config.GlobalConfigStore; import io.floci.cli.output.Ansi; import io.floci.cli.output.Printer; +import io.floci.cli.util.Causes; import picocli.CommandLine.*; import java.io.IOException; @@ -37,7 +38,7 @@ public class ConfigDefaultProductCommand implements Callable { printer.println(Ansi.gray("Config saved to: " + store.configFilePath())); return 0; } catch (IOException e) { - printer.error("Could not save config: " + e.getMessage(), + printer.error("Could not save config: " + Causes.firstLine(e), "Check that " + store.configFilePath().getParent() + " is writable and re-run the command."); return 1; } diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index dd8f1ea..ae55d42 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -8,6 +8,7 @@ import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; +import io.floci.cli.util.Causes; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -149,7 +150,7 @@ public class ConfigProfileCommand implements Callable { } return 0; } catch (IOException e) { - printer.error("Could not list profiles: " + e.getMessage(), + printer.error("Could not list profiles: " + Causes.firstLine(e), "Check the files under ~/.floci/profiles and re-run the command."); return 1; } @@ -175,7 +176,7 @@ public class ConfigProfileCommand implements Callable { if (p.namespace != null) printer.println(" namespace: " + p.namespace); return 0; } catch (IOException e) { - printer.error("Could not read profile: " + e.getMessage(), "Fix or delete the profile file, then re-run the command."); + printer.error("Could not read profile: " + Causes.firstLine(e), "Fix or delete the profile file, then re-run the command."); return 1; } } @@ -212,7 +213,7 @@ public class ConfigProfileCommand implements Callable { printer.error("Interrupted while " + editor.get(0) + " was open.\nRe-run '" + prefix + "edit " + name + "'."); return 1; } catch (IOException e) { - printer.error("Could not start the editor '" + String.join(" ", editor) + "': " + e.getMessage(), + printer.error("Could not start the editor '" + String.join(" ", editor) + "': " + Causes.firstLine(e), "Set EDITOR to a command on your PATH, or edit " + file + " yourself."); return 1; } @@ -231,8 +232,7 @@ public class ConfigProfileCommand implements Callable { } ProfileDefaultValueProvider.warnAboutUnknownKeys(store, name, edited.get()); } catch (IOException e) { - String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable"); - printer.error("Profile '" + name + "' is no longer valid: " + reason + "\n" + printer.error("Profile '" + name + "' is no longer valid: " + Causes.firstLine(e) + "\n" + "Re-run '" + prefix + "edit " + name + "' to fix it."); return 1; } @@ -329,7 +329,7 @@ public class ConfigProfileCommand implements Callable { printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name)); return 0; } catch (IOException e) { - printer.error("Could not create profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command."); + printer.error("Could not create profile: " + Causes.firstLine(e), "Check that ~/.floci/profiles is writable and re-run the command."); return 1; } } @@ -401,7 +401,7 @@ public class ConfigProfileCommand implements Callable { printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files); return 0; } catch (IOException e) { - printer.error("Could not delete profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command."); + printer.error("Could not delete profile: " + Causes.firstLine(e), "Check that ~/.floci/profiles is writable and re-run the command."); return 1; } } 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 af11486..23ed1da 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -7,6 +7,7 @@ import io.floci.cli.output.Ansi; import io.floci.cli.output.Glyphs; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; +import io.floci.cli.util.Causes; import picocli.CommandLine.*; import java.io.IOException; @@ -59,7 +60,7 @@ public class ConfigValidateCommand implements Callable { try { content = Files.readString(composeFile); } catch (IOException e) { - printer.error("Could not read " + composeFile + ": " + e.getMessage(), + printer.error("Could not read " + composeFile + ": " + Causes.firstLine(e), "Check the file's permissions, or pass another with --file."); return 1; } @@ -72,8 +73,7 @@ public class ConfigValidateCommand implements Callable { 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; + unreadable = "Could not read " + composeFile + " as YAML: " + Causes.firstLine(e); } if (unreadable != null) { // Structured output always carries the report, so a script reading it gets 'valid: false' diff --git a/src/main/java/io/floci/cli/commands/config/YamlTree.java b/src/main/java/io/floci/cli/commands/config/YamlTree.java index 4f27ae1..f1f1427 100644 --- a/src/main/java/io/floci/cli/commands/config/YamlTree.java +++ b/src/main/java/io/floci/cli/commands/config/YamlTree.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.cli.util.Causes; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; @@ -85,8 +86,7 @@ public final class YamlTree { Iterator documents = reader.loadAll(yaml).iterator(); first = documents.hasNext() ? documents.next() : null; } catch (YAMLException | IllegalArgumentException e) { - String reason = e.getMessage() == null ? "not valid YAML" : e.getMessage().lines().findFirst().orElse("not valid YAML"); - throw new IOException(reason); + throw new IOException(Causes.firstLine(e)); } return first == null ? NODES.missingNode() : tree(first, new int[] {MAX_NODES}, 0); } diff --git a/src/main/java/io/floci/cli/config/GlobalConfigStore.java b/src/main/java/io/floci/cli/config/GlobalConfigStore.java index 780ea21..889d3a8 100644 --- a/src/main/java/io/floci/cli/config/GlobalConfigStore.java +++ b/src/main/java/io/floci/cli/config/GlobalConfigStore.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.floci.cli.output.Ansi; +import io.floci.cli.util.Causes; import java.io.IOException; import java.nio.file.AccessDeniedException; @@ -49,10 +50,7 @@ public class GlobalConfigStore { private static String reason(IOException e) { if (e instanceof AccessDeniedException) return "permission denied"; - String message = e.getMessage(); - if (message == null) return e.getClass().getSimpleName(); - int newline = message.indexOf('\n'); - return newline >= 0 ? message.substring(0, newline) : message; + return Causes.firstLine(e); } public void setDefaultProduct(String product) throws IOException { diff --git a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java index 271c75d..d932082 100644 --- a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java +++ b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java @@ -2,6 +2,7 @@ package io.floci.cli.config; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; +import io.floci.cli.util.Causes; import picocli.CommandLine; import picocli.CommandLine.IDefaultValueProvider; import picocli.CommandLine.Model.ArgSpec; @@ -117,7 +118,7 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider { } catch (IllegalArgumentException e) { throw new ProfileNotFoundException(commandLine, e.getMessage()); } catch (IOException e) { - throw invalid(commandLine, name, e.getMessage()); + throw invalid(commandLine, name, Causes.firstLine(e)); } if (loaded.isEmpty()) { throw new ProfileNotFoundException(commandLine, diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java index 0db2682..5243db0 100644 --- a/src/main/java/io/floci/cli/config/ProfileStore.java +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -3,6 +3,7 @@ package io.floci.cli.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.floci.cli.output.Ansi; +import io.floci.cli.util.Causes; import java.io.IOException; import java.nio.file.Files; @@ -75,7 +76,7 @@ public class ProfileStore { // The cause is quoted, not guessed: this is a parse error or a // file that could not be opened. System.err.println(Ansi.yellow("Warning: ") + "Could not read profile file " + p - + ": " + firstLine(e.getMessage()) + + ": " + Causes.firstLine(e) + "\nCheck the file and its permissions, or delete it."); } }); @@ -89,12 +90,6 @@ public class ProfileStore { return Optional.of(read(file)); } - private static String firstLine(String message) { - if (message == null) return "unreadable"; - int newline = message.indexOf('\n'); - return newline >= 0 ? message.substring(0, newline) : message; - } - // The one read path, so list and show agree on a profile's name. private static Profile read(Path file) throws IOException { Profile profile = YAML.readValue(file.toFile(), Profile.class); diff --git a/src/main/java/io/floci/cli/util/Causes.java b/src/main/java/io/floci/cli/util/Causes.java new file mode 100644 index 0000000..712a6fd --- /dev/null +++ b/src/main/java/io/floci/cli/util/Causes.java @@ -0,0 +1,23 @@ +package io.floci.cli.util; + +/** + * Turns an exception into the one line a user is shown. Parser errors from Jackson and YAML come + * with a second line of source location ("at [Source: ...; line: 3]"), which is noise in a + * message and, worse, looks like a next step to {@code Printer.error(message, nextStep)}. + */ +public final class Causes { + + private Causes() {} + + /** The first line of {@code e}'s message, or its type name when it has none. */ + public static String firstLine(Throwable e) { + String message = e.getMessage(); + if (message == null || message.isBlank()) return e.getClass().getSimpleName(); + return firstLine(message); + } + + /** The first non-empty line of {@code message}. */ + public static String firstLine(String message) { + return message.strip().lines().findFirst().orElse(message).strip(); + } +} diff --git a/src/test/java/io/floci/cli/unit/CausesTest.java b/src/test/java/io/floci/cli/unit/CausesTest.java new file mode 100644 index 0000000..ad0da07 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/CausesTest.java @@ -0,0 +1,32 @@ +package io.floci.cli.unit; + +import io.floci.cli.util.Causes; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** BL-096: a cause is shown as one line, so the next step that follows it is not mistaken for part of it. */ +class CausesTest { + + @Test + void aParserMessageIsCutAtItsFirstLine() { + IOException jackson = new IOException("Cannot deserialize value of type `java.lang.Integer`\n" + + " at [Source: (File); line: 3, column: 7] (through reference chain: Profile[\"port\"])"); + + assertEquals("Cannot deserialize value of type `java.lang.Integer`", Causes.firstLine(jackson)); + } + + @Test + void aOneLineMessageIsKept() { + assertEquals("Permission denied", Causes.firstLine(new IOException("Permission denied"))); + assertEquals("Permission denied", Causes.firstLine(" Permission denied\n")); + } + + @Test + void anExceptionWithoutAMessageIsNamedByItsType() { + assertEquals("IOException", Causes.firstLine(new IOException())); + assertEquals("IllegalStateException", Causes.firstLine(new IllegalStateException(" "))); + } +} diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index a9591df..4d6a3e3 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -401,4 +401,33 @@ class ConfigCommandsTest { partial.add("port"); assertEquals(partial, jsonKeys(runShow(ProductProfile.AWS, "--profile", "partial", "-o", "json"))); } + + /** + * BL-096: a profile that does not parse is reported in one line of cause, followed by the next + * step. The parser's "at [Source: ...]" line used to stand in for it. + */ + @Test + void aBrokenProfileIsReportedWithItsNextStep() throws Exception { + writeProfile("broken", "port: [unterminated\n"); + + Run show = profileCmd(ProductProfile.AWS, "show", "broken"); + + assertEquals(1, show.exit()); + List lines = show.err().strip().lines().toList(); + assertEquals(2, lines.size(), show.err()); + assertTrue(lines.get(0).contains("Could not read profile: "), show.err()); + assertEquals("Fix or delete the profile file, then re-run the command.", lines.get(1)); + assertFalse(show.err().contains("[Source"), show.err()); + } + + @Test + void creatingOverABrokenProfileKeepsItsNextStepToo() throws Exception { + writeProfile("broken", "port: [unterminated\n"); + + Run create = profileCmd(ProductProfile.AWS, "create", "broken"); + + assertEquals(1, create.exit()); + assertTrue(create.err().strip().endsWith("re-run the command."), create.err()); + assertFalse(create.err().contains("[Source"), create.err()); + } } diff --git a/src/test/java/io/floci/cli/unit/MissingProfileTest.java b/src/test/java/io/floci/cli/unit/MissingProfileTest.java index 190e4a0..997f88a 100644 --- a/src/test/java/io/floci/cli/unit/MissingProfileTest.java +++ b/src/test/java/io/floci/cli/unit/MissingProfileTest.java @@ -192,4 +192,19 @@ class MissingProfileTest { assertThrows(ProfileNotFoundException.class, () -> cli().parseArgs("start", "--profile", "typo")); } + + /** BL-096: --profile on a file that does not parse says so in two lines: the cause, then what to do. */ + @Test + void aProfileThatDoesNotParseIsReportedInTwoLines() throws IOException { + writeProfile("broken", "port: [unterminated\n"); + int[] exit = new int[1]; + + String stderr = captureStderr(() -> cli().execute("status", "--profile", "broken"), exit); + + assertEquals(2, exit[0]); + assertEquals(2, stderr.strip().lines().count(), stderr); + assertTrue(stderr.contains("Profile 'broken' is invalid: "), stderr); + assertTrue(stderr.strip().endsWith("and try again."), stderr); + assertFalse(stderr.contains("[Source"), stderr); + } } diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 0e8fd82..72cff7c 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -11,6 +11,8 @@ 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; import java.io.ByteArrayOutputStream; @@ -66,7 +68,7 @@ class StartPreflightTest { } @Override - public String startContainer(List args) { + public String startContainer(List args) throws DockerException { runArgs.addAll(args); calls.add("run"); return "0123456789abcdef"; @@ -272,6 +274,29 @@ class StartPreflightTest { assertEquals(List.of(), docker.calls); } + /** + * BL-096: docker's own error is often several lines. The next step must still follow it; a + * second line of docker output is not advice. + */ + @ParameterizedTest + @ValueSource(strings = { + "docker: Error response from daemon: driver failed programming external connectivity.", + "docker: Error response from daemon: Conflict.\nRun 'docker run --help' for more information.\n"}) + void aFailedDockerRunKeepsItsNextStep(String dockerOutput) { + FakeDocker docker = new FakeDocker(REMOTE) { + @Override + public String startContainer(List args) throws DockerException { + throw DockerException.ofOutput(dockerOutput); + } + }; + + Out r = start(docker, "--container", "floci-gcp-preflight", "--detach"); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("Failed to start container: docker: Error response from daemon"), r.err()); + assertTrue(r.err().strip().endsWith("Run 'floci gcp doctor' to check Docker, the image and the port."), r.err()); + } + /** A context selected with DOCKER_CONTEXT or 'docker context use' is not in the environment: docker is asked. */ @Test @DisabledOnOs(OS.WINDOWS) From c65987abbac07c666fd21ab81cc88d20feebce96 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 11 Oct 2026 21:17:32 -0500 Subject: [PATCH 4/4] fix(cli): exit 2 for every rejected value, not 1 in some commands (#66) * fix(cli): exit 2 for every rejected value, not 1 in some commands config default-product, config profile (unknown action, missing name, --port out of range), update --version, an invalid snapshot name, an invalid az setup container name and an unusable --persist path returned 1, the code for a command that ran and failed. They now return 2 like every other rejected value. A persist directory that cannot be created is still 1. Signed-off-by: Hector Ventura * test(restart): pin exit 2 for an unusable persist path before anything is stopped Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- README.md | 17 ++--- .../io/floci/cli/commands/RestartCommand.java | 5 ++ .../io/floci/cli/commands/StartCommand.java | 33 +++++++-- .../io/floci/cli/commands/UpdateCommand.java | 6 +- .../floci/cli/commands/az/AzSetupCommand.java | 3 +- .../config/ConfigDefaultProductCommand.java | 2 +- .../commands/config/ConfigProfileCommand.java | 12 ++-- .../snapshot/SnapshotDeleteCommand.java | 5 ++ .../snapshot/SnapshotLoadCommand.java | 5 ++ .../snapshot/SnapshotSaveCommand.java | 5 ++ .../io/floci/cli/http/FlociHttpClient.java | 18 +++-- .../io/floci/cli/unit/AzSetupCommandTest.java | 2 +- .../io/floci/cli/unit/ConfigCommandsTest.java | 2 +- .../io/floci/cli/unit/ExitCodeTableTest.java | 20 +++++- .../io/floci/cli/unit/RestartCommandTest.java | 70 +++++++++++++++++++ .../io/floci/cli/unit/StartPreflightTest.java | 2 +- 16 files changed, 175 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index aa9bc92..05e47fc 100644 --- a/README.md +++ b/README.md @@ -932,9 +932,10 @@ the same three codes: | `1` | It ran and failed, or the answer to the question it asks is "no". | | `2` | The command line could not be used: an unknown flag or command, a missing argument, a value picocli cannot convert (`--port abc`), or a `--profile` that does not exist or cannot be read. | -A value the command line accepts but the command then rejects is reported by that command. Most -use `2` for it, as the table below shows; three use `1`: `config default-product `, -`update --version ` and `config profile create --port `. +A value the command line accepts but the command then rejects is exit `2` as well, in every +command: an out-of-range `--port`, an unknown `--pull` policy, a `--persist` path that cannot be +used, a `--version` that is not a release version, an unknown product or action, a missing or +invalid name. Exit `1` always means the command ran. Where a command's codes carry a specific meaning a script can rely on: @@ -944,16 +945,16 @@ Where a command's codes carry a specific meaning a script can rely on: | `wait` | ready before `--timeout` | timed out | `--timeout` is not a positive duration | | `doctor` | every check passed (warnings allowed) | at least one check failed | `--check` names no known check | | `update --check` | up to date | an update is available | the check itself failed | -| `update` | updated, or already up to date | the update failed, or `--version` is not a release version; the binary is unchanged | bad flag | -| `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed | `--port`, `--pull` or the namespace is not valid | +| `update` | updated, or already up to date | the update failed; the binary is unchanged | `--version` is not a release version | +| `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed, or the `--persist` directory cannot be created | `--port`, `--pull`, the namespace or the `--persist` path is not valid | | `stop` | stopped, or was not running | no such container, or Docker failed | bad flag or profile | | `reset` | state reset | declined, not available on this server, no running instance to reset, or the configuration names two different servers | no terminal to ask on and no `--yes` | | `config validate` | no errors (warnings allowed) | errors found, or the file cannot be read | bad flag | -| `config profile ...` | done | not found, already exists, cannot be read, `--port` is out of range, or (for `edit`) no editor is set, the editor failed or the file no longer parses | the profile name is not valid | -| `config default-product` | saved | not `aws`, `gcp`, `az` or `oci`, or the file cannot be written | bad flag | +| `config profile ...` | done | not found, already exists, cannot be read, or (for `edit`) no editor is set, the editor failed or the file no longer parses | unknown action, missing or invalid profile name, `--port` out of range | +| `config default-product` | saved | the file cannot be written | not `aws`, `gcp`, `az` or `oci` | | `env` | variables printed | | `--shell` is not supported | | `completion` | script printed | | the shell is not `bash` or `zsh` | -| `snapshot ...` | done | failed, or the server has no snapshot API yet | bad flag or profile | +| `snapshot ...` | done | failed, or the server has no snapshot API yet | invalid snapshot name | `docs/help/` holds the `--help` text of every command, generated from the code. A test fails when the files and the commands drift apart; regenerate them with diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index a3754e9..e7725b5 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -74,6 +74,11 @@ public class RestartCommand implements Callable { printer.error(invalid); return 2; } + String rejected = start.persistPathError(); + if (rejected != null) { + printer.error(rejected); + return ExitCode.USAGE; + } String unwritable = start.preparePersistDir(); if (unwritable != null) { printer.error(unwritable); diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 1066d1e..e9893e8 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -187,8 +187,13 @@ public class StartCommand implements Callable { return preparePersistDir(docker.daemonHost()); } - /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ - public String preparePersistDir(DockerClient.DockerHost daemon) { + /** + * Why the {@code --persist} value cannot be used at all, or {@code null}. This is about the + * value, not about the file system: a path this machine cannot parse, or a relative one for + * a remote daemon. Callers report it as a usage error (exit 2); a directory that is fine as a + * value but cannot be created is {@link #preparePersistDir}'s to report (exit 1). + */ + public String persistPathError(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 @@ -199,14 +204,29 @@ public class StartCommand implements Callable { : "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()); + Path.of(persistPath()); + return null; } 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."; } + } + + /** {@link #persistPathError(DockerClient.DockerHost)} for the daemon docker resolved. */ + public String persistPathError() { + return persistPathError(docker.daemonHost()); + } + + /** {@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; + String rejected = persistPathError(daemon); + if (rejected != null) return rejected; + // A remote daemon creates the directory on its own machine. + if (daemon.kind() == DockerClient.Kind.TCP) return null; + Path path = Path.of(persistPath()); try { Files.createDirectories(path); return null; @@ -314,6 +334,11 @@ public class StartCommand implements Callable { // whether the daemon docker will talk to is on this machine. DockerClient.DockerHost daemon = docker.daemonHost(); + String rejected = persistPathError(daemon); + if (rejected != null) { + printer.error(rejected); + return ExitCode.USAGE; + } String unwritable = preparePersistDir(daemon); if (unwritable != null) { printer.error(unwritable); diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index 5bf0e73..c9c2af4 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -101,8 +101,10 @@ public class UpdateCommand implements Callable { String current = CliVersion.CLI_VERSION; boolean pinned = to != null && !to.isBlank(); if (pinned && !Version.isValid(to.trim())) { - // It goes into the download URL; refuse anything that is not a release version. - throw new UpdateException("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + // It goes into the download URL; refuse anything that is not a release version. A + // value the command cannot accept, so the exit code of any other bad argument. + printer.error("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + return ExitCode.USAGE; } String target = pinned ? to.trim() : fetchLatestVersion(); diff --git a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java index c40c3f8..e3b8c1a 100644 --- a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java @@ -120,8 +120,9 @@ public class AzSetupCommand implements Callable { try { flociAzDir = InstanceState.dir(stateRoot, ProductProfile.AZ, cloud); } catch (IllegalArgumentException e) { + // A container name that cannot be used: the same exit code as any other bad argument. printer.error(e.getMessage()); - return 1; + return ExitCode.USAGE; } try { return reset ? reset(printer, flociAzDir, cloud) : setup(printer, flociAzDir, cloud); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java index 728858b..57c6a66 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -28,7 +28,7 @@ public class ConfigDefaultProductCommand implements Callable { Printer printer = global.printer(); if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product) && !"oci".equals(product)) { printer.error("Unknown product '" + product + "'.\nUse one of: aws, az, gcp, oci."); - return 1; + return ExitCode.USAGE; // a value the command cannot accept, like any other bad argument } GlobalConfigStore store = new GlobalConfigStore(); try { diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index ae55d42..31c8ccd 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -100,7 +100,7 @@ public class ConfigProfileCommand implements Callable { case "delete" -> deleteProfile(printer, store); default -> { printer.error("Unknown action '" + action + "'.\nUse one of: list, show, create, edit, delete."); - yield 1; + yield ExitCode.USAGE; } }; } catch (IllegalArgumentException e) { @@ -157,7 +157,7 @@ public class ConfigProfileCommand implements Callable { } private int showProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { var profile = store.get(name); if (profile.isEmpty()) { @@ -187,7 +187,7 @@ public class ConfigProfileCommand implements Callable { * not created here, since {@code create} is what writes the product's defaults into it. */ private int editProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } String prefix = this.profile.commandPrefix() + " config profile "; // Asked of the file, not of its contents: a profile that no longer parses is exactly the // one that has to be opened to be repaired. @@ -299,7 +299,7 @@ public class ConfigProfileCommand implements Callable { } private int createProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { if (store.get(name).isPresent()) { printer.error("Profile '" + name + "' already exists.\nDelete it first, or edit " + store.existingFile(name) + "."); @@ -308,7 +308,7 @@ public class ConfigProfileCommand implements Callable { if (port != null && (port < 1 || port > 65535)) { printer.error("--port must be between 1 and 65535, but was " + port + ".\n" + "Pick a free port, for example " + (profile.defaultPort() + 10000) + "."); - return 1; + return ExitCode.USAGE; } Profile p = new Profile(profile, name); // Only flags the user typed: the mixin's own values may come from FLOCI_* env vars, and @@ -388,7 +388,7 @@ public class ConfigProfileCommand implements Callable { } private int deleteProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { List removed = store.delete(name); if (removed.isEmpty()) { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java index 51def60..30ac1a0 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java @@ -38,6 +38,11 @@ public class SnapshotDeleteCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java index 93c8547..ab06b91 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java @@ -38,6 +38,11 @@ public class SnapshotLoadCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java index 4b19c40..e55812a 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java @@ -41,6 +41,11 @@ public class SnapshotSaveCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index 1f3e2cb..73dd484 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -313,12 +313,22 @@ public class FlociHttpClient { } } + /** + * Why {@code name} cannot be a snapshot name, or {@code null}. Commands ask before they send + * anything, so a bad name is a usage error rather than a failed request. + */ + public static String snapshotNameError(String name) { + if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) { + return "Invalid snapshot name '" + name + "'.\n" + + "Use a name that is not '.' or '..' and has no '/'."; + } + return null; + } + /** A snapshot name as one URL path segment; names that could change the path are refused. */ static String snapshotSegment(String name) throws FlociException { - if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) { - throw new FlociException("Invalid snapshot name '" + name + "'.\n" - + "Use a name that is not '.' or '..' and has no '/'."); - } + String invalid = snapshotNameError(name); + if (invalid != null) throw new FlociException(invalid); return URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20"); } } diff --git a/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java index 1107b8b..f96986c 100644 --- a/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java +++ b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java @@ -339,7 +339,7 @@ class AzSetupCommandTest { @Test void aContainerNameThatWouldEscapeIsRefused() { - assertEquals(1, run("--container", "../x")); + assertEquals(2, run("--container", "../x"), "a rejected value is a usage error"); assertTrue(az.calls.isEmpty()); } diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index 4d6a3e3..a801900 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -207,7 +207,7 @@ class ConfigCommandsTest { void createRefusesAPortOutOfRange() throws Exception { Run r = profileCmd(ProductProfile.AZ, "create", "bad", "--port", "70000"); - assertEquals(1, r.exit()); + assertEquals(2, r.exit(), "a rejected value is a usage error"); assertTrue(store().get("bad").isEmpty()); } diff --git a/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java b/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java index 8fd74a6..4d0c9d4 100644 --- a/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java +++ b/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java @@ -39,9 +39,23 @@ class ExitCodeTableTest { "2, completion fish", "2, status --json --no-such-flag", "2, config profile show ../escape", - // Accepted by the command line, rejected by the command with 1. - "1, update --version not-a-version", - "1, config profile create demo --port 0", + // Accepted by the command line, rejected by the command: the same code. + "2, update --version not-a-version", + "2, update --check --version not-a-version", + "2, config profile create demo --port 0", + "2, config profile create demo --port 70000", + "2, config profile bogus", + "2, config profile show", + "2, config profile create", + "2, config profile edit", + "2, config profile delete", + "2, config default-product nope", + "2, snapshot save a/b", + "2, snapshot load ..", + "2, snapshot delete a/b", + "2, gcp snapshot save a/b", + "2, az setup --container ../escape", + // It ran and the answer is no. "1, config profile show no-such-profile", "1, config profile edit no-such-profile", "1, config validate -f no-such-compose-file.yml", diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index d5283ac..28a4f21 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -374,4 +374,74 @@ class RestartCommandTest { assertTrue(r.err().contains("did not finish within 30s"), r.err()); assertTrue(r.err().contains("floci restart"), r.err()); } + + /** + * A --persist value that cannot be used is a usage error (exit 2), and restart finds out before + * it stops anything: here a relative path, which a remote daemon cannot resolve. + */ + @Test + void aPersistPathThatCannotBeUsedExitsTwoBeforeTheStop() { + DockerClient.DockerHost remote = new DockerClient.DockerHost(DockerClient.Kind.TCP, null, "tcp://build-host:2375"); + DockerClient running = new DockerClient() { + @Override + public Optional inspectRunSettings(String name, int containerPort) { + // What the running container was started with: a relative data directory. + return Optional.of(new RunSettings("floci/floci:0.9", 14566, "data", Map.of())); + } + + @Override + public Optional inspectContainer(String name) { + return Optional.of(new ContainerInfo("abc", name, "floci/floci:0.9", "running", "14566->4566/tcp")); + } + }; + List ran = new ArrayList<>(); + RestartCommand restart = new RestartCommand(ProductProfile.AWS, running) { + @Override + public StartCommand buildStartCommand() throws DockerException { + StartCommand real = super.buildStartCommand(); + return new StartCommand(ProductProfile.AWS) { + @Override + public String validationError() { + return real.validationError(); + } + + @Override + public String persistPathError() { + return real.persistPathError(remote); + } + + @Override + public String preparePersistDir() { + return real.preparePersistDir(remote); + } + + @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(); + + Ran r = run(restart); + + assertEquals(2, r.exit()); + assertEquals(List.of(), ran, "nothing was stopped or started"); + assertTrue(r.err().contains("--persist must be an absolute path on the daemon's machine"), r.err()); + } } diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 72cff7c..5582df3 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -173,7 +173,7 @@ class StartPreflightTest { FakeDocker refused = new FakeDocker(REMOTE); Out relative = start(refused, "--persist", "data", "--container", "floci-gcp-preflight", "--detach"); - assertEquals(1, relative.exit()); + assertEquals(2, relative.exit(), "a rejected value is a usage error"); assertTrue(relative.err().contains("must be an absolute path on the daemon's machine"), relative.err()); assertEquals(List.of(), refused.calls); }