mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
Merge remote-tracking branch 'origin/main' into feat/cli-ergonomics
config validate keeps the structure-based checks from main and prints its marks through Glyphs. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
16 files changed
+1575
-90
No files matched your search
@@ -471,16 +471,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
|
||||
@@ -735,6 +746,21 @@ Each product tree has its own `config show|validate|profile` (`floci gcp config
|
||||
uses that product's defaults; `config default-product` is available through bare `floci config`
|
||||
and `floci aws config`, but not through the GCP, Azure, or OCI config trees.
|
||||
|
||||
`config validate` reads the Compose file and checks the service that runs the emulator (found by
|
||||
its image; a file with a single service is checked whatever its image is):
|
||||
|
||||
| Check | Result when it fails |
|
||||
|---|---|
|
||||
| The emulator port is mapped over TCP (`"4566:4566"`, `"5566:4566"`, `"127.0.0.1:5566:4566"`, a range, or the long form; any host port works) | error |
|
||||
| A socket is mounted at `/var/run/docker.sock` in the container (the host side may be any socket) | error where the product needs it, otherwise a warning |
|
||||
| The volume at `/app/data` is writable and not bound to a file | error |
|
||||
| A volume at `/app/data` comes with `<PREFIX>_STORAGE_MODE=persistent`, and the other way round | warning |
|
||||
| The image tag is not older than the oldest version this CLI supports (AWS tree) | warning |
|
||||
|
||||
It exits 1 when there is an error and 0 otherwise. `-o json` and `-o yaml` print
|
||||
`file`, `service`, `valid`, `errors` and `warnings`, also for a file that cannot be parsed. An
|
||||
`env_file` is not read, so nothing is said about a storage mode it may set.
|
||||
|
||||
#### Profiles
|
||||
|
||||
Profiles are stored in `~/.floci/profiles/<name>.yaml`. Pass `--profile <name>` to any command to
|
||||
@@ -861,6 +887,8 @@ floci completion bash >> ~/.bashrc
|
||||
floci completion zsh >> ~/.zshrc
|
||||
```
|
||||
|
||||
Completion scripts are generated for bash and zsh. Any other shell name is a usage error (exit 2).
|
||||
|
||||
### `floci update`
|
||||
|
||||
Self-update the CLI in place: downloads the release binary from GitHub, verifies its
|
||||
|
||||
@@ -21,7 +21,9 @@ public class CompletionCommand implements Callable<Integer> {
|
||||
@Spec
|
||||
Model.CommandSpec spec;
|
||||
|
||||
@Parameters(index = "0", description = "Shell type: bash, zsh, fish, powershell", paramLabel = "bash|zsh|fish|powershell")
|
||||
// Only the shells a script is generated for: picocli writes bash completion, which zsh loads
|
||||
// through bashcompinit. Listing fish and powershell here promised scripts that do not exist.
|
||||
@Parameters(index = "0", description = "Shell type: bash or zsh", paramLabel = "bash|zsh")
|
||||
String shell;
|
||||
|
||||
@Override
|
||||
@@ -36,13 +38,13 @@ public class CompletionCommand implements Callable<Integer> {
|
||||
case "bash" -> AutoComplete.bash("floci", root);
|
||||
case "zsh" -> AutoComplete.bash("floci", root); // zsh is bash-compatible; picocli bash script works for zsh too
|
||||
default -> {
|
||||
printer.error("Shell '" + shell + "' not supported. Supported: bash, zsh\n" +
|
||||
"For fish and powershell, track https://github.com/floci-io/floci-cli/issues");
|
||||
printer.error("Shell '" + shell + "' is not supported.\nUse bash or zsh.");
|
||||
yield null;
|
||||
}
|
||||
};
|
||||
|
||||
if (script == null) return 1;
|
||||
// A value the command cannot accept, like any other bad argument.
|
||||
if (script == null) return ExitCode.USAGE;
|
||||
System.out.print(script);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -33,14 +33,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";
|
||||
@@ -83,9 +90,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"));
|
||||
@@ -110,7 +118,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 + ")");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package io.floci.cli.commands.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.doctor.checks.ImageVersionCheck;
|
||||
import io.floci.cli.update.Version;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What {@code config validate} finds in a Compose file. It reads the parsed document and looks
|
||||
* at the one service that runs the product's emulator, so a port or a volume on some other
|
||||
* service is never taken for the emulator's.
|
||||
*/
|
||||
public final class ComposeCheck {
|
||||
|
||||
/** The directory the emulator keeps its state in, inside the container. */
|
||||
static final String DATA_DIR = "/app/data";
|
||||
|
||||
private ComposeCheck() {}
|
||||
|
||||
/**
|
||||
* The findings for one file. {@code service} is the Compose service that was checked, or null
|
||||
* when none could be told apart as the emulator's.
|
||||
*/
|
||||
public record Report(String service, List<String> errors, List<String> warnings) {
|
||||
|
||||
public boolean valid() {
|
||||
return errors.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the emulator looks for the Docker socket, inside the container. */
|
||||
static final String DOCKER_SOCK = "/var/run/docker.sock";
|
||||
|
||||
/**
|
||||
* A volume entry, from either the short {@code src:dst[:mode]} or the long form. {@code bind}
|
||||
* is true when the source is a path on the host rather than a named volume.
|
||||
*/
|
||||
record Mount(String source, String target, boolean readOnly, boolean bind) {}
|
||||
|
||||
/**
|
||||
* @param baseDir the Compose file's directory, against which relative bind sources resolve
|
||||
*/
|
||||
public static Report analyze(JsonNode compose, ProductProfile profile, boolean dockerSockRequired,
|
||||
String dockerSockNeededFor, Path baseDir) {
|
||||
List<String> errors = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
JsonNode services = compose.path("services");
|
||||
if (!services.isObject() || services.isEmpty()) {
|
||||
errors.add("No services found: a Compose file needs a 'services' section with the "
|
||||
+ profile.displayName() + " service in it");
|
||||
return new Report(null, errors, warnings);
|
||||
}
|
||||
|
||||
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
|
||||
Map.Entry<String, JsonNode> found = null;
|
||||
for (Map.Entry<String, JsonNode> service : services.properties()) {
|
||||
String repository = repositoryOf(service.getValue().path("image").asText(""));
|
||||
if (repository.equals(profile.image()) || repository.equals("docker.io/" + profile.image())
|
||||
|| repository.equals(ghcrImage)) {
|
||||
found = service;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found == null) {
|
||||
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
|
||||
+ profile.image() + " or " + ghcrImage);
|
||||
// With one service there is no doubt which one is meant (a locally built image, a
|
||||
// mirror); with several, checking the wrong one would only mislead.
|
||||
if (services.size() != 1) {
|
||||
return new Report(null, errors, warnings);
|
||||
}
|
||||
found = services.properties().iterator().next();
|
||||
}
|
||||
|
||||
JsonNode service = found.getValue();
|
||||
List<Mount> mounts = mounts(service.path("volumes"));
|
||||
Map<String, String> environment = environment(service.path("environment"));
|
||||
int port = profile.defaultPort();
|
||||
|
||||
// The container side is what the emulator opens; the host side may be any socket (Podman's,
|
||||
// a rootless Docker's), so only the target is checked.
|
||||
if (mounts.stream().noneMatch(m -> DOCKER_SOCK.equals(stripTrailingSlash(m.target())))) {
|
||||
(dockerSockRequired ? errors : warnings)
|
||||
.add("Missing " + DOCKER_SOCK + " volume mount — required for " + dockerSockNeededFor);
|
||||
}
|
||||
|
||||
// With host networking the container's ports are the host's; there is nothing to map.
|
||||
if (!"host".equals(service.path("network_mode").asText("")) && !publishes(service.path("ports"), port)) {
|
||||
errors.add("No port mapping for " + port + " found — " + profile.displayName() + " listens on " + port
|
||||
+ " inside the container; map any host port to it, for example \"" + port + ":" + port + "\"");
|
||||
}
|
||||
|
||||
Mount data = mounts.stream().filter(m -> DATA_DIR.equals(stripTrailingSlash(m.target()))).findFirst().orElse(null);
|
||||
String storageVar = profile.envVar("STORAGE_MODE");
|
||||
String storageMode = environment.get(storageVar);
|
||||
// A value Compose will substitute (${MODE:-persistent}) cannot be judged from here, and
|
||||
// neither can one an env_file may set: the file is not read.
|
||||
boolean storageKnown = storageMode == null
|
||||
? service.path("env_file").isMissingNode() || service.path("env_file").isNull()
|
||||
: !storageMode.contains("${");
|
||||
if (data != null && storageKnown && !"persistent".equalsIgnoreCase(storageMode)) {
|
||||
warnings.add("A volume is mounted at " + DATA_DIR + " but " + storageVar + " is not 'persistent' — "
|
||||
+ "the emulator keeps its state in memory by default, so the volume stays empty");
|
||||
}
|
||||
if (data == null && "persistent".equalsIgnoreCase(storageMode)) {
|
||||
warnings.add(storageVar + " is 'persistent' but nothing is mounted at " + DATA_DIR
|
||||
+ " — the state is lost when the container is removed");
|
||||
}
|
||||
if (data != null) {
|
||||
if (data.readOnly()) {
|
||||
errors.add("The volume at " + DATA_DIR + " is mounted read-only — the emulator cannot save its state there");
|
||||
}
|
||||
String notADirectory = fileWhereADirectoryIsNeeded(data, baseDir);
|
||||
if (notADirectory != null) {
|
||||
errors.add("The volume at " + DATA_DIR + " is bound to " + notADirectory + ", which is a file, not a directory");
|
||||
}
|
||||
}
|
||||
|
||||
String tag = tagOf(service.path("image").asText(""));
|
||||
// The minimum is the AWS emulator's; the other emulators are versioned on their own lines.
|
||||
if ("aws".equals(profile.name()) && Version.isValid(tag)
|
||||
&& !ImageVersionCheck.meetsMinimum(tag, ImageVersionCheck.MIN_VERSION)) {
|
||||
warnings.add("Image tag " + tag + " is older than " + ImageVersionCheck.MIN_VERSION
|
||||
+ ", the oldest version this CLI supports — use a newer tag");
|
||||
}
|
||||
|
||||
return new Report(found.getKey(), errors, warnings);
|
||||
}
|
||||
|
||||
/** {@code registry/name:tag@digest} without its tag and digest. */
|
||||
public static String repositoryOf(String image) {
|
||||
String reference = image.strip();
|
||||
int digest = reference.indexOf('@');
|
||||
if (digest >= 0) reference = reference.substring(0, digest);
|
||||
int colon = reference.lastIndexOf(':');
|
||||
// A colon before the last slash is a registry port, not a tag.
|
||||
return colon > reference.lastIndexOf('/') ? reference.substring(0, colon) : reference;
|
||||
}
|
||||
|
||||
/** The tag of an image reference, or an empty string when it has none. */
|
||||
public static String tagOf(String image) {
|
||||
String reference = image.strip();
|
||||
int digest = reference.indexOf('@');
|
||||
if (digest >= 0) reference = reference.substring(0, digest);
|
||||
int colon = reference.lastIndexOf(':');
|
||||
return colon > reference.lastIndexOf('/') ? reference.substring(colon + 1) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one of a service's {@code ports} entries reaches {@code port} inside the container,
|
||||
* whatever the host side is: {@code 4566}, {@code "4566:4566"}, {@code "5566:4566"},
|
||||
* {@code "127.0.0.1:5566:4566/tcp"}, a range that contains it, or the long form's {@code target}.
|
||||
*/
|
||||
public static boolean publishes(JsonNode ports, int port) {
|
||||
for (JsonNode entry : ports) {
|
||||
if (entry.isObject()) {
|
||||
if (entry.path("target").asInt(-1) == port && isTcp(entry.path("protocol").asText(""))) return true;
|
||||
continue;
|
||||
}
|
||||
String text = entry.asText("").strip();
|
||||
int slash = text.indexOf('/');
|
||||
String protocol = slash >= 0 ? text.substring(slash + 1) : "";
|
||||
if (slash >= 0) text = text.substring(0, slash);
|
||||
String container = text.substring(text.lastIndexOf(':') + 1);
|
||||
if (isTcp(protocol) && inRange(container, port)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. An
|
||||
// entry without a protocol is TCP, as Compose reads it.
|
||||
private static boolean isTcp(String protocol) {
|
||||
return protocol.isBlank() || "tcp".equalsIgnoreCase(protocol.strip());
|
||||
}
|
||||
|
||||
private static boolean inRange(String spec, int port) {
|
||||
try {
|
||||
int dash = spec.indexOf('-');
|
||||
if (dash < 0) return Integer.parseInt(spec.strip()) == port;
|
||||
return Integer.parseInt(spec.substring(0, dash).strip()) <= port
|
||||
&& port <= Integer.parseInt(spec.substring(dash + 1).strip());
|
||||
} catch (NumberFormatException e) {
|
||||
return false; // a ${VARIABLE} or something else that is not a number
|
||||
}
|
||||
}
|
||||
|
||||
static List<Mount> mounts(JsonNode volumes) {
|
||||
List<Mount> mounts = new ArrayList<>();
|
||||
for (JsonNode entry : volumes) {
|
||||
if (entry.isObject()) {
|
||||
// In the long form the type says what the source is; a bind's is a host path
|
||||
// even when it is a bare name like 'data'.
|
||||
mounts.add(new Mount(entry.path("source").asText(""), entry.path("target").asText(""),
|
||||
entry.path("read_only").asBoolean(false), "bind".equals(entry.path("type").asText(""))));
|
||||
continue;
|
||||
}
|
||||
String text = entry.asText("");
|
||||
// A Windows source (C:\data:/app/data) has a colon of its own after the drive letter.
|
||||
int from = startsWithDrive(text) ? 2 : 0;
|
||||
int first = text.indexOf(':', from);
|
||||
if (first < 0) {
|
||||
mounts.add(new Mount("", text, false, false)); // an anonymous volume: only the container path
|
||||
continue;
|
||||
}
|
||||
String source = text.substring(0, first);
|
||||
String rest = text.substring(first + 1);
|
||||
int second = rest.indexOf(':');
|
||||
String target = second < 0 ? rest : rest.substring(0, second);
|
||||
String mode = second < 0 ? "" : rest.substring(second + 1);
|
||||
// In the short form a source is a host path when it looks like one; a bare name is a
|
||||
// named volume.
|
||||
boolean bind = source.startsWith("/") || source.startsWith(".") || source.startsWith("~")
|
||||
|| startsWithDrive(source);
|
||||
mounts.add(new Mount(source, target, List.of(mode.split(",")).contains("ro"), bind));
|
||||
}
|
||||
return mounts;
|
||||
}
|
||||
|
||||
private static boolean startsWithDrive(String text) {
|
||||
return text.length() > 2 && Character.isLetter(text.charAt(0)) && text.charAt(1) == ':'
|
||||
&& (text.charAt(2) == '\\' || text.charAt(2) == '/');
|
||||
}
|
||||
|
||||
/** A service's {@code environment}, from either the mapping or the {@code KEY=value} list form. */
|
||||
static Map<String, String> environment(JsonNode environment) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
if (environment.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> entry : environment.properties()) {
|
||||
values.put(entry.getKey(), entry.getValue().asText(""));
|
||||
}
|
||||
} else {
|
||||
for (JsonNode entry : environment) {
|
||||
String text = entry.asText("");
|
||||
int equals = text.indexOf('=');
|
||||
if (equals > 0) values.put(text.substring(0, equals), text.substring(equals + 1));
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static String stripTrailingSlash(String path) {
|
||||
return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
|
||||
}
|
||||
|
||||
// Best effort: only a bind source that already exists on this machine can be looked at. A
|
||||
// named volume, a ${VARIABLE}, a home-relative path Compose expands itself, or a path that
|
||||
// is not there yet says nothing.
|
||||
private static String fileWhereADirectoryIsNeeded(Mount mount, Path baseDir) {
|
||||
if (!mount.bind() || mount.source().isBlank() || mount.source().contains("${") || mount.source().startsWith("~")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Path path = baseDir.resolve(mount.source()).normalize();
|
||||
return Files.isRegularFile(path) ? path.toString() : null;
|
||||
} catch (InvalidPathException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
package io.floci.cli.commands.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.output.Ansi;
|
||||
import io.floci.cli.output.Glyphs;
|
||||
import io.floci.cli.output.OutputFormat;
|
||||
import io.floci.cli.output.Printer;
|
||||
import picocli.CommandLine.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Command(
|
||||
name = "validate",
|
||||
@@ -22,6 +26,8 @@ import java.util.regex.Pattern;
|
||||
)
|
||||
public class ConfigValidateCommand implements Callable<Integer> {
|
||||
|
||||
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
protected final ProductProfile profile;
|
||||
private final boolean dockerSockRequired;
|
||||
private final String dockerSockNeededFor;
|
||||
@@ -62,50 +68,68 @@ public class ConfigValidateCommand implements Callable<Integer> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
printer.println(Ansi.bold("Validating") + " " + composeFile);
|
||||
JsonNode compose = null;
|
||||
String unreadable = null;
|
||||
try {
|
||||
compose = YAML.readTree(content);
|
||||
if (compose == null || !compose.isObject()) {
|
||||
unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping";
|
||||
}
|
||||
} catch (IOException e) {
|
||||
String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable");
|
||||
unreadable = "Could not read " + composeFile + " as YAML: " + reason;
|
||||
}
|
||||
if (unreadable != null) {
|
||||
// Structured output always carries the report, so a script reading it gets 'valid: false'
|
||||
// and the reason rather than nothing.
|
||||
if (printer.format() != OutputFormat.text) {
|
||||
printer.structured(document(composeFile, new ComposeCheck.Report(null, List.of(unreadable), List.of())));
|
||||
} else {
|
||||
printer.error(unreadable, "Fix the file's syntax, or pass another with --file.");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
Path baseDir = composeFile.toAbsolutePath().getParent();
|
||||
ComposeCheck.Report report = ComposeCheck.analyze(compose, profile, dockerSockRequired, dockerSockNeededFor, baseDir);
|
||||
|
||||
if (printer.format() != OutputFormat.text) {
|
||||
printer.structured(document(composeFile, report));
|
||||
return report.valid() ? 0 : 1;
|
||||
}
|
||||
|
||||
printer.println(Ansi.bold("Validating") + " " + composeFile
|
||||
+ (report.service() == null ? "" : Ansi.gray(" (service: " + report.service() + ")")));
|
||||
printer.println("");
|
||||
|
||||
List<String> issues = new ArrayList<>();
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
// Check for docker.sock mount (an error where the product needs it for core services)
|
||||
if (!content.contains("/var/run/docker.sock")) {
|
||||
(dockerSockRequired ? issues : warnings)
|
||||
.add("Missing /var/run/docker.sock volume mount — required for " + dockerSockNeededFor);
|
||||
}
|
||||
|
||||
// Check port mapping
|
||||
int port = profile.defaultPort();
|
||||
if (!Pattern.compile(port + "\\s*:\\s*" + port).matcher(content).find()) {
|
||||
issues.add("Port mapping " + port + ":" + port + " not found — " + profile.displayName()
|
||||
+ " listens on " + port + " by default");
|
||||
}
|
||||
|
||||
// Check for the product image
|
||||
String ghcrImage = "ghcr.io/floci-io/" + profile.image().substring(profile.image().indexOf('/') + 1);
|
||||
if (!content.contains(profile.image()) && !content.contains(ghcrImage)) {
|
||||
warnings.add(profile.displayName() + " image reference not detected — ensure your service uses "
|
||||
+ profile.image() + " or " + ghcrImage);
|
||||
}
|
||||
|
||||
for (String issue : issues) {
|
||||
for (String issue : report.errors()) {
|
||||
printer.println(" " + Ansi.red(Glyphs.fail()) + " " + issue);
|
||||
}
|
||||
for (String warn : warnings) {
|
||||
for (String warn : report.warnings()) {
|
||||
printer.println(" " + Ansi.yellow(Glyphs.warn()) + " " + warn);
|
||||
}
|
||||
if (issues.isEmpty() && warnings.isEmpty()) {
|
||||
if (report.errors().isEmpty() && report.warnings().isEmpty()) {
|
||||
printer.println(" " + Ansi.green(Glyphs.ok()) + " Compose file looks good");
|
||||
}
|
||||
|
||||
printer.println("");
|
||||
if (!issues.isEmpty()) {
|
||||
printer.println(issues.size() + " error(s) found.");
|
||||
if (!report.valid()) {
|
||||
printer.println(report.errors().size() + " error(s) found.");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static Map<String, Object> document(Path composeFile, ComposeCheck.Report report) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("file", composeFile.toString());
|
||||
out.put("service", report.service());
|
||||
out.put("valid", report.valid());
|
||||
out.put("errors", report.errors());
|
||||
out.put("warnings", report.warnings());
|
||||
return out;
|
||||
}
|
||||
|
||||
private Path resolveComposeFile() {
|
||||
if (file != null) return Path.of(file);
|
||||
for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) {
|
||||
|
||||
@@ -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;
|
||||
@@ -67,18 +68,10 @@ public class DockerClient {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) throws DockerException {
|
||||
String out;
|
||||
Optional<JsonNode> document = inspectDocument(name);
|
||||
if (document.isEmpty()) return Optional.empty();
|
||||
try {
|
||||
out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name);
|
||||
} catch (DockerException e) {
|
||||
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (out.isBlank()) return Optional.empty();
|
||||
try {
|
||||
JsonNode c = JSON.readTree(out);
|
||||
JsonNode c = document.get();
|
||||
String image = textOrNull(c.path("Config").path("Image"));
|
||||
Integer hostPort = null;
|
||||
JsonNode binding = c.path("HostConfig").path("PortBindings").path(containerPort + "/tcp");
|
||||
@@ -133,26 +126,56 @@ public class DockerClient {
|
||||
}
|
||||
|
||||
public Optional<ContainerInfo> inspectContainer(String name) throws DockerException {
|
||||
Optional<JsonNode> document = inspectDocument(name);
|
||||
if (document.isEmpty()) return Optional.empty();
|
||||
JsonNode c = document.get();
|
||||
String reported = c.path("Name").asText("").replaceFirst("^/", "");
|
||||
return Optional.of(new ContainerInfo(
|
||||
c.path("Id").asText(""),
|
||||
reported.isBlank() ? name : reported,
|
||||
c.path("Config").path("Image").asText(""),
|
||||
c.path("State").path("Status").asText(""),
|
||||
publishedPorts(c.path("NetworkSettings").path("Ports"))));
|
||||
}
|
||||
|
||||
/**
|
||||
* The published ports of an inspect document as {@code "14566->4566/tcp 18080->8080/tcp"}:
|
||||
* host port, then the container side. A port that is exposed but not published has no
|
||||
* binding and is left out.
|
||||
*/
|
||||
public static String publishedPorts(JsonNode ports) {
|
||||
StringBuilder published = new StringBuilder();
|
||||
for (var port : ports.properties()) {
|
||||
JsonNode bindings = port.getValue();
|
||||
if (!bindings.isArray() || bindings.isEmpty()) continue;
|
||||
String hostPort = bindings.get(0).path("HostPort").asText("");
|
||||
if (hostPort.isBlank()) continue;
|
||||
if (!published.isEmpty()) published.append(' ');
|
||||
published.append(hostPort).append("->").append(port.getKey());
|
||||
}
|
||||
return published.toString();
|
||||
}
|
||||
|
||||
// The container's whole inspect document, or empty when there is no such container. One
|
||||
// JSON read serves every caller; a field-by-field Go template had to be split on a
|
||||
// delimiter, which a value could contain.
|
||||
private Optional<JsonNode> inspectDocument(String name) throws DockerException {
|
||||
String out;
|
||||
try {
|
||||
String out = run("docker", "container", "inspect",
|
||||
"--format",
|
||||
"{{.Id}}|{{.Name}}|{{.Config.Image}}|{{.State.Status}}|" +
|
||||
"{{range $p, $b := .NetworkSettings.Ports}}{{if $b}}{{(index $b 0).HostPort}}->{{$p}} {{end}}{{end}}",
|
||||
"--", name);
|
||||
if (out.isBlank()) return Optional.empty();
|
||||
String[] parts = out.trim().split("\\|", -1);
|
||||
return Optional.of(new ContainerInfo(
|
||||
parts.length > 0 ? parts[0] : "", // id
|
||||
parts.length > 1 ? parts[1].replaceFirst("^/", "") : name,
|
||||
parts.length > 2 ? parts[2] : "", // image
|
||||
parts.length > 3 ? parts[3] : "", // status
|
||||
parts.length > 4 ? parts[4].trim() : "")); // ports
|
||||
out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name);
|
||||
} catch (DockerException e) {
|
||||
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (out.isBlank()) return Optional.empty();
|
||||
try {
|
||||
return Optional.of(JSON.readTree(out));
|
||||
} catch (Exception e) {
|
||||
throw new DockerException("Could not read the details of container '" + name + "': " + e.getMessage()
|
||||
+ "\n" + CHECK_DOCKER);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isImagePresent(String image) throws DockerException {
|
||||
@@ -186,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 {
|
||||
@@ -227,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 {
|
||||
@@ -282,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 {
|
||||
@@ -290,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(() -> {
|
||||
|
||||
@@ -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<JsonNode> documents = new ArrayList<>();
|
||||
try (MappingIterator<JsonNode> 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<String> 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<ContainerInfo> inspectContainer(String name) {
|
||||
return state == null ? Optional.empty()
|
||||
: Optional.of(new ContainerInfo("abc123", name, "floci/floci:latest", state, ports));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RunSettings> 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<String> 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<Integer> 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<String> 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<String> 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<String> 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<String> 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.FlociCli;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** BL-054: completion offers the shells it can generate a script for, and only those. */
|
||||
class CompletionCommandTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private record Run(int exit, String out, String err) {}
|
||||
|
||||
private Run run(String... args) {
|
||||
PrintStream out = System.out;
|
||||
PrintStream err = System.err;
|
||||
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outBuf));
|
||||
System.setErr(new PrintStream(errBuf));
|
||||
try {
|
||||
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(args);
|
||||
return new Run(exit, outBuf.toString(), errBuf.toString());
|
||||
} finally {
|
||||
System.setOut(out);
|
||||
System.setErr(err);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHelpListsOnlyTheShellsThatWork() {
|
||||
CommandLine completion = FlociCli.buildCommandLine(new ProfileStore(tempDir)).getSubcommands().get("completion");
|
||||
|
||||
assertEquals("bash|zsh", completion.getCommandSpec().positionalParameters().get(0).paramLabel());
|
||||
String usage = completion.getUsageMessage(CommandLine.Help.Ansi.OFF);
|
||||
assertFalse(usage.contains("fish"), usage);
|
||||
assertFalse(usage.contains("powershell"), usage);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bash", "zsh", "BASH"})
|
||||
void aSupportedShellGetsAScript(String shell) {
|
||||
Run r = run("completion", shell);
|
||||
|
||||
assertEquals(0, r.exit(), r.err());
|
||||
assertTrue(r.out().contains("floci"), "a completion script for the floci command");
|
||||
assertEquals("", r.err());
|
||||
}
|
||||
|
||||
/** A shell there is no script for is a usage error, and nothing is written to stdout to be sourced. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"fish", "powershell", "nushell"})
|
||||
void anUnsupportedShellIsAUsageError(String shell) {
|
||||
Run r = run("completion", shell);
|
||||
|
||||
assertEquals(2, r.exit());
|
||||
assertEquals("", r.out());
|
||||
assertTrue(r.err().contains("Shell '" + shell + "' is not supported."), r.err());
|
||||
assertTrue(r.err().contains("Use bash or zsh."), r.err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.floci.cli.FlociCli;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.commands.config.ComposeCheck;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** BL-055: config validate reads the Compose file's structure and checks the emulator's own service. */
|
||||
class ConfigValidateTest {
|
||||
|
||||
private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory());
|
||||
private static final String NEEDED_FOR = "Lambda, EC2";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private ComposeCheck.Report aws(String compose) throws Exception {
|
||||
return ComposeCheck.analyze(YAML.readTree(compose), ProductProfile.AWS, true, NEEDED_FOR, tempDir);
|
||||
}
|
||||
|
||||
private static String service(String ports, String extra) {
|
||||
return """
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
ports:
|
||||
- %s
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
%s""".formatted(ports, extra);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCompleteServiceHasNothingToReport() throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", ""));
|
||||
|
||||
assertEquals("floci", r.service());
|
||||
assertEquals(List.of(), r.errors());
|
||||
assertEquals(List.of(), r.warnings());
|
||||
assertTrue(r.valid());
|
||||
}
|
||||
|
||||
/** Any host port works: only the container side has to be the emulator's port. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"\"4566:4566\"", "\"5566:4566\"", "\"127.0.0.1:5566:4566\"", "\"5566:4566/tcp\"",
|
||||
"4566", "\"4566\"", "\"14510-14600:4510-4600\"", "{target: 4566, published: 5566}",
|
||||
"{target: 4566, published: \"5566\", protocol: tcp}"})
|
||||
void everyWayOfMappingTheEmulatorPortIsAccepted(String ports) throws Exception {
|
||||
assertEquals(List.of(), aws(service(ports, "")).errors(), ports);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"\"4566:8080\"", "\"8080:8080\"", "\"45660:45660\"", "8080", "{target: 8080, published: 4566}",
|
||||
"\"${HOST_PORT}:${CONTAINER_PORT}\""})
|
||||
void aMappingThatDoesNotReachTheEmulatorPortIsAnError(String ports) throws Exception {
|
||||
List<String> errors = aws(service(ports, "")).errors();
|
||||
|
||||
assertEquals(1, errors.size(), errors.toString());
|
||||
assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0));
|
||||
}
|
||||
|
||||
/** The emulator's endpoint is HTTP: a UDP mapping of the same number does not reach it. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"\"4566:4566/udp\"", "{target: 4566, published: 5566, protocol: udp}", "\"5566:4566/sctp\""})
|
||||
void aMappingThatIsNotTcpIsAnError(String ports) throws Exception {
|
||||
List<String> errors = aws(service(ports, "")).errors();
|
||||
|
||||
assertEquals(1, errors.size(), errors.toString());
|
||||
assertTrue(errors.get(0).startsWith("No port mapping for 4566 found"), errors.get(0));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"\"4566:4566/TCP\"", "{target: 4566, published: 5566, protocol: tcp}", "{target: 4566}"})
|
||||
void tcpIsAcceptedHoweverItIsSpelled(String ports) throws Exception {
|
||||
assertEquals(List.of(), aws(service(ports, "")).errors(), ports);
|
||||
}
|
||||
|
||||
/** What matters is where the socket lands in the container; the host side may be any socket. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/run/user/1000/podman/podman.sock:/var/run/docker.sock", "/var/run/docker.sock:/var/run/docker.sock:ro",
|
||||
"{type: bind, source: /var/run/docker.sock, target: /var/run/docker.sock}"})
|
||||
void aSocketMountedAtTheExpectedPathIsAccepted(String volume) throws Exception {
|
||||
assertEquals(List.of(), aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"./notdocker.sock:/tmp/notdocker.sock", "/var/run/docker.sock:/tmp/docker.sock",
|
||||
"{type: bind, source: /var/run/docker.sock, target: /run/docker.sock}"})
|
||||
void aSocketMountedSomewhereElseDoesNotCount(String volume) throws Exception {
|
||||
List<String> errors = aws(service("\"4566:4566\"", "").replace("/var/run/docker.sock:/var/run/docker.sock", volume)).errors();
|
||||
|
||||
assertEquals(1, errors.size(), errors.toString());
|
||||
assertTrue(errors.get(0).startsWith("Missing /var/run/docker.sock volume mount"), errors.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostNetworkingNeedsNoPortMapping() throws Exception {
|
||||
ComposeCheck.Report r = aws("""
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
network_mode: host
|
||||
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
|
||||
""");
|
||||
|
||||
assertEquals(List.of(), r.errors());
|
||||
}
|
||||
|
||||
/** Another service's port or socket mount must not satisfy the emulator's checks. */
|
||||
@Test
|
||||
void onlyTheEmulatorsOwnServiceCounts() throws Exception {
|
||||
ComposeCheck.Report r = aws("""
|
||||
services:
|
||||
proxy:
|
||||
image: nginx
|
||||
ports: ["4566:4566"]
|
||||
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
|
||||
floci:
|
||||
image: ghcr.io/floci-io/floci:1.6.0
|
||||
""");
|
||||
|
||||
assertEquals("floci", r.service());
|
||||
assertEquals(2, r.errors().size(), r.errors().toString());
|
||||
assertTrue(r.errors().get(0).contains("docker.sock"), r.errors().toString());
|
||||
assertTrue(r.errors().get(1).contains("No port mapping for 4566"), r.errors().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSocketIsOnlyAWarningWhereTheProductDoesNotNeedIt() throws Exception {
|
||||
JsonNode compose = YAML.readTree("""
|
||||
services:
|
||||
gcp:
|
||||
image: floci/floci-gcp:latest
|
||||
ports: ["4588:4588"]
|
||||
""");
|
||||
|
||||
ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.GCP, false, "Cloud Run", tempDir);
|
||||
|
||||
assertTrue(r.valid());
|
||||
assertEquals(1, r.warnings().size());
|
||||
assertTrue(r.warnings().get(0).contains("docker.sock"), r.warnings().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLongVolumeFormIsRead() throws Exception {
|
||||
ComposeCheck.Report r = aws("""
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci
|
||||
ports: ["4566:4566"]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /var/run/docker.sock
|
||||
target: /var/run/docker.sock
|
||||
""");
|
||||
|
||||
assertEquals(List.of(), r.errors());
|
||||
}
|
||||
|
||||
// ---- storage mode and the data volume ----------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aDataVolumeWithoutPersistentStorageIsFlagged() throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./data:/app/data\n"));
|
||||
|
||||
assertTrue(r.valid());
|
||||
assertEquals(1, r.warnings().size(), r.warnings().toString());
|
||||
assertTrue(r.warnings().get(0).contains("FLOCI_STORAGE_MODE is not 'persistent'"), r.warnings().get(0));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"""
|
||||
environment:
|
||||
FLOCI_STORAGE_MODE: persistent
|
||||
""", """
|
||||
environment:
|
||||
- FLOCI_STORAGE_MODE=persistent
|
||||
""", """
|
||||
environment:
|
||||
FLOCI_STORAGE_MODE: ${MODE:-memory}
|
||||
"""})
|
||||
void aDataVolumeWithPersistentStorageIsFine(String environment) throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - floci-data:/app/data\n" + environment));
|
||||
|
||||
assertEquals(List.of(), r.warnings(), environment);
|
||||
}
|
||||
|
||||
/** An env_file may set the storage mode; it is not read, so nothing is claimed about it. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" env_file: .env\n", " env_file:\n - .env\n - .env.local\n"})
|
||||
void anEnvFileMakesTheStorageModeUnknown(String envFile) throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", " - ./state:/app/data\n" + envFile));
|
||||
|
||||
assertEquals(List.of(), r.warnings(), envFile);
|
||||
}
|
||||
|
||||
/** A mode the file itself spells out is still judged, env_file or not. */
|
||||
@Test
|
||||
void anExplicitStorageModeIsJudgedEvenWithAnEnvFile() throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"",
|
||||
" - ./state:/app/data\n env_file: .env\n environment: {FLOCI_STORAGE_MODE: memory}\n"));
|
||||
|
||||
assertEquals(1, r.warnings().size(), r.warnings().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistentStorageWithoutADataVolumeIsFlagged() throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", " environment:\n FLOCI_STORAGE_MODE: persistent\n"));
|
||||
|
||||
assertEquals(1, r.warnings().size(), r.warnings().toString());
|
||||
assertTrue(r.warnings().get(0).contains("nothing is mounted at /app/data"), r.warnings().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStorageVariableIsTheProductsOwn() throws Exception {
|
||||
JsonNode compose = YAML.readTree("""
|
||||
services:
|
||||
oci:
|
||||
image: floci/floci-oci:latest
|
||||
ports: ["4599:4599"]
|
||||
volumes: ["./state:/app/data", "/var/run/docker.sock:/var/run/docker.sock"]
|
||||
environment:
|
||||
FLOCI_STORAGE_MODE: persistent
|
||||
""");
|
||||
|
||||
ComposeCheck.Report r = ComposeCheck.analyze(compose, ProductProfile.OCI, true, "Functions", tempDir);
|
||||
|
||||
assertTrue(r.warnings().get(0).contains("FLOCI_OCI_STORAGE_MODE is not 'persistent'"), r.warnings().toString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" - ./data:/app/data:ro\n", " - floci-data:/app/data/:ro,z\n",
|
||||
" - {type: bind, source: ./data, target: /app/data, read_only: true}\n"})
|
||||
void aReadOnlyDataVolumeIsAnError(String volume) throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", volume + " environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
|
||||
assertEquals(1, r.errors().size(), r.errors().toString());
|
||||
assertTrue(r.errors().get(0).contains("mounted read-only"), r.errors().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDataVolumeBoundToAFileIsAnError() throws Exception {
|
||||
Files.writeString(tempDir.resolve("data"), "not a directory");
|
||||
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"",
|
||||
" - ./data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
|
||||
assertEquals(1, r.errors().size(), r.errors().toString());
|
||||
assertTrue(r.errors().get(0).contains("which is a file, not a directory"), r.errors().get(0));
|
||||
}
|
||||
|
||||
/** In the long form the type says the source is a host path, even when it is a bare name. */
|
||||
@Test
|
||||
void aLongFormBindToAFileIsAnErrorEvenWithABareName() throws Exception {
|
||||
Files.writeString(tempDir.resolve("data"), "not a directory");
|
||||
|
||||
ComposeCheck.Report bind = aws(service("\"4566:4566\"",
|
||||
" - {type: bind, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
ComposeCheck.Report named = aws(service("\"4566:4566\"",
|
||||
" - {type: volume, source: data, target: /app/data}\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
ComposeCheck.Report shortNamed = aws(service("\"4566:4566\"",
|
||||
" - data:/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
|
||||
assertEquals(1, bind.errors().size(), bind.errors().toString());
|
||||
assertTrue(bind.errors().get(0).contains("which is a file, not a directory"), bind.errors().get(0));
|
||||
assertEquals(List.of(), named.errors(), "a named volume called 'data' is not the file");
|
||||
assertEquals(List.of(), shortNamed.errors(), "nor is the short form's bare name");
|
||||
}
|
||||
|
||||
/** A directory, a path that does not exist yet and a named volume say nothing against the mount. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"./state", "./not-there-yet", "floci-data", "${DATA_DIR}"})
|
||||
void otherDataSourcesAreNotJudged(String source) throws Exception {
|
||||
Files.createDirectories(tempDir.resolve("state"));
|
||||
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"",
|
||||
" - " + source + ":/app/data\n environment: {FLOCI_STORAGE_MODE: persistent}\n"));
|
||||
|
||||
assertEquals(List.of(), r.errors(), source);
|
||||
}
|
||||
|
||||
// ---- image ---------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void anImageOlderThanTheSupportedMinimumIsFlagged() throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", "floci/floci:1.4.2"));
|
||||
|
||||
assertTrue(r.valid());
|
||||
assertEquals(1, r.warnings().size(), r.warnings().toString());
|
||||
assertTrue(r.warnings().get(0).contains("Image tag 1.4.2 is older than 1.5.0"), r.warnings().get(0));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"floci/floci", "floci/floci:latest", "floci/floci:1.5.0", "floci/floci:2.0.1",
|
||||
"ghcr.io/floci-io/floci:1.6.0", "docker.io/floci/floci:1.6.0", "floci/floci:1.6.0@sha256:abc", "floci/floci:nightly"})
|
||||
void supportedOrUnversionedImagesAreNotFlagged(String image) throws Exception {
|
||||
ComposeCheck.Report r = aws(service("\"4566:4566\"", "").replace("floci/floci:latest", image));
|
||||
|
||||
assertEquals("floci", r.service(), image);
|
||||
assertEquals(List.of(), r.warnings(), image);
|
||||
}
|
||||
|
||||
@Test
|
||||
void repositoriesAndTagsAreSplitAtTheRightColon() {
|
||||
assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci:1.6.0"));
|
||||
assertEquals("1.6.0", ComposeCheck.tagOf("registry.local:5000/floci/floci:1.6.0"));
|
||||
assertEquals("registry.local:5000/floci/floci", ComposeCheck.repositoryOf("registry.local:5000/floci/floci"));
|
||||
assertEquals("", ComposeCheck.tagOf("registry.local:5000/floci/floci"));
|
||||
}
|
||||
|
||||
/** One service and no recognisable image (built locally, mirrored): it is still the one to check. */
|
||||
@Test
|
||||
void aSingleServiceIsCheckedEvenWithoutARecognisedImage() throws Exception {
|
||||
ComposeCheck.Report r = aws("""
|
||||
services:
|
||||
emulator:
|
||||
build: .
|
||||
""");
|
||||
|
||||
assertEquals("emulator", r.service());
|
||||
assertEquals(2, r.errors().size(), r.errors().toString());
|
||||
assertTrue(r.warnings().get(0).contains("image reference not detected"), r.warnings().toString());
|
||||
}
|
||||
|
||||
/** Several services and none recognisable: checking one at random would only mislead. */
|
||||
@Test
|
||||
void severalServicesWithoutARecognisedImageAreNotGuessedAt() throws Exception {
|
||||
ComposeCheck.Report r = aws("""
|
||||
services:
|
||||
web: {image: nginx}
|
||||
db: {image: postgres}
|
||||
""");
|
||||
|
||||
assertNull(r.service());
|
||||
assertEquals(List.of(), r.errors());
|
||||
assertEquals(1, r.warnings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFileWithoutServicesIsAnError() throws Exception {
|
||||
ComposeCheck.Report r = aws("version: '3'\n");
|
||||
|
||||
assertFalse(r.valid());
|
||||
assertTrue(r.errors().get(0).startsWith("No services found"), r.errors().toString());
|
||||
}
|
||||
|
||||
// ---- the command ---------------------------------------------------------------------------
|
||||
|
||||
private record Run(int exit, String out, String err) {}
|
||||
|
||||
private Run run(String... args) {
|
||||
PrintStream out = System.out;
|
||||
PrintStream err = System.err;
|
||||
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outBuf));
|
||||
System.setErr(new PrintStream(errBuf));
|
||||
try {
|
||||
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir.resolve("profiles"))).execute(args);
|
||||
return new Run(exit, outBuf.toString(), errBuf.toString());
|
||||
} finally {
|
||||
System.setOut(out);
|
||||
System.setErr(err);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonOutputCarriesTheFindingsAndTheExitCode() throws Exception {
|
||||
Path file = Files.writeString(tempDir.resolve("compose.yml"), """
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:1.4.0
|
||||
ports: ["4566:8080"]
|
||||
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
|
||||
""");
|
||||
|
||||
Run r = run("config", "validate", "-f", file.toString(), "-o", "json");
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
JsonNode json = new ObjectMapper().readTree(r.out());
|
||||
assertEquals(file.toString(), json.path("file").asText());
|
||||
assertEquals("floci", json.path("service").asText());
|
||||
assertFalse(json.path("valid").asBoolean());
|
||||
assertEquals(1, json.path("errors").size());
|
||||
assertEquals(1, json.path("warnings").size());
|
||||
assertFalse(r.out().contains("Validating"), "no text banner in structured output");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValidFileExitsZeroInEveryTree() throws Exception {
|
||||
Path file = Files.writeString(tempDir.resolve("compose.yml"), """
|
||||
services:
|
||||
gcp:
|
||||
image: floci/floci-gcp:latest
|
||||
ports: ["14588:4588"]
|
||||
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
|
||||
""");
|
||||
|
||||
Run text = run("gcp", "config", "validate", "-f", file.toString());
|
||||
Run yaml = run("gcp", "config", "validate", "-f", file.toString(), "-o", "yaml");
|
||||
|
||||
assertEquals(0, text.exit(), text.out() + text.err());
|
||||
assertTrue(text.out().contains("Compose file looks good"), text.out());
|
||||
assertEquals(0, yaml.exit());
|
||||
assertTrue(yaml.out().contains("valid: true"), yaml.out());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFileThatIsNotYamlIsReportedWithANextStep() throws Exception {
|
||||
Path file = Files.writeString(tempDir.resolve("compose.yml"), "services: [unterminated\n");
|
||||
|
||||
Run r = run("config", "validate", "-f", file.toString());
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
assertTrue(r.err().contains("as YAML"), r.err());
|
||||
assertTrue(r.err().contains("pass another with --file"), r.err());
|
||||
}
|
||||
|
||||
/** A script reading the report gets one for a file that cannot be parsed too. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"services: [unterminated\n", "- just\n- a list\n", "plain text\n"})
|
||||
void aFileThatCannotBeReadStillGetsAStructuredReport(String content) throws Exception {
|
||||
Path file = Files.writeString(tempDir.resolve("compose.yml"), content);
|
||||
|
||||
Run r = run("config", "validate", "-f", file.toString(), "-o", "json");
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
JsonNode json = new ObjectMapper().readTree(r.out());
|
||||
assertEquals(file.toString(), json.path("file").asText());
|
||||
assertTrue(json.path("service").isNull(), r.out());
|
||||
assertFalse(json.path("valid").asBoolean());
|
||||
assertEquals(1, json.path("errors").size());
|
||||
assertTrue(json.path("errors").get(0).asText().startsWith("Could not read "), r.out());
|
||||
assertEquals(0, json.path("warnings").size());
|
||||
assertEquals("", r.err());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.docker.DockerException;
|
||||
@@ -271,4 +273,74 @@ class DockerClientProcessTest {
|
||||
assertTrue(errBuf.toString().contains("+ docker rm"), errBuf.toString());
|
||||
assertTrue(errBuf.toString().contains("floci-x"), errBuf.toString());
|
||||
}
|
||||
|
||||
private DockerClient dockerPrinting(String inspectJson) throws Exception {
|
||||
Path json = Files.createTempFile(tempDir, "inspect", ".json");
|
||||
Files.writeString(json, inspectJson);
|
||||
Path fakeDocker = Files.createTempFile(tempDir, "docker", "");
|
||||
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
|
||||
assertTrue(fakeDocker.toFile().setExecutable(true));
|
||||
return new DockerClient(fakeDocker.toString());
|
||||
}
|
||||
|
||||
/** BL-046: container details come from the inspect document, not from a delimiter-split template. */
|
||||
@Test
|
||||
@DisabledOnOs(OS.WINDOWS)
|
||||
void containerDetailsAreReadFromTheInspectDocument() throws Exception {
|
||||
DockerClient docker = dockerPrinting("""
|
||||
{"Id":"0123abcd","Name":"/floci-team-b","Config":{"Image":"floci/floci:1.6.0"},
|
||||
"State":{"Status":"running"},
|
||||
"NetworkSettings":{"Ports":{"4566/tcp":[{"HostIp":"0.0.0.0","HostPort":"14566"},{"HostIp":"::","HostPort":"14566"}],
|
||||
"8080/tcp":null}}}
|
||||
""");
|
||||
|
||||
DockerClient.ContainerInfo info = docker.inspectContainer("floci-team-b").orElseThrow();
|
||||
|
||||
assertEquals("0123abcd", info.id());
|
||||
assertEquals("floci-team-b", info.name());
|
||||
assertEquals("floci/floci:1.6.0", info.image());
|
||||
assertEquals("running", info.state());
|
||||
assertEquals("14566->4566/tcp", info.ports());
|
||||
}
|
||||
|
||||
/** A value with the old delimiter in it cannot shift the fields any more. */
|
||||
@Test
|
||||
@DisabledOnOs(OS.WINDOWS)
|
||||
void aPipeInAValueDoesNotShiftTheFields() throws Exception {
|
||||
DockerClient docker = dockerPrinting("""
|
||||
{"Id":"0123abcd","Name":"/floci","Config":{"Image":"registry.local/team|floci:latest"},
|
||||
"State":{"Status":"exited"},"NetworkSettings":{"Ports":{}}}
|
||||
""");
|
||||
|
||||
DockerClient.ContainerInfo info = docker.inspectContainer("floci").orElseThrow();
|
||||
|
||||
assertEquals("registry.local/team|floci:latest", info.image());
|
||||
assertEquals("exited", info.state());
|
||||
assertEquals("", info.ports());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishedPortsListEveryBindingAndSkipWhatIsNotPublished() throws Exception {
|
||||
JsonNode ports = new ObjectMapper().readTree("""
|
||||
{"4566/tcp":[{"HostIp":"","HostPort":"14566"}],"8080/tcp":null,"9000/tcp":[],
|
||||
"4510/tcp":[{"HostIp":"","HostPort":"24510"}]}
|
||||
""");
|
||||
|
||||
assertEquals("14566->4566/tcp 24510->4510/tcp", DockerClient.publishedPorts(ports));
|
||||
assertEquals("", DockerClient.publishedPorts(new ObjectMapper().readTree("{}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledOnOs(OS.WINDOWS)
|
||||
void aMissingContainerIsEmptyAndGarbageIsReportedWithANextStep() throws Exception {
|
||||
Path missing = Files.createTempFile(tempDir, "docker", "");
|
||||
Files.writeString(missing, "#!/bin/sh\necho 'Error response from daemon: No such container: floci' >&2\nexit 1\n");
|
||||
assertTrue(missing.toFile().setExecutable(true));
|
||||
|
||||
assertTrue(new DockerClient(missing.toString()).inspectContainer("floci").isEmpty());
|
||||
|
||||
DockerException e = assertThrows(DockerException.class, () -> dockerPrinting("not json").inspectContainer("floci"));
|
||||
assertTrue(e.getMessage().contains("Could not read the details of container 'floci'"), e.getMessage());
|
||||
assertTrue(e.getMessage().contains("docker info"), e.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -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<String> args) {
|
||||
runArgs.addAll(args);
|
||||
|
||||
Reference in new issue
Block a user