From 85b5237687669ad7bbb8c2fe2d2d2657bd7c17de Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 23:27:17 -0500 Subject: [PATCH] feat(cli): report the container's real state after start and stop start reads the state back, so a container that exited during the readiness wait is not reported as running, and stop reports a container docker removed on its own (--rm) as removed. The tests now reject anything after the one document on stdout. Signed-off-by: Hector Ventura --- .../io/floci/cli/commands/StartCommand.java | 19 ++++- .../io/floci/cli/commands/StopCommand.java | 21 ++++- .../io/floci/cli/unit/ActionOutputTest.java | 83 ++++++++++++++++++- 3 files changed, 114 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index bd73f6e..ce907ab 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -399,13 +399,18 @@ public class StartCommand implements Callable { WaitCommand wait = new WaitCommand(profile); wait.global = global; wait.knownEndpoint = endpoint; - wait.timeout = "30s"; + wait.timeout = readinessTimeout(); wait.embedded = true; int exit = wait.call(); if (structured) printer.structured(result(id, endpoint, exit == 0)); return exit; } + /** How long start waits for the emulator to answer. A seam: tests do not wait half a minute. */ + protected String readinessTimeout() { + return "30s"; + } + // What -o json/yaml reports for a start: 'ready' is left out when --detach did not wait for it. private Map result(String id, String endpoint, Boolean ready) { Map result = new LinkedHashMap<>(); @@ -413,11 +418,21 @@ public class StartCommand implements Callable { result.put("id", id); result.put("image", image); result.put("endpoint", endpoint); - result.put("state", "running"); + result.put("state", stateNow()); if (ready != null) result.put("ready", ready); return result; } + // Read back, not assumed: a container that crashed while start waited for it has exited, and + // a script must not be told it is running. "unknown" when docker cannot say. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse("removed"); + } catch (DockerException e) { + return "unknown"; + } + } + /** * Whether a busy local {@code port} would stop this start. Not for a remote daemon, which * publishes the port on its own machine, and not for a number that is no port at all: diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java index 78e1d16..2d75e6e 100644 --- a/src/main/java/io/floci/cli/commands/StopCommand.java +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -90,20 +90,35 @@ public class StopCommand implements Callable { return 1; } - if (remove) { + // What is left of it: a container run with docker's --rm is gone the moment it stops, + // whatever --remove said, so the result is read back rather than assumed. + String state = stateNow(); + boolean gone = state == null; + if (remove && !gone) { try { docker.removeContainer(global.container); - progress.accept("Container removed."); + gone = true; } catch (DockerException e) { printer.error("Failed to remove container: " + e.withNextStep(DockerClient.CHECK_DOCKER)); return 1; } } + if (remove) progress.accept("Container removed."); - report(printer, structured, remove ? "removed" : "exited", true, remove); + report(printer, structured, gone ? "removed" : state, true, gone); return 0; } + // The container's state as docker has it now; null when it no longer exists. A lookup that + // fails after a stop that succeeded is reported as the state the stop leaves behind. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse(null); + } catch (DockerException e) { + return "exited"; + } + } + // What -o json/yaml reports for a stop: the state the container was left in, whether this // call is what stopped it, and whether it was removed. private void report(Printer printer, boolean structured, String state, boolean stopped, boolean removed) { diff --git a/src/test/java/io/floci/cli/unit/ActionOutputTest.java b/src/test/java/io/floci/cli/unit/ActionOutputTest.java index 73f77d4..85fe29f 100644 --- a/src/test/java/io/floci/cli/unit/ActionOutputTest.java +++ b/src/test/java/io/floci/cli/unit/ActionOutputTest.java @@ -1,7 +1,10 @@ package io.floci.cli.unit; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.sun.net.httpserver.HttpServer; import io.floci.cli.ProductProfile; import io.floci.cli.commands.RestartCommand; @@ -44,7 +47,20 @@ class ActionOutputTest { // A remote daemon, so start does not probe the local port its own stub server listens on. private static final DockerHost REMOTE = new DockerHost(Kind.TCP, null, "tcp://build-host:2375"); - private static final ObjectMapper JSON = new ObjectMapper(); + // One document and nothing after it: a second value on stdout fails the parse. + private static final ObjectMapper JSON = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + + /** The single YAML document on {@code stdout}; fails when there are several, or none. */ + private static JsonNode oneYamlDocument(String stdout) throws Exception { + List documents = new ArrayList<>(); + try (MappingIterator all = YAML.readerFor(JsonNode.class).readValues(stdout)) { + all.forEachRemaining(documents::add); + } + assertEquals(1, documents.size(), "exactly one YAML document on stdout: " + stdout); + assertTrue(documents.get(0).isObject(), stdout); + return documents.get(0); + } @TempDir Path tempDir; @@ -188,12 +204,48 @@ class ActionOutputTest { } @Test - void startInYamlIsOneDocumentToo() { + void startInYamlIsOneDocumentToo() throws Exception { Run r = execute(new StartCommand(ProductProfile.AWS, new FakeDocker(null)), startArgs("-o", "yaml", "--detach")); assertEquals(0, r.exit(), r.err()); - assertTrue(r.out().startsWith("container: \"floci-actions\""), r.out()); - assertFalse(r.out().contains("Detached."), r.out()); + JsonNode yaml = oneYamlDocument(r.out()); + assertEquals("floci-actions", yaml.path("container").asText()); + assertEquals("running", yaml.path("state").asText()); + assertEquals(5, yaml.size(), "container, id, image, endpoint, state: " + r.out()); + } + + @Test + void anythingExtraOnStdoutFailsTheseTests() { + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\n{\"b\":2}\n")); + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\nStarting...\n")); + assertThrows(AssertionError.class, () -> oneYamlDocument("a: 1\n---\nb: 2\n")); + } + + /** A container that died while start waited for it is reported as it is, not as running. */ + @Test + void aContainerThatExitedDuringTheWaitIsNotReportedRunning() throws Exception { + emulator.stop(0); // nothing answers the readiness poll + FakeDocker docker = new FakeDocker(null) { + @Override + public String startContainer(List args) { + String id = super.startContainer(args); + state = "exited"; // it crashed right after docker run returned + return id; + } + }; + StartCommand start = new StartCommand(ProductProfile.AWS, docker) { + @Override + protected String readinessTimeout() { + return "300ms"; + } + }; + + Run r = execute(start, startArgs("-o", "json")); + + assertEquals(1, r.exit()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("exited", json.path("state").asText()); + assertFalse(json.path("ready").asBoolean()); } /** Text output is what it was: the progress lines, and docker's pull output on stdout. */ @@ -230,6 +282,29 @@ class ActionOutputTest { assertEquals(List.of(calls.split(";")), docker.calls); } + /** A container run with docker's --rm is gone once it stops, whatever --remove said. */ + @ParameterizedTest + @CsvSource({"false", "true"}) + void aContainerDockerRemovesItselfIsReportedRemoved(boolean remove) throws Exception { + FakeDocker docker = new FakeDocker("running") { + @Override + public void stopContainer(String name, int timeout) { + calls.add("stop"); + state = null; // --rm: docker removed it + } + }; + List args = new ArrayList<>(List.of("-o", "json")); + if (remove) args.add("--remove"); + + Run r = execute(new StopCommand(ProductProfile.AWS, docker), args.toArray(String[]::new)); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("removed", json.path("state").asText()); + assertTrue(json.path("removed").asBoolean()); + assertEquals(List.of("stop"), docker.calls, "nothing left to remove"); + } + @Test void stoppingAContainerThatIsNotRunningSaysSo() throws Exception { Run r = execute(new StopCommand(ProductProfile.AWS, new FakeDocker("exited")), "-o", "json");