fix(cli)!: stop using the default instance for a missing container

status no longer probes the default instance for a named container with no known
endpoint, and env, services, snapshot and az setup exit 1 with the next step
instead of acting on it. wait keeps looking for the container until --timeout, and
doctor and version still run. A profile's port is used before its container
starts, and an endpoint from --endpoint, FLOCI_ENDPOINT or another host beats a
local container's published port.

BREAKING CHANGE: in status -o json, endpoint is null when the selected container
has no known endpoint. env, services, snapshot and az setup exit 1 in that case,
where they used to use the default endpoint. An --endpoint or FLOCI_ENDPOINT on
the default port is now honoured even when a local container publishes another
port.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-11-03 23:53:22 -06:00
1 parent ac52515471
commit 33367ecb9b
17 files changed
+469 -57

No files matched your search

+11
View File
@@ -489,6 +489,17 @@ stdout: the progress lines are left out and docker's pull progress goes to stder
`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.
A selected container with no published port and no configured endpoint has no known endpoint.
`status` does not probe the default instance and reports `endpoint: null` in structured output.
`env`, `services`, `az setup` and the `snapshot` commands exit `1` with the next step rather than
act on the default instance. `doctor` and `version` still run and do not probe it. `wait` keeps
looking for the container until `--timeout`.
A profile's `port` supplies its endpoint when the endpoint is unset or still the product default.
A running container's published port corrects that endpoint, unless the endpoint was chosen on
purpose: typed with `--endpoint`, set in `FLOCI_ENDPOINT`, or on another host. `env` warns on stderr
when it looked the container up and it is not running.
### `floci status` / `floci gcp status` / `floci az status` / `floci oci status`
```sh
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "floci",
"version": "1.0.0",
"version": "1.0.1",
"description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.",
"author": {
"name": "Floci",
+5 -3
View File
@@ -85,9 +85,11 @@ clouds the user works with; suggest installing them, do not install them unasked
7. **Never add `-q` to `env`**: it suppresses the exports themselves.
8. **Do not guess what an emulator supports.** Check `floci <tree> services -o json` and the
published docs ([references/docs.md](references/docs.md)) instead of answering from memory.
9. **With a profile, start and wait before `env`.** Until the profile's container is running,
`env` and `status` fall back to the default port and describe the default instance. Trust
`"state": "running"` in `status -o json`, not `reachable`.
9. **With a profile, start and wait before `env`.** Until the container is running, `env`
warns on stderr. A profile with a `port` resolves to that port; a named container with
neither a port nor an endpoint has `"endpoint": null` in `status -o json` and `env` exits 1
rather than describe the default instance. Trust `"state": "running"` in `status -o json`,
not `reachable`.
## Lifecycle (same for every tree)
+84 -16
View File
@@ -1,6 +1,7 @@
package io.floci.cli;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat;
@@ -11,6 +12,8 @@ import picocli.CommandLine.Spec;
import java.net.URI;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
@@ -37,10 +40,15 @@ public class GlobalOptions {
@Spec(Spec.Target.MIXEE)
CommandSpec mixee;
private static final Set<String> LOOPBACK_HOSTS = Set.of("localhost", "127.0.0.1", "[::1]", "localhost.floci.io");
private static final Pattern PLAIN_WORD = Pattern.compile("[A-Za-z0-9._@%+=:,/-]+");
public final ProductProfile product;
// The value FLOCI_ENDPOINT supplied, if any: that is a choice, like typing --endpoint.
private final String endpointFromEnv;
@Option(names = {"--endpoint"},
description = "Floci server endpoint URL (default: ${DEFAULT-VALUE})",
paramLabel = "<url>")
@@ -88,6 +96,7 @@ public class GlobalOptions {
/** Test seam: {@code envLookup} replaces {@code System.getenv}. */
public GlobalOptions(ProductProfile product, UnaryOperator<String> envLookup) {
this.product = product;
this.endpointFromEnv = envLookup.apply(product.envVar("ENDPOINT"));
this.endpoint = envOr(envLookup, product.envVar("ENDPOINT"), product.defaultEndpoint());
this.container = envOr(envLookup, product.envVar("CONTAINER"), product.defaultContainer());
}
@@ -157,27 +166,86 @@ public class GlobalOptions {
return noEmoji || !terminal || noColorEnv;
}
// Inspects the container and derives the endpoint from its host port mapping.
// Falls back to the configured endpoint if the container is not found or has no mapping.
public String resolvedEndpoint(DockerClient docker) {
/** Whether a configured endpoint can identify this instance without a container lookup. */
public boolean canUseConfiguredEndpoint() {
return typed("--endpoint") || !product.defaultEndpoint().equals(endpoint)
|| product.defaultContainer().equals(container);
}
/**
* Whether the configured endpoint was chosen on purpose, so it beats the port a local container
* publishes: typed, from the environment, or on another host. A loopback endpoint from a
* profile is only where the instance was last known to be, so the container corrects it.
*/
public boolean configuredEndpointWins() {
return typed("--endpoint") || endpoint.equals(endpointFromEnv) || !isLoopback(endpoint);
}
private static boolean isLoopback(String url) {
try {
return docker.inspectContainer(container)
.map(info -> endpointFromPorts(info.ports(), endpoint))
.orElse(endpoint);
} catch (Exception e) {
return endpoint;
String host = URI.create(url).getHost();
return host == null || LOOPBACK_HOSTS.contains(host);
} catch (IllegalArgumentException e) {
return false;
}
}
// Matches the container-side port from the configured endpoint to find the actual host port.
public String endpointFromPorts(String ports, String fallback) {
if (ports == null || ports.isBlank()) return fallback;
/**
* For commands that act on the instance (env, services, snapshot, az setup): where it is, or
* an {@link IllegalStateException} with the next step when that cannot be known, because
* acting on the default instance instead could change the wrong state.
*/
public String resolvedEndpoint(DockerClient docker) {
return resolvedEndpoint(docker, message -> { });
}
/** As above, reporting a missing or stopped container on stderr so env's stdout stays clean. */
public String resolvedEndpoint(DockerClient docker, Consumer<String> warning) {
Lookup found = lookup(docker);
if (found.problem() != null) warning.accept(found.problem());
if (found.endpoint() != null) return found.endpoint();
throw new IllegalStateException("The endpoint for container '" + container + "' is unknown.\n"
+ (found.dockerFailed()
? "Check that Docker is running and retry, or pass --endpoint <url> explicitly."
: "Run '" + product.commandPrefix() + " start" + instanceSelector()
+ "', or pass --endpoint <url> explicitly."));
}
/**
* For commands that only report (doctor, version, wait): where the instance is, or empty when
* that cannot be known. They must still run when the instance is missing, without describing
* the default instance as if it were this one.
*/
public Optional<String> knownEndpoint(DockerClient docker) {
return Optional.ofNullable(lookup(docker).endpoint());
}
private record Lookup(String endpoint, String problem, boolean dockerFailed) { }
private Lookup lookup(DockerClient docker) {
if (configuredEndpointWins()) return new Lookup(endpoint, null, false);
String configured = canUseConfiguredEndpoint() ? endpoint : null;
try {
int containerPort = URI.create(fallback).getPort();
if (containerPort == -1) containerPort = product.defaultPort();
return publishedEndpoint(ports, containerPort).orElse(fallback);
} catch (Exception ignored) {}
return fallback;
var info = docker.inspectContainer(container);
if (info.isEmpty()) return new Lookup(configured, instanceNotRunning(), false);
String problem = "running".equals(info.get().state()) ? null : instanceNotRunning();
String published = endpointFromPorts(info.get().ports(), null);
return new Lookup(published != null ? published : configured, problem, false);
} catch (DockerException | RuntimeException e) {
return new Lookup(configured,
"Could not inspect container '" + container + "'.\nCheck that Docker is running and retry.", true);
}
}
private String instanceNotRunning() {
return "Container '" + container + "' is not running.\nRun '" + product.commandPrefix()
+ " start" + instanceSelector() + "' before using its environment.";
}
// Published mappings always name the product's internal port, even when a profile's
// configured endpoint already contains its custom host port.
public String endpointFromPorts(String ports, String fallback) {
return publishedEndpoint(ports, product.defaultPort()).orElse(fallback);
}
/**
@@ -30,6 +30,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -84,6 +85,8 @@ public class DoctorCommand implements Callable<Integer> {
new AzCliConnectionStringCheck()
);
private static final String ENDPOINT_REACHABLE = "endpoint.reachable";
private final DockerClient docker;
private final List<Check> allChecks;
@@ -130,7 +133,9 @@ public class DoctorCommand implements Callable<Integer> {
}
List<CheckResult> results = new ArrayList<>();
String effectiveEndpoint = global.resolvedEndpoint(docker);
// Doctor is where a failed start sends people, so a missing instance must not stop it.
Optional<String> known = global.knownEndpoint(docker);
String effectiveEndpoint = known.orElse(global.endpoint);
boolean textMode = printer.format() == OutputFormat.text;
@@ -143,7 +148,9 @@ public class DoctorCommand implements Callable<Integer> {
// concurrently; results are still printed in list order as each one becomes available.
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<CheckResult>> pending = selected.stream()
.map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container)))
.map(check -> pool.submit(() -> known.isEmpty() && ENDPOINT_REACHABLE.equals(check.name())
? unknownEndpoint()
: runSafely(check, effectiveEndpoint, global.container)))
.toList();
for (int i = 0; i < selected.size(); i++) {
CheckResult result = await(selected.get(i), pending.get(i));
@@ -199,6 +206,13 @@ public class DoctorCommand implements Callable<Integer> {
return allChecks.stream().map(Check::name).filter(n -> n != null).toList();
}
// Probing the configured endpoint here would report the default instance as this one's.
private CheckResult unknownEndpoint() {
return CheckResult.warn(ENDPOINT_REACHABLE,
"Endpoint for container '" + global.container + "' is unknown, so it was not probed",
profile.commandPrefix() + " start" + global.instanceSelector());
}
// One failing check must not abort the run: report it and keep going.
private static CheckResult runSafely(Check check, String endpoint, String container) {
try {
@@ -48,7 +48,7 @@ public class EnvCommand implements Callable<Integer> {
printer.error(ShellExport.unsupported(shell));
return 2;
}
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient(), printer::warn);
int port = extractPort(effectiveEndpoint);
String endpointUrl = "http://" + host + ":" + port;
@@ -54,13 +54,18 @@ public class StatusCommand implements Callable<Integer> {
String containerImage = "";
String containerPorts = "";
String effectiveEndpoint = global.endpoint;
boolean endpointKnown = global.canUseConfiguredEndpoint();
try {
Optional<DockerClient.ContainerInfo> info = docker.inspectContainer(global.container);
if (info.isPresent()) {
containerState = info.get().state();
containerImage = info.get().image();
containerPorts = info.get().ports();
effectiveEndpoint = global.endpointFromPorts(containerPorts, global.endpoint);
String published = global.configuredEndpointWins() ? null : global.endpointFromPorts(containerPorts, null);
if (published != null) {
effectiveEndpoint = published;
endpointKnown = true;
}
}
} catch (DockerException e) {
containerState = "error: " + e.getMessage();
@@ -70,13 +75,16 @@ public class StatusCommand implements Callable<Integer> {
String serverVersion = "unavailable";
String serverEdition = "";
boolean reachable = false;
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try {
var health = client.health();
serverVersion = health.version();
serverEdition = health.edition();
reachable = true;
} catch (Exception ignored) {}
if (!endpointKnown) effectiveEndpoint = null;
if (endpointKnown) {
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try {
var health = client.health();
serverVersion = health.version();
serverEdition = health.edition();
reachable = true;
} catch (Exception ignored) {}
}
// On stderr, so structured output stays one document.
ServerCompatibility.warning(profile, serverVersion, global.instanceSelector()).ifPresent(printer::warn);
@@ -106,7 +114,7 @@ public class StatusCommand implements Callable<Integer> {
printer.println(" Container: " + global.container + " " + stateColor);
if (!containerImage.isBlank()) printer.println(" Image: " + containerImage);
if (!containerPorts.isBlank()) printer.println(" Ports: " + containerPorts);
printer.println(" Endpoint: " + effectiveEndpoint);
printer.println(" Endpoint: " + (endpointKnown ? effectiveEndpoint : "unknown"));
printer.println(" Reachable: " + (reachable ? Ansi.green("yes") : Ansi.red("no")));
if (reachable) {
printer.println(" Version: " + serverVersion);
@@ -4,6 +4,7 @@ import io.floci.cli.CliVersion;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.ServerCompatibility;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat;
@@ -27,11 +28,19 @@ public class VersionCommand implements Callable<Integer> {
@Mixin
protected GlobalOptions global;
private final DockerClient docker;
public VersionCommand() {
this(ProductProfile.AWS);
}
protected VersionCommand(ProductProfile profile) {
this(profile, new DockerClient());
}
/** Test seam: {@code docker} answers the container and image lookups. */
public VersionCommand(ProductProfile profile, DockerClient docker) {
this.docker = docker;
this.profile = profile;
this.global = new GlobalOptions(profile);
}
@@ -44,15 +53,17 @@ public class VersionCommand implements Callable<Integer> {
String serverEdition = null;
String imageDigest = null;
var docker = new io.floci.cli.docker.DockerClient();
String effectiveEndpoint = global.resolvedEndpoint(docker);
String effectiveEndpoint = global.knownEndpoint(docker).orElse(null);
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try {
var info = client.info();
serverVersion = info.version();
serverEdition = info.edition();
} catch (Exception ignored) {}
// The CLI's own version does not depend on the instance, so a missing one is not an error.
if (effectiveEndpoint != null) {
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
try {
var info = client.info();
serverVersion = info.version();
serverEdition = info.edition();
} catch (Exception ignored) {}
}
// On stderr, so structured output stays one document.
ServerCompatibility.warning(profile, serverVersion, global.instanceSelector()).ifPresent(printer::warn);
@@ -78,7 +89,9 @@ public class VersionCommand implements Callable<Integer> {
} else {
// Effective endpoint (port auto-detected) — the gcp/az/oci trees always did
// this; the old AWS copy printed the raw --endpoint value.
printer.println("Server: " + Ansi.gray("not reachable at " + effectiveEndpoint));
printer.println("Server: " + Ansi.gray(effectiveEndpoint != null
? "not reachable at " + effectiveEndpoint
: "unknown, container '" + global.container + "' has no published port"));
}
if (imageDigest != null) {
printer.println("Image: " + imageDigest);
@@ -96,13 +96,18 @@ public class WaitCommand implements Callable<Integer> {
// The deadline starts now, so the container lookup below counts against --timeout too.
Instant deadline = Instant.now().plusMillis(timeoutMillis);
String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline);
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
// Null until the container exists: never poll the default instance on its behalf.
FlociHttpClient client = effectiveEndpoint != null ? new FlociHttpClient(effectiveEndpoint, profile) : null;
// Poll soon after a start, then back off; never let a request or a pause run past the
// deadline, so --timeout is a real upper bound.
long delay = FIRST_DELAY_MS;
while (Instant.now().isBefore(deadline)) {
if (isReady(client, service, requestTimeout(Duration.between(Instant.now(), deadline)))) {
if (client == null) {
effectiveEndpoint = endpointWithin(deadline);
if (effectiveEndpoint != null) client = new FlociHttpClient(effectiveEndpoint, profile);
}
if (client != null && isReady(client, service, requestTimeout(Duration.between(Instant.now(), deadline)))) {
if (spinner) clearSpinner(printer);
if (printer.format() != OutputFormat.text) {
if (!embedded) printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint));
@@ -130,27 +135,28 @@ public class WaitCommand implements Callable<Integer> {
// A stalled daemon or an unreachable remote DOCKER_HOST can hold `docker inspect` far longer
// than --timeout, so the lookup gets the time left and the configured endpoint is the fallback.
private String endpointWithin(Instant deadline) {
String fallback = global.canUseConfiguredEndpoint() ? global.endpoint : null;
long remaining = Duration.between(Instant.now(), deadline).toMillis();
if (remaining <= 0) return global.endpoint;
if (remaining <= 0) return fallback;
// A detached virtual thread: a hung lookup is abandoned, not joined, and cannot keep the
// JVM alive once wait returns.
CompletableFuture<String> resolved = new CompletableFuture<>();
Thread lookup = Thread.ofVirtual().name("floci-wait-endpoint").start(() -> {
try {
resolved.complete(global.resolvedEndpoint(docker));
resolved.complete(global.knownEndpoint(docker).orElse(null));
} catch (RuntimeException e) {
resolved.complete(global.endpoint);
resolved.complete(fallback);
}
});
try {
return resolved.get(remaining, TimeUnit.MILLISECONDS);
} catch (TimeoutException | ExecutionException e) {
lookup.interrupt(); // DockerClient kills the docker process it was waiting on
return global.endpoint;
return fallback;
} catch (InterruptedException e) {
lookup.interrupt();
Thread.currentThread().interrupt();
return global.endpoint;
return fallback;
}
}
@@ -92,7 +92,7 @@ public class AzEnvCommand implements Callable<Integer> {
printer.error(ShellExport.unsupported(shell));
return 2;
}
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient(), printer::warn);
int port = extractPort(effectiveEndpoint);
boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null;
@@ -48,7 +48,7 @@ public class GcpEnvCommand implements Callable<Integer> {
printer.error(ShellExport.unsupported(shell));
return 2;
}
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient(), printer::warn);
String host = extractHost(effectiveEndpoint);
int port = extractPort(effectiveEndpoint);
String hostPort = host + ":" + port;
@@ -37,7 +37,7 @@ public class OciEnvCommand implements Callable<Integer> {
printer.error(ShellExport.unsupported(shell));
return 2;
}
String endpoint = global.resolvedEndpoint(new DockerClient());
String endpoint = global.resolvedEndpoint(new DockerClient(), printer::warn);
Map<String, String> vars = new LinkedHashMap<>();
// OCI SDKs and CLI take one endpoint for every service; ocilocal reads FLOCI_OCI_ENDPOINT.
@@ -1,5 +1,6 @@
package io.floci.cli.config;
import io.floci.cli.GlobalOptions;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat;
import io.floci.cli.util.Causes;
@@ -77,7 +78,7 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider {
CommandSpec command = arg.command();
// Group commands, the root, and `update` carry no GlobalOptions mixin.
OptionSpec profileOption = command.findOption("--profile");
if (profileOption == null) return null;
if (profileOption == null || !command.mixins().containsKey("global")) return null;
String name = profileOption.getValue();
if (name == null) return null;
@@ -92,7 +93,8 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider {
throw e;
}
for (String optionName : option.names()) {
String value = ProfileDefaults.valueFor(profile, optionName);
GlobalOptions global = (GlobalOptions) command.mixins().get("global").userObject();
String value = ProfileDefaults.valueFor(profile, optionName, global.product);
if (value != null) return value;
}
return null;
@@ -1,5 +1,7 @@
package io.floci.cli.config;
import io.floci.cli.ProductProfile;
/**
* Maps a loaded {@link Profile} onto the CLI options it supplies defaults for.
*
@@ -10,6 +12,20 @@ public final class ProfileDefaults {
private ProfileDefaults() {}
public static String valueFor(Profile profile, String optionName, ProductProfile product) {
return profile != null && "--endpoint".equals(optionName)
? endpointFor(profile, product) : valueFor(profile, optionName);
}
/** Legacy profiles may pair a custom host port with the product's default endpoint. */
public static String endpointFor(Profile profile, ProductProfile product) {
if (profile.port != null && (profile.endpoint == null
|| profile.endpoint.equals(product.defaultEndpoint()))) {
return "http://localhost:" + profile.port;
}
return profile.endpoint;
}
/**
* The profile's value for {@code optionName}, or {@code null} when the profile is silent
* about that option — in which case picocli keeps the existing default.
@@ -37,10 +37,12 @@ class AzEnvCommandTest {
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
String[] all = new String[args.length + 2];
String[] all = new String[args.length + 4];
all[0] = "--container";
all[1] = container;
System.arraycopy(args, 0, all, 2, args.length);
all[2] = "--endpoint";
all[3] = "http://localhost:4577";
System.arraycopy(args, 0, all, 4, args.length);
assertEquals(0, new CommandLine(new AzEnvCommand(tempDir, certs)).execute(all));
} finally {
System.setOut(out);
@@ -0,0 +1,270 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.DoctorCommand;
import io.floci.cli.commands.StatusCommand;
import io.floci.cli.commands.VersionCommand;
import io.floci.cli.commands.WaitCommand;
import io.floci.cli.commands.config.ConfigProfileCommand;
import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import io.floci.cli.doctor.Check;
import io.floci.cli.doctor.checks.EndpointReachableCheck;
import com.sun.net.httpserver.HttpServer;
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.MethodSource;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class MissingInstanceEndpointTest {
static List<ProductProfile> products() {
return List.of(ProductProfile.AWS, ProductProfile.GCP, ProductProfile.AZ, ProductProfile.OCI);
}
@TempDir Path temp;
private final DockerClient missing = new DockerClient() {
@Override public Optional<ContainerInfo> inspectContainer(String name) { return Optional.empty(); }
};
@ParameterizedTest
@MethodSource("products")
void legacyProfilePortWorksBeforeStartupInEveryTree(ProductProfile product) throws Exception {
Files.writeString(temp.resolve("other.yaml"), "container: other\nport: 14500\nendpoint: "
+ product.defaultEndpoint() + "\n");
List<String> args = new ArrayList<>(List.of(product.name().toLowerCase(), "env", "--profile", "other"));
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp)).parseArgs(args.toArray(String[]::new));
while (parsed.hasSubcommand()) parsed = parsed.subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
List<String> warnings = new ArrayList<>();
assertEquals("http://localhost:14500", global.resolvedEndpoint(missing, warnings::add));
assertTrue(warnings.getFirst().contains("--profile other"));
assertEquals("http://localhost:16000", global.endpointFromPorts("16000->" + product.defaultPort() + "/tcp", global.endpoint));
}
@ParameterizedTest
@MethodSource("products")
void aCreatedInstanceResolvesToItsPortWithoutStoringAnEndpointNobodyTyped(ProductProfile product) throws Exception {
ProfileStore store = new ProfileStore(temp);
assertEquals(0, new CommandLine(new ConfigProfileCommand(product, store))
.execute("create", "other", "--container", "other", "--port", "14500"));
assertEquals(product.defaultEndpoint(), store.get("other").orElseThrow().endpoint);
var parsed = FlociCli.buildCommandLine(store).parseArgs(product.name().toLowerCase(), "env", "--profile", "other");
while (parsed.hasSubcommand()) parsed = parsed.subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
assertEquals("http://localhost:14500", global.endpoint);
}
private final DockerClient running = new DockerClient() {
@Override public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.of(new ContainerInfo("id", name, "image", "running", "16000->4566/tcp"));
}
};
@Test
void aTypedEndpointBeatsARunningContainersPublishedPort() throws Exception {
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp))
.parseArgs("env", "--container", "other", "--endpoint", "http://localhost:9999").subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
assertEquals("http://localhost:9999", global.resolvedEndpoint(running));
}
@Test
void anEnvironmentEndpointBeatsARunningContainersPublishedPort() {
GlobalOptions global = new GlobalOptions(ProductProfile.AWS,
key -> key.equals("FLOCI_ENDPOINT") ? "http://localhost:9999" : null);
assertEquals("http://localhost:9999", global.resolvedEndpoint(running));
}
@Test
void aProfileEndpointOnAnotherHostBeatsALocalContainer() throws Exception {
Files.writeString(temp.resolve("other.yaml"), "container: other\nendpoint: http://remote:9000\n");
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp)).parseArgs("env", "--profile", "other").subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
assertEquals("http://remote:9000", global.resolvedEndpoint(running));
}
@Test
void aRunningContainerCorrectsALoopbackProfileEndpoint() throws Exception {
Files.writeString(temp.resolve("other.yaml"), "container: other\nport: 14500\n");
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp)).parseArgs("env", "--profile", "other").subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
assertEquals("http://localhost:16000", global.resolvedEndpoint(running));
}
@Test
void aTypedEndpointDoesNotWarnAboutALocalContainer() throws Exception {
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp))
.parseArgs("env", "--container", "other", "--endpoint", "http://remote:4566").subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
List<String> warnings = new ArrayList<>();
global.resolvedEndpoint(missing, warnings::add);
assertEquals(List.of(), warnings);
}
@Test
void anUnreachableDaemonSaysSoInsteadOfSuggestingStart() {
DockerClient down = new DockerClient() {
@Override public Optional<ContainerInfo> inspectContainer(String name) throws DockerException {
throw new DockerException("daemon down");
}
};
GlobalOptions global = new GlobalOptions(ProductProfile.AWS, key -> null);
global.container = "missing-other";
var error = assertThrows(IllegalStateException.class, () -> global.resolvedEndpoint(down));
assertTrue(error.getMessage().contains("Check that Docker is running"), error.getMessage());
assertFalse(error.getMessage().contains("floci start"), error.getMessage());
}
private String[] captured(Callable<Integer> command, int expectedExit, String... args) {
PrintStream out = System.out, err = System.err;
ByteArrayOutputStream stdout = new ByteArrayOutputStream(), stderr = new ByteArrayOutputStream();
try {
System.setOut(new PrintStream(stdout));
System.setErr(new PrintStream(stderr));
assertEquals(expectedExit, new CommandLine(command).execute(args), stderr.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
return new String[]{stdout.toString(), stderr.toString()};
}
@ParameterizedTest
@MethodSource("products")
void doctorStillRunsAndDoesNotVouchForTheDefaultInstance(ProductProfile product) {
Check reachable = new EndpointReachableCheck(product);
String[] out = captured(new DoctorCommand(product, missing, List.of(reachable)), 0,
"--container", "missing-other", "--json");
assertTrue(out[0].contains("\"status\" : \"warn\""), out[0]);
assertTrue(out[0].contains("is unknown"), out[0]);
assertTrue(out[0].contains(product.commandPrefix() + " start --container missing-other"), out[0]);
}
@Test
void waitForAMissingContainerIgnoresAServerOnTheDefaultPort() throws Exception {
HttpServer server;
try {
server = HttpServer.create(new InetSocketAddress("localhost", 4566), 0);
} catch (BindException e) {
assumeTrue(false, "default port already occupied");
return;
}
AtomicInteger requests = new AtomicInteger();
server.createContext("/", exchange -> {
requests.incrementAndGet();
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.start();
try {
captured(new WaitCommand(ProductProfile.AWS, missing), 1, "--container", "missing-other", "--timeout", "300ms");
assertEquals(0, requests.get());
} finally {
server.stop(0);
}
}
@Test
void waitFindsAContainerThatAppearsWhileItWaits() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
byte[] body = "{\"version\":\"2.2.0\",\"status\":\"running\"}".getBytes();
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
AtomicInteger lookups = new AtomicInteger();
DockerClient appears = new DockerClient() {
@Override public Optional<ContainerInfo> inspectContainer(String name) {
if (lookups.incrementAndGet() < 3) return Optional.empty();
return Optional.of(new ContainerInfo("id", name, "image", "running", server.getAddress().getPort() + "->4566/tcp"));
}
};
try {
String[] out = captured(new WaitCommand(ProductProfile.AWS, appears), 0, "--container", "late", "--timeout", "5s");
assertTrue(out[0].contains(":" + server.getAddress().getPort()), out[0]);
} finally {
server.stop(0);
}
}
@Test
void versionStillPrintsTheCliVersionForAMissingContainer() {
String[] out = captured(new VersionCommand(ProductProfile.AWS, missing), 0, "--container", "missing-other", "--json");
assertTrue(out[0].contains("\"server\" : \"unavailable\""), out[0]);
}
@Test
void explicitEndpointWinsOverAProfilePort() throws Exception {
Files.writeString(temp.resolve("other.yaml"), "container: other\nport: 14500\n");
var parsed = FlociCli.buildCommandLine(new ProfileStore(temp)).parseArgs("env", "--profile", "other",
"--endpoint", "http://remote:4566").subcommand();
GlobalOptions global = (GlobalOptions) parsed.commandSpec().mixins().get("global").userObject();
assertEquals("http://remote:4566", global.resolvedEndpoint(missing));
}
@ParameterizedTest
@MethodSource("products")
void unknownCustomContainerCannotProduceDefaultExports(ProductProfile product) {
GlobalOptions global = new GlobalOptions(product, key -> null);
global.container = "missing-other";
var error = assertThrows(IllegalStateException.class, () -> global.resolvedEndpoint(missing));
assertTrue(error.getMessage().contains("--endpoint"));
assertTrue(error.getMessage().contains("--container missing-other"));
}
@Test
void missingNamedContainerDoesNotProbeTheDefaultServer() throws Exception {
HttpServer server;
try {
server = HttpServer.create(new InetSocketAddress("localhost", 4566), 0);
} catch (BindException e) {
assumeTrue(false, "default port already occupied");
return;
}
AtomicInteger requests = new AtomicInteger();
server.createContext("/", exchange -> {
requests.incrementAndGet();
byte[] body = "{\"version\":\"2.2.0\",\"status\":\"running\"}".getBytes();
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
PrintStream original = System.out;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
System.setOut(new PrintStream(out));
assertEquals(1, new CommandLine(new StatusCommand(ProductProfile.AWS, missing))
.execute("--container", "missing-other", "--json"));
assertEquals(0, requests.get());
assertTrue(out.toString().contains("\"endpoint\" : null"), out.toString());
assertTrue(out.toString().contains("\"reachable\" : false"), out.toString());
assertTrue(out.toString().contains("unavailable"), out.toString());
} finally {
System.setOut(original);
server.stop(0);
}
}
}
@@ -57,7 +57,7 @@ class ProfilePrecedenceTest {
writeProfile("probe", FULL_PROFILE);
CommandSpec spec = leafSpec("start", "--profile", "probe");
assertEquals("http://localhost:4566", spec.findOption("--endpoint").getValue());
assertEquals("http://localhost:4599", spec.findOption("--endpoint").getValue());
assertEquals("floci-probe", spec.findOption("--container").getValue());
assertEquals("floci/floci:enforced", spec.findOption("--image").getValue());
assertEquals(Integer.valueOf(4599), spec.findOption("--port").getValue());
@@ -118,7 +118,7 @@ class ProfilePrecedenceTest {
for (String command : new String[]{"status", "logs", "wait", "doctor", "env", "services"}) {
CommandSpec spec = leafSpec(command, "--profile", "probe");
assertEquals("floci-probe", spec.findOption("--container").getValue(), command);
assertEquals("http://localhost:4566", spec.findOption("--endpoint").getValue(), command);
assertEquals("http://localhost:4599", spec.findOption("--endpoint").getValue(), command);
}
}