feat(cli): structured output for start, stop and restart, and a status exit code scripts can use (#60)

* feat(cli): structured output for start, stop and restart, and a status exit code scripts can use

start, stop and restart print one document with -o json or -o yaml and keep progress off stdout. status exits 1 when the instance is not up (it always exited 0). logs stays plain text and says so when -o is passed.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* 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 <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-11 08:59:58 -05:00
1 parent 804e355936
commit 4a9a9b5a4a
10 files changed
+588 -31

No files matched your search

@@ -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<Integer> {
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.");
}
@@ -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<Integer> {
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<Integer> {
* 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;
@@ -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<Integer> {
@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<String> progress = structured ? line -> { } : printer::println;
String invalid = validationError();
if (invalid != null) {
@@ -323,7 +331,7 @@ public class StartCommand implements Callable<Integer> {
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<Integer> {
// 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<Integer> {
List<String> 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<String, Object> result(String id, String endpoint, Boolean ready) {
Map<String, Object> 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";
}
}
/**
@@ -32,14 +32,21 @@ public class StatusCommand implements Callable<Integer> {
}
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<Integer> {
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<Integer> {
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;
}
}
@@ -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<Integer> {
}
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<Integer> {
@Override
public Integer call() {
Printer printer = global.printer();
DockerClient docker = new DockerClient();
boolean structured = printer.format() != OutputFormat.text;
Consumer<String> progress = structured ? line -> { } : printer::println;
try {
var info = docker.inspectContainer(global.container);
@@ -49,11 +68,12 @@ public class StopCommand implements Callable<Integer> {
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<Integer> {
}
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<String, Object> result = new LinkedHashMap<>();
result.put("container", global.container);
result.put("state", state);
result.put("stopped", stopped);
result.put("removed", removed);
printer.structured(result);
}
}
@@ -70,6 +70,12 @@ public class WaitCommand implements Callable<Integer> {
*/
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<Integer> {
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 + ")");
}
@@ -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<String> 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(() -> {