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

+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.