diff --git a/README.md b/README.md index 4931f54..fab9051 100644 --- a/README.md +++ b/README.md @@ -459,16 +459,27 @@ floci stop # graceful stop (10s timeout) floci stop --timeout 30 # wait up to 30s before force-kill floci stop --timeout -1 # never force-kill: wait for the container to exit floci stop --remove # also remove the container after stopping +floci stop -o json # {"container", "state", "stopped", "removed"} ``` +`start`, `stop` and `restart` print one document with `-o json` or `-o yaml` and nothing else on +stdout: the progress lines are left out and docker's pull progress goes to stderr. `start` and +`restart` report `container`, `id`, `image`, `endpoint`, `state` and `ready` (`ready` is absent +with `--detach`). `logs` prints the container's own output and stays plain text. + ### `floci status` / `floci gcp status` / `floci az status` / `floci oci status` ```sh floci status # auto-detects endpoint from container port mapping floci status --container myfloci # target a specific container floci status -o json # structured output +floci status >/dev/null && echo up # exit 0: the instance is up, exit 1: it is not ``` +`status` exits 0 when the server answers and its container, if there is one, is running, and 1 +otherwise, in every output format. An instance with no local container (a remote `--endpoint`, a +Compose service under another name) counts as up when it answers. + ### `floci env` Prints AWS environment variables pointing at the running Floci instance. The default diff --git a/src/main/java/io/floci/cli/commands/LogsCommand.java b/src/main/java/io/floci/cli/commands/LogsCommand.java index b2ad0f2..af0f752 100644 --- a/src/main/java/io/floci/cli/commands/LogsCommand.java +++ b/src/main/java/io/floci/cli/commands/LogsCommand.java @@ -4,6 +4,7 @@ import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; @@ -58,6 +59,11 @@ public class LogsCommand implements Callable { return 1; } + if (printer.format() != OutputFormat.text) { + // Logs are the container's own output, line by line; there is no document to build. + printer.warn("logs prints the container's output as plain text; -o " + printer.format() + " is ignored."); + } + if (service != null) { printer.warn("--service filtering is not yet supported. Showing all container logs."); } diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 85b2e11..a3754e9 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -6,6 +6,7 @@ import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileNotFoundException; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -81,7 +82,9 @@ public class RestartCommand implements Callable { if (!containerExists()) { // Nothing to stop: start it, rather than failing on the stop. - printer.println("Container '" + global.container + "' not found; starting it."); + if (printer.format() == OutputFormat.text) { + printer.println("Container '" + global.container + "' not found; starting it."); + } return start.call(); } @@ -97,8 +100,10 @@ public class RestartCommand implements Callable { * that follows needs neither a pause nor a second inspect-and-remove of its own. */ public StopCommand buildStopCommand() { - StopCommand stop = new StopCommand(profile); + StopCommand stop = new StopCommand(profile, docker); stop.global = global; + // The start that follows reports the restart; one structured document, not two. + stop.embedded = true; stop.remove = true; stop.timeout = 10; return stop; diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 7ab7887..ce907ab 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -10,6 +10,7 @@ import io.floci.cli.doctor.CheckStatus; import io.floci.cli.doctor.checks.DockerSocketCheck; import io.floci.cli.doctor.checks.PortAvailableCheck; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine; import picocli.CommandLine.*; @@ -19,10 +20,13 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Callable; +import java.util.function.Consumer; import java.util.regex.Pattern; @Command( @@ -295,6 +299,10 @@ public class StartCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + // Structured output is one document on stdout: the progress lines a person reads are + // left out, and docker's own pull progress goes to stderr. + boolean structured = printer.format() != OutputFormat.text; + Consumer progress = structured ? line -> { } : printer::println; String invalid = validationError(); if (invalid != null) { @@ -323,7 +331,7 @@ public class StartCommand implements Callable { return 1; } // Remove stopped container so we can start fresh - printer.println(Ansi.gray("Removing stopped container '" + global.container + "'...")); + progress.accept(Ansi.gray("Removing stopped container '" + global.container + "'...")); docker.removeContainer(global.container); } } catch (DockerException e) { @@ -350,8 +358,12 @@ public class StartCommand implements Callable { // Pull image if needed try { - printer.println(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); - docker.pull(image, pull); + progress.accept(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); + if (structured) { + docker.pull(image, pull, System.err); + } else { + docker.pull(image, pull); + } } catch (DockerException e) { printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never' to skip pulling."); return 1; @@ -359,32 +371,66 @@ public class StartCommand implements Callable { List args = dockerRunArgs(DockerClient.dockerSocketRunArgs(), daemon); + String id; try { - printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); - String id = docker.startContainer(args); - printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); + progress.accept("Starting " + Ansi.gold(profile.displayName()) + " container..."); + id = docker.startContainer(args); + progress.accept(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); } catch (DockerException e) { printer.error("Failed to start container: " + e.getMessage(), "Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port."); return 1; } + // The endpoint of the port actually bound, keeping whatever host the endpoint already + // names — a profile or --endpoint may well point somewhere else. + String endpoint = withPort(global.endpoint, port); + if (detach) { - printer.println(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness.")); + progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness.")); + if (structured) printer.structured(result(id, endpoint, null)); return 0; } - // Point the readiness poll at the port actually bound, keeping whatever host the - // endpoint already names — a profile or --endpoint may well point somewhere else. - global.endpoint = withPort(global.endpoint, port); + global.endpoint = endpoint; // Wait for readiness - printer.println(Ansi.gray("Waiting for " + profile.displayName() + " to be ready...")); + progress.accept(Ansi.gray("Waiting for " + profile.displayName() + " to be ready...")); WaitCommand wait = new WaitCommand(profile); wait.global = global; - wait.knownEndpoint = global.endpoint; - wait.timeout = "30s"; - return wait.call(); + wait.knownEndpoint = endpoint; + wait.timeout = readinessTimeout(); + wait.embedded = true; + int exit = wait.call(); + if (structured) printer.structured(result(id, endpoint, exit == 0)); + return exit; + } + + /** How long start waits for the emulator to answer. A seam: tests do not wait half a minute. */ + protected String readinessTimeout() { + return "30s"; + } + + // What -o json/yaml reports for a start: 'ready' is left out when --detach did not wait for it. + private Map result(String id, String endpoint, Boolean ready) { + Map result = new LinkedHashMap<>(); + result.put("container", global.container); + result.put("id", id); + result.put("image", image); + result.put("endpoint", endpoint); + result.put("state", stateNow()); + if (ready != null) result.put("ready", ready); + return result; + } + + // Read back, not assumed: a container that crashed while start waited for it has exited, and + // a script must not be told it is running. "unknown" when docker cannot say. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse("removed"); + } catch (DockerException e) { + return "unknown"; + } } /** diff --git a/src/main/java/io/floci/cli/commands/StatusCommand.java b/src/main/java/io/floci/cli/commands/StatusCommand.java index ba901c8..598e1e4 100644 --- a/src/main/java/io/floci/cli/commands/StatusCommand.java +++ b/src/main/java/io/floci/cli/commands/StatusCommand.java @@ -32,14 +32,21 @@ public class StatusCommand implements Callable { } protected StatusCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers the container lookup. */ + public StatusCommand(ProductProfile profile, DockerClient docker) { this.profile = profile; this.global = new GlobalOptions(profile); + this.docker = docker; } + private final DockerClient docker; + @Override public Integer call() { Printer printer = global.printer(); - DockerClient docker = new DockerClient(); // Gather container info String containerState = "not found"; @@ -80,9 +87,10 @@ public class StatusCommand implements Callable { data.put("version", serverVersion); data.put("edition", serverEdition); + int exit = exitCode(containerState, reachable); if (printer.format() != OutputFormat.text) { printer.structured(data); - return 0; + return exit; } printer.println(Ansi.bold(profile.displayName() + " Status")); @@ -107,7 +115,20 @@ public class StatusCommand implements Callable { printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start' to launch " + profile.displayName() + ".")); } - return 0; + return exit; + } + + /** + * 0 when the instance is up, 1 when it is not, so a script can ask. Up means the server + * answers and its container, if there is one, is running. An instance with no container here + * (a remote endpoint, a Compose service under another name), or whose container docker could + * not look up, is up when it answers. + */ + public static int exitCode(String containerState, boolean reachable) { + // A lookup that failed ("error: ...") says nothing about the container either way. + boolean containerDown = !"running".equals(containerState) && !"not found".equals(containerState) + && !containerState.startsWith("error:"); + return reachable && !containerDown ? 0 : 1; } } diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java index 1af7136..2d75e6e 100644 --- a/src/main/java/io/floci/cli/commands/StopCommand.java +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -5,10 +5,14 @@ import io.floci.cli.ProductProfile; import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerException; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; +import java.util.function.Consumer; @Command( name = "stop", @@ -27,10 +31,24 @@ public class StopCommand implements Callable { } protected StopCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + /** Test seam: {@code docker} answers every docker call this stop makes. */ + public StopCommand(ProductProfile profile, DockerClient docker) { this.profile = profile; this.global = new GlobalOptions(profile); + this.docker = docker; } + private final DockerClient docker; + + /** + * Set by {@code restart}, whose start reports the outcome: this stop then prints no structured + * document of its own, so stdout carries exactly one. + */ + boolean embedded; + @Option(names = {"--remove", "-r"}, description = "Remove the container after stopping") boolean remove; @@ -40,7 +58,8 @@ public class StopCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - DockerClient docker = new DockerClient(); + boolean structured = printer.format() != OutputFormat.text; + Consumer progress = structured ? line -> { } : printer::println; try { var info = docker.inspectContainer(global.container); @@ -49,11 +68,12 @@ public class StopCommand implements Callable { return 1; } if (!"running".equals(info.get().state())) { - printer.println(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); + progress.accept(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); if (remove) { docker.removeContainer(global.container); - printer.println("Container removed."); + progress.accept("Container removed."); } + report(printer, structured, remove ? "removed" : info.get().state(), false, remove); return 0; } } catch (DockerException e) { @@ -62,24 +82,52 @@ public class StopCommand implements Callable { } try { - printer.println("Stopping " + Ansi.gold(profile.displayName()) + " container '" + global.container + "'..."); + progress.accept("Stopping " + Ansi.gold(profile.displayName()) + " container '" + global.container + "'..."); docker.stopContainer(global.container, timeout); - printer.println(Ansi.green("Stopped.")); + progress.accept(Ansi.green("Stopped.")); } catch (DockerException e) { printer.error("Failed to stop container: " + e.withNextStep(DockerClient.CHECK_DOCKER)); return 1; } - if (remove) { + // What is left of it: a container run with docker's --rm is gone the moment it stops, + // whatever --remove said, so the result is read back rather than assumed. + String state = stateNow(); + boolean gone = state == null; + if (remove && !gone) { try { docker.removeContainer(global.container); - printer.println("Container removed."); + gone = true; } catch (DockerException e) { printer.error("Failed to remove container: " + e.withNextStep(DockerClient.CHECK_DOCKER)); return 1; } } + if (remove) progress.accept("Container removed."); + report(printer, structured, gone ? "removed" : state, true, gone); return 0; } + + // The container's state as docker has it now; null when it no longer exists. A lookup that + // fails after a stop that succeeded is reported as the state the stop leaves behind. + private String stateNow() { + try { + return docker.inspectContainer(global.container).map(DockerClient.ContainerInfo::state).orElse(null); + } catch (DockerException e) { + return "exited"; + } + } + + // What -o json/yaml reports for a stop: the state the container was left in, whether this + // call is what stopped it, and whether it was removed. + private void report(Printer printer, boolean structured, String state, boolean stopped, boolean removed) { + if (!structured || embedded) return; + Map result = new LinkedHashMap<>(); + result.put("container", global.container); + result.put("state", state); + result.put("stopped", stopped); + result.put("removed", removed); + printer.structured(result); + } } diff --git a/src/main/java/io/floci/cli/commands/WaitCommand.java b/src/main/java/io/floci/cli/commands/WaitCommand.java index a9ed3a0..030db5a 100644 --- a/src/main/java/io/floci/cli/commands/WaitCommand.java +++ b/src/main/java/io/floci/cli/commands/WaitCommand.java @@ -70,6 +70,12 @@ public class WaitCommand implements Callable { */ String knownEndpoint; + /** + * Set by {@code start}, which reports the outcome in its own structured result: this wait + * then prints no document of its own, so stdout carries exactly one. + */ + boolean embedded; + static final long FIRST_DELAY_MS = 25; static final long MAX_DELAY_MS = 500; static final Duration MAX_REQUEST_TIMEOUT = Duration.ofSeconds(10); @@ -99,7 +105,7 @@ public class WaitCommand implements Callable { if (isReady(client, service, requestTimeout(Duration.between(Instant.now(), deadline)))) { if (spinner) clearSpinner(printer); if (printer.format() != OutputFormat.text) { - printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint)); + if (!embedded) printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint)); } else { printer.println(Ansi.green(profile.displayName() + " is ready") + " (" + effectiveEndpoint + ")"); } diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index 56a748c..0d0e264 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -8,6 +8,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.PrintStream; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -208,9 +209,17 @@ public class DockerClient { } public void pull(String image, String policy) throws DockerException { + pull(image, policy, System.out); + } + + /** + * {@link #pull(String, String)} with docker's progress written to {@code progress}. A command + * printing structured output sends it to stderr, so stdout stays one parseable document. + */ + public void pull(String image, String policy, PrintStream progress) throws DockerException { if ("never".equalsIgnoreCase(policy)) return; if ("missing".equalsIgnoreCase(policy) && isImagePresent(image)) return; - runStreaming("docker", "pull", "--", image); + runStreaming(progress, "docker", "pull", "--", image); } public String startContainer(List args) throws DockerException { @@ -249,7 +258,7 @@ public class DockerClient { if (since != null && !since.isBlank()) { cmd.add("--since"); cmd.add(since); } cmd.add("--"); cmd.add(name); - runStreaming(cmd.toArray(String[]::new)); + runStreaming(System.out, cmd.toArray(String[]::new)); } private String run(String... cmd) throws DockerException { @@ -304,7 +313,7 @@ public class DockerClient { return words.toString(); } - private void runStreaming(String... cmd) throws DockerException { + private void runStreaming(PrintStream stdout, String... cmd) throws DockerException { Process proc = null; boolean finished = false; try { @@ -312,7 +321,7 @@ public class DockerClient { proc = started; Thread out = new Thread(() -> { try (var reader = new BufferedReader(new InputStreamReader(started.getInputStream()))) { - reader.lines().forEach(System.out::println); + reader.lines().forEach(stdout::println); } catch (IOException ignored) {} }); Thread err = new Thread(() -> { diff --git a/src/test/java/io/floci/cli/unit/ActionOutputTest.java b/src/test/java/io/floci/cli/unit/ActionOutputTest.java new file mode 100644 index 0000000..85fe29f --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ActionOutputTest.java @@ -0,0 +1,400 @@ +package io.floci.cli.unit; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MappingIterator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.RestartCommand; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.commands.StatusCommand; +import io.floci.cli.commands.StopCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerClient.DockerHost; +import io.floci.cli.docker.DockerClient.Kind; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * BL-056 and BL-057: start, stop and restart print one structured document with -o json/yaml and + * nothing else on stdout, and status says through its exit code whether the instance is up. + */ +class ActionOutputTest { + + // A remote daemon, so start does not probe the local port its own stub server listens on. + private static final DockerHost REMOTE = new DockerHost(Kind.TCP, null, "tcp://build-host:2375"); + // One document and nothing after it: a second value on stdout fails the parse. + private static final ObjectMapper JSON = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + + /** The single YAML document on {@code stdout}; fails when there are several, or none. */ + private static JsonNode oneYamlDocument(String stdout) throws Exception { + List documents = new ArrayList<>(); + try (MappingIterator all = YAML.readerFor(JsonNode.class).readValues(stdout)) { + all.forEachRemaining(documents::add); + } + assertEquals(1, documents.size(), "exactly one YAML document on stdout: " + stdout); + assertTrue(documents.get(0).isObject(), stdout); + return documents.get(0); + } + + @TempDir + Path tempDir; + + private HttpServer emulator; + private int port; + + @BeforeEach + void startEmulatorStub() throws Exception { + emulator = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + emulator.createContext("/", exchange -> { + byte[] body = "{\"version\":\"1.6.0\",\"edition\":\"community\",\"services\":[\"s3\"]}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + exchange.close(); + }); + emulator.start(); + port = emulator.getAddress().getPort(); + } + + @AfterEach + void stopEmulatorStub() { + emulator.stop(0); + } + + /** A docker that holds one container (or none) and records what was asked of it. */ + private static class FakeDocker extends DockerClient { + final List calls = new ArrayList<>(); + String state; // null: no such container + String ports = ""; + + FakeDocker(String state) { + this.state = state; + } + + @Override + public DockerHost daemonHost() { + return REMOTE; + } + + @Override + public Optional inspectContainer(String name) { + return state == null ? Optional.empty() + : Optional.of(new ContainerInfo("abc123", name, "floci/floci:latest", state, ports)); + } + + @Override + public Optional inspectRunSettings(String name, int containerPort) { + return Optional.empty(); + } + + @Override + public void pull(String image, String policy) { + calls.add("pull:stdout"); + System.out.println("latest: Pulling from floci/floci"); + } + + @Override + public void pull(String image, String policy, PrintStream progress) { + calls.add("pull:" + (progress == System.err ? "stderr" : "other")); + progress.println("latest: Pulling from floci/floci"); + } + + @Override + public String startContainer(List args) { + calls.add("run"); + state = "running"; + return "0123456789abcdef0123"; + } + + @Override + public void stopContainer(String name, int timeout) { + calls.add("stop"); + state = "exited"; + } + + @Override + public void removeContainer(String name) { + calls.add("rm"); + state = null; + } + } + + private record Run(int exit, String out, String err) {} + + private Run execute(Callable command, String... args) { + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + int exit = new CommandLine(command) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir))) + .execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + private String[] startArgs(String... more) { + List args = new ArrayList<>(List.of("--port", String.valueOf(port), "--container", "floci-actions")); + args.addAll(List.of(more)); + return args.toArray(String[]::new); + } + + // ---- start ----------------------------------------------------------------------------------- + + @Test + void startPrintsOneJsonDocumentAndKeepsProgressOffStdout() throws Exception { + FakeDocker docker = new FakeDocker(null); + + Run r = execute(new StartCommand(ProductProfile.AWS, docker), startArgs("-o", "json", "--pull", "always")); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); // fails if anything but the document is on stdout + assertEquals("floci-actions", json.path("container").asText()); + assertEquals("0123456789abcdef0123", json.path("id").asText()); + assertEquals("floci/floci:latest", json.path("image").asText()); + assertEquals("http://localhost:" + port, json.path("endpoint").asText()); + assertEquals("running", json.path("state").asText()); + assertTrue(json.path("ready").asBoolean()); + assertEquals(List.of("pull:stderr", "run"), docker.calls); + assertTrue(r.err().contains("Pulling from"), "docker's pull progress goes to stderr: " + r.err()); + assertFalse(r.out().contains("Starting"), r.out()); + } + + @Test + void aDetachedStartReportsNoReadiness() throws Exception { + Run r = execute(new StartCommand(ProductProfile.AWS, new FakeDocker(null)), startArgs("-o", "json", "--detach")); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("running", json.path("state").asText()); + assertFalse(json.has("ready"), "readiness was not waited for: " + r.out()); + } + + @Test + void startInYamlIsOneDocumentToo() throws Exception { + Run r = execute(new StartCommand(ProductProfile.AWS, new FakeDocker(null)), startArgs("-o", "yaml", "--detach")); + + assertEquals(0, r.exit(), r.err()); + JsonNode yaml = oneYamlDocument(r.out()); + assertEquals("floci-actions", yaml.path("container").asText()); + assertEquals("running", yaml.path("state").asText()); + assertEquals(5, yaml.size(), "container, id, image, endpoint, state: " + r.out()); + } + + @Test + void anythingExtraOnStdoutFailsTheseTests() { + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\n{\"b\":2}\n")); + assertThrows(Exception.class, () -> JSON.readTree("{\"a\":1}\nStarting...\n")); + assertThrows(AssertionError.class, () -> oneYamlDocument("a: 1\n---\nb: 2\n")); + } + + /** A container that died while start waited for it is reported as it is, not as running. */ + @Test + void aContainerThatExitedDuringTheWaitIsNotReportedRunning() throws Exception { + emulator.stop(0); // nothing answers the readiness poll + FakeDocker docker = new FakeDocker(null) { + @Override + public String startContainer(List args) { + String id = super.startContainer(args); + state = "exited"; // it crashed right after docker run returned + return id; + } + }; + StartCommand start = new StartCommand(ProductProfile.AWS, docker) { + @Override + protected String readinessTimeout() { + return "300ms"; + } + }; + + Run r = execute(start, startArgs("-o", "json")); + + assertEquals(1, r.exit()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("exited", json.path("state").asText()); + assertFalse(json.path("ready").asBoolean()); + } + + /** Text output is what it was: the progress lines, and docker's pull output on stdout. */ + @Test + void startInTextStillNarrates() { + FakeDocker docker = new FakeDocker(null); + + Run r = execute(new StartCommand(ProductProfile.AWS, docker), startArgs("--detach", "--pull", "always")); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("Container started"), r.out()); + assertTrue(r.out().contains("Detached."), r.out()); + assertEquals(List.of("pull:stdout", "run"), docker.calls); + assertFalse(r.out().contains("\"container\""), r.out()); + } + + // ---- stop ------------------------------------------------------------------------------------ + + @ParameterizedTest + @CsvSource({"false, exited, stop", "true, removed, stop;rm"}) + void stopReportsWhatItDid(boolean remove, String state, String calls) throws Exception { + FakeDocker docker = new FakeDocker("running"); + List args = new ArrayList<>(List.of("-o", "json", "--container", "floci-actions")); + if (remove) args.add("--remove"); + + Run r = execute(new StopCommand(ProductProfile.AWS, docker), args.toArray(String[]::new)); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("floci-actions", json.path("container").asText()); + assertEquals(state, json.path("state").asText()); + assertTrue(json.path("stopped").asBoolean()); + assertEquals(remove, json.path("removed").asBoolean()); + assertEquals(List.of(calls.split(";")), docker.calls); + } + + /** A container run with docker's --rm is gone once it stops, whatever --remove said. */ + @ParameterizedTest + @CsvSource({"false", "true"}) + void aContainerDockerRemovesItselfIsReportedRemoved(boolean remove) throws Exception { + FakeDocker docker = new FakeDocker("running") { + @Override + public void stopContainer(String name, int timeout) { + calls.add("stop"); + state = null; // --rm: docker removed it + } + }; + List args = new ArrayList<>(List.of("-o", "json")); + if (remove) args.add("--remove"); + + Run r = execute(new StopCommand(ProductProfile.AWS, docker), args.toArray(String[]::new)); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("removed", json.path("state").asText()); + assertTrue(json.path("removed").asBoolean()); + assertEquals(List.of("stop"), docker.calls, "nothing left to remove"); + } + + @Test + void stoppingAContainerThatIsNotRunningSaysSo() throws Exception { + Run r = execute(new StopCommand(ProductProfile.AWS, new FakeDocker("exited")), "-o", "json"); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("exited", json.path("state").asText()); + assertFalse(json.path("stopped").asBoolean()); + assertFalse(json.path("removed").asBoolean()); + } + + @Test + void stopInTextStillNarrates() { + Run r = execute(new StopCommand(ProductProfile.AWS, new FakeDocker("running")), "--remove"); + + assertTrue(r.out().contains("Stopped."), r.out()); + assertTrue(r.out().contains("Container removed."), r.out()); + } + + // ---- restart --------------------------------------------------------------------------------- + + /** A restart is a stop and a start, but its structured output is the one document of the start. */ + @Test + void restartPrintsOneDocument() throws Exception { + FakeDocker docker = new FakeDocker("running"); + docker.ports = port + "->4566/tcp"; + RestartCommand restart = new RestartCommand(ProductProfile.AWS, docker) { + @Override + public StartCommand buildStartCommand() { + StartCommand start = new StartCommand(ProductProfile.AWS, docker); + new CommandLine(start).parseArgs(startArgs("-o", "json")); + return start; + } + }; + + Run r = execute(restart, "-o", "json", "--container", "floci-actions"); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = JSON.readTree(r.out()); + assertEquals("running", json.path("state").asText()); + assertTrue(json.path("ready").asBoolean()); + assertEquals(List.of("stop", "rm", "pull:stderr", "run"), docker.calls); + } + + // ---- status ---------------------------------------------------------------------------------- + + @ParameterizedTest + @CsvSource({ + "running, true, 0", + "running, false, 1", + "exited, false, 1", + "exited, true, 1", // something else answers there; this container is down + "not found, true, 0", // a remote endpoint, or a Compose service under another name + "not found, false, 1", + "'error: Cannot connect to the Docker daemon', true, 0", + "'error: Cannot connect to the Docker daemon', false, 1"}) + void statusExitCodeSaysWhetherTheInstanceIsUp(String state, boolean reachable, int exit) { + assertEquals(exit, StatusCommand.exitCode(state, reachable)); + } + + @Test + void statusOfARunningInstanceExitsZero() throws Exception { + FakeDocker docker = new FakeDocker("running"); + docker.ports = port + "->4566/tcp"; + + Run json = execute(new StatusCommand(ProductProfile.AWS, docker), "-o", "json"); + Run text = execute(new StatusCommand(ProductProfile.AWS, docker)); + + assertEquals(0, json.exit(), json.err()); + assertTrue(JSON.readTree(json.out()).path("reachable").asBoolean()); + assertEquals(0, text.exit()); + assertTrue(text.out().contains("Reachable: yes"), text.out()); + } + + @Test + void statusOfAnInstanceThatIsDownExitsOneInEveryFormat() throws Exception { + int closed; + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + closed = socket.getLocalPort(); + } + FakeDocker docker = new FakeDocker(null); + String endpoint = "http://127.0.0.1:" + closed; + + Run json = execute(new StatusCommand(ProductProfile.AWS, docker), "-o", "json", "--endpoint", endpoint); + Run text = execute(new StatusCommand(ProductProfile.AWS, docker), "--endpoint", endpoint); + + assertEquals(1, json.exit()); + assertFalse(JSON.readTree(json.out()).path("reachable").asBoolean()); + assertEquals("not found", JSON.readTree(json.out()).path("state").asText()); + assertEquals(1, text.exit()); + assertTrue(text.out().contains("floci start"), text.out()); + } +} diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 0930b69..0e8fd82 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -60,6 +60,11 @@ class StartPreflightTest { calls.add("pull"); } + @Override + public void pull(String image, String policy, PrintStream progress) { + calls.add("pull"); + } + @Override public String startContainer(List args) { runArgs.addAll(args);