mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(ui): reconnect the UI sidecar without restarting Floci (#2718)
* fix(ui): reconnect the UI sidecar without restarting Floci The floci-ui sidecar's FLOCI_ENDPOINT is baked in at container-create time, but Floci's container IP changes on every restart. adoptExisting() took over a surviving sidecar verbatim and never compared its endpoint against the current one, so the sidecar kept polling the previous instance's address indefinitely. The dashboard reported "Not connected" with ECONNREFUSED and the only way out was to recreate the sidecar by hand -- in practice, by restarting the emulator alongside it. Detect that drift on adoption and recreate the sidecar instead, so recovery stays entirely within the sidecar's own lifecycle and never requires disturbing Floci. Two supporting changes: - status() re-arms ensureStarted() when the readiness probe fails. started was a one-way latch, so a sidecar that was removed, crashed, or turned out to be stale left Floci with no path back. The UI polls status continuously, which supplies the retry cadence. - UiServiceConfig gains endpoint() and insecureSkipTlsVerify(). With TLS on, the derived endpoint is https://<floci-container-ip>:<port>, which the sidecar's Node/Bun proxy rejects: the self-signed certificate has no IP SAN for Floci's own container address, so verification fails with ERR_TLS_CERT_ALTNAME_INVALID even once the CA is trusted. Trusting the CA alone is therefore not enough. endpoint() lets an operator point the sidecar at http://<ip>:<port> -- the same server, via the port's HTTP/HTTPS protocol detection, with TLS left enabled -- and insecureSkipTlsVerify() covers the case where https must be kept. A blank or malformed override is a hard error, not a silent fall back to the derived endpoint. * fix(ui): derive http for the sidecar when the host is a bare IP With TLS enabled the endpoint handed to the UI sidecar was derived as https://<floci's own container IP>:4566. That address can never appear in the self-signed certificate: it is assigned at container-create time and changes on every recreate, and the certificate is generated by a ConfigSource that runs before CDI, with no Docker client to ask what the address will be. Every connection therefore failed altname verification — not chain trust, so mounting the CA would not have helped either — and the dashboard sat at "Not connected" with no path back. Nothing in the manager notices: the sidecar is running, so the re-arm added in 8f4fd900 correctly declines to replace it, and the readiness probe only checks the sidecar's own port, never the hop that is broken. Floci's listener does HTTP/HTTPS protocol detection on the same port, so http:// reaches it with TLS left enabled. That is one hop on an internal Docker network, not the emulator, and it is the only scheme that works unattended on the default configuration. A named host such as host.docker.internal is a DNS SAN on the certificate and keeps https. So does an IP literal when insecure-skip-tls-verify is set, since the operator has said explicitly that they want TLS on this hop and verification is no longer the obstacle. isIpLiteral mirrors the iPAddress/dNSName distinction CertificateGenerator already draws, kept local so this package does not depend on the ACM service for one predicate. * fix(ui): bracket an IPv6 host so the sidecar endpoint parses The endpoint was built by concatenating host and port, which produces http://fd00::2:4566 when the resolver hands back an IPv6 literal — the port separator is indistinguishable from the address's own colons and no client can parse it. DockerHostResolver reaches that case through InetAddress.getLocalHost().getHostAddress() on an IPv6-only host. Bracket the authority host. Names and IPv4 literals are unchanged. * fix(ui): reset the async re-arm latch and stop swallowing pre-start failures Local code review (review-local.ts) against FlociUiManager.java found two HIGH-severity bugs before this branch reached a PR: - ensureStartedAsync()'s kicked latch was only reset after a FAILED start, never after a successful one. status()'s self-recovery path sets started=false and calls ensureStartedAsync() when the sidecar is gone, but after any prior successful async start that CAS always failed silently -- the documented "recovers without Floci being restarted" behavior could never actually fire. - findByName() and replaceIfEndpointDrifted() ran before ensureStarted()'s try/catch. A container-runtime failure there (e.g. an unreachable Docker socket) escaped uncaught to a synchronous caller, or vanished into a discarded Future on the async path, leaving status() reporting {started:false, ready:false, error:null} with no diagnostic. Reset kicked whenever status() re-arms a lost sidecar, and move the whole body of ensureStarted() into the try/catch so every failure is routed through lastError. A misconfigured endpoint override's own validation message (set by replaceIfEndpointDrifted before it rethrows) is preserved rather than overwritten by the generic describeStartFailure() message. * fix(ui): validate endpoint override authority and capture fresh-start errors - validateEndpointOverride() now rejects http:// URLs with no authority (e.g. "http://", "http:///path"), which previously passed the bare prefix check and were injected as an unreachable FLOCI_ENDPOINT. - ensureStarted()'s IllegalStateException handler now fills lastError when nothing more specific was already recorded, so a fresh start (no existing sidecar to adopt) with a blank/malformed endpoint override surfaces the validation message instead of error=null. - Document the new endpoint and insecure-skip-tls-verify settings in application.yml's floci.services.ui block.
This commit is contained in:
1 parent
ff36141c19
commit
02f9754ac7
5 files changed
+707
-15
No files matched your search
@@ -1707,6 +1707,35 @@ public interface EmulatorConfig {
|
||||
boolean keepRunningOnShutdown();
|
||||
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* Overrides the Floci endpoint handed to the UI sidecar, instead of deriving it from
|
||||
* the resolved Docker host and {@link EmulatorConfig#tls()}.
|
||||
* Env: {@code FLOCI_SERVICES_UI_ENDPOINT}
|
||||
*
|
||||
* <p>The derived value is {@code https://<floci-container-ip>:<port>} when TLS is on,
|
||||
* which the sidecar's Node/Bun proxy rejects: Floci's self-signed certificate carries no
|
||||
* IP SAN for its own container IP, so verification fails with
|
||||
* {@code ERR_TLS_CERT_ALTNAME_INVALID} even when the CA is trusted. Floci's port does
|
||||
* HTTP/HTTPS protocol detection, so pointing the sidecar at {@code http://<ip>:<port>}
|
||||
* reaches the same server over the private container network with TLS left enabled.
|
||||
*
|
||||
* <p>Must be an absolute {@code http://} or {@code https://} URL. A blank or malformed
|
||||
* value is a hard error rather than a silent fall back to the derived endpoint.
|
||||
*/
|
||||
Optional<String> endpoint();
|
||||
|
||||
/**
|
||||
* Disables TLS certificate verification in the UI sidecar's Node/Bun proxy by injecting
|
||||
* {@code NODE_TLS_REJECT_UNAUTHORIZED=0}. Env: {@code FLOCI_SERVICES_UI_INSECURE_SKIP_TLS_VERIFY}
|
||||
*
|
||||
* <p>Trusting Floci's CA alone is not sufficient — it fixes the chain but not the missing
|
||||
* IP SAN — so this is the only trust knob that makes an {@code https://<container-ip>}
|
||||
* endpoint work. Scoped to the sidecar's connection to Floci; it does not affect Floci's
|
||||
* own TLS. Prefer {@link #endpoint()} where an {@code http://} endpoint is acceptable.
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean insecureSkipTlsVerify();
|
||||
}
|
||||
|
||||
interface EcrServiceConfig {
|
||||
|
||||
+60
@@ -465,6 +465,66 @@ public class ContainerLifecycleManager {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the environment a container was created with. The {@link Container} summaries
|
||||
* returned by {@link #findByName} carry no environment, so callers that must compare an
|
||||
* adoption candidate's baked-in configuration against current settings have to inspect it.
|
||||
*
|
||||
* <p>An unreadable container is reported as {@link Optional#empty()} rather than as an empty
|
||||
* environment: callers act destructively on what they find here, and "the container declares
|
||||
* no variables" and "the runtime would not tell me" must not lead to the same decision.
|
||||
*
|
||||
* @param containerId the container ID to inspect
|
||||
* @return the container's environment as {@code KEY=value} entries, or empty if it could
|
||||
* not be read at all
|
||||
*/
|
||||
public Optional<List<String>> containerEnv(String containerId) {
|
||||
try {
|
||||
String[] env = dockerClient.inspectContainerCmd(containerId).exec().getConfig().getEnv();
|
||||
return Optional.of(env == null ? List.of() : List.of(env));
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not read environment of container {0}: {1}", containerId, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a container exists and is running — distinguishing "gone" from "cannot tell". */
|
||||
public enum ContainerPresence {
|
||||
/** The container exists and is running. */
|
||||
RUNNING,
|
||||
/** The container exists but has exited or has not been started. */
|
||||
STOPPED,
|
||||
/** The container no longer exists. */
|
||||
ABSENT,
|
||||
/** The container runtime could not be reached, so its state is unknown. */
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes whether a container is still there. Callers use this to tell a sidecar that has
|
||||
* genuinely vanished from one that is merely slow, so that recovery is triggered by the
|
||||
* former and never by the latter.
|
||||
*
|
||||
* @param containerId the container ID to probe, may be null
|
||||
* @return the container's presence, {@link ContainerPresence#UNKNOWN} if it could not be probed
|
||||
*/
|
||||
public ContainerPresence presenceOf(String containerId) {
|
||||
if (containerId == null) {
|
||||
return ContainerPresence.ABSENT;
|
||||
}
|
||||
try {
|
||||
InspectContainerResponse.ContainerState state =
|
||||
dockerClient.inspectContainerCmd(containerId).exec().getState();
|
||||
boolean running = state != null && Boolean.TRUE.equals(state.getRunning());
|
||||
return running ? ContainerPresence.RUNNING : ContainerPresence.STOPPED;
|
||||
} catch (NotFoundException e) {
|
||||
return ContainerPresence.ABSENT;
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not probe container {0}: {1}", containerId, e.getMessage());
|
||||
return ContainerPresence.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopts an existing container, starting it if stopped.
|
||||
* Useful for services like ECR that reuse containers across restarts.
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -16,6 +17,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerPresence;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
@@ -43,6 +45,8 @@ public class FlociUiManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FlociUiManager.class);
|
||||
private static final int CONTAINER_INTERNAL_PORT = 4500;
|
||||
private static final String FLOCI_ENDPOINT_ENV = "FLOCI_ENDPOINT";
|
||||
private static final Pattern IPV4_LITERAL = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}$");
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
@@ -112,17 +116,17 @@ public class FlociUiManager {
|
||||
// Clear any error from a prior failed attempt so status() reports this retry
|
||||
// as in-progress rather than surfacing the stale failure.
|
||||
this.lastError = null;
|
||||
String name = ContainerStorageHelper.dockerName(config, config.services().ui().containerName());
|
||||
|
||||
Optional<Container> existing = lifecycleManager.findByName(name);
|
||||
if (existing.isPresent()) {
|
||||
adoptExisting(existing.get());
|
||||
return;
|
||||
}
|
||||
|
||||
String image = config.services().ui().image();
|
||||
int chosenPort = config.services().ui().port();
|
||||
try {
|
||||
String name = ContainerStorageHelper.dockerName(config, config.services().ui().containerName());
|
||||
|
||||
Optional<Container> existing = lifecycleManager.findByName(name);
|
||||
if (existing.isPresent() && !replaceIfEndpointDrifted(existing.get())) {
|
||||
adoptExisting(existing.get());
|
||||
return;
|
||||
}
|
||||
|
||||
int chosenPort = config.services().ui().port();
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(name)
|
||||
.withEnv(injectedEnv())
|
||||
@@ -143,6 +147,15 @@ public class FlociUiManager {
|
||||
this.lastError = null;
|
||||
LOG.infov("Started floci-ui sidecar {0} on host port {1}", name, String.valueOf(hostPort));
|
||||
attachLogStream();
|
||||
} catch (IllegalStateException e) {
|
||||
// replaceIfEndpointDrifted() records its own specific message for a container with an
|
||||
// existing sidecar to adopt, but a fresh start (no existing container) reaches this
|
||||
// catch directly from injectedEnv()/resolveFlociEndpoint() with lastError still null --
|
||||
// only fill it in when nothing more specific was already recorded.
|
||||
if (this.lastError == null) {
|
||||
this.lastError = e.getMessage();
|
||||
}
|
||||
LOG.errorv(e, "Failed to start floci-ui sidecar: {0}", e.getMessage());
|
||||
} catch (Exception e) {
|
||||
this.lastError = describeStartFailure(image, e);
|
||||
LOG.errorv(e, "Failed to start floci-ui sidecar from image {0}", image);
|
||||
@@ -172,12 +185,35 @@ public class FlociUiManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Current state, including a probe of whether the UI is accepting connections. */
|
||||
/**
|
||||
* Current state, including a probe of whether the UI is accepting connections.
|
||||
*
|
||||
* <p>A sidecar that has gone away is un-started here so the next call re-runs
|
||||
* {@link #ensureStarted()}. {@code started} is otherwise a one-way latch: it is set on a
|
||||
* successful start or adoption and never cleared, so a sidecar that is removed or exits
|
||||
* would leave Floci with no path back — the dashboard would stay "Not connected" until
|
||||
* someone intervened by hand. The UI polls this endpoint continuously, which supplies the
|
||||
* retry cadence; no extra backoff machinery is needed.
|
||||
*
|
||||
* <p>The failed probe alone is deliberately not the trigger. It also fails throughout a cold
|
||||
* boot, and re-arming on it would re-adopt the container on every poll. Recovery is driven by
|
||||
* the container being gone, which is the condition that actually needs a restart.
|
||||
*/
|
||||
public UiStatus status() {
|
||||
if (lastError != null) {
|
||||
return new UiStatus(started, false, hostPort, lastError);
|
||||
}
|
||||
boolean ready = started && probeReady();
|
||||
if (started && !ready && shouldReArm(lifecycleManager.presenceOf(containerId))) {
|
||||
LOG.infov("floci-ui sidecar {0} is gone — starting it again so the dashboard "
|
||||
+ "recovers without Floci being restarted", containerId);
|
||||
this.started = false;
|
||||
// ensureStartedAsync() only submits on kicked's false->true edge, but a prior
|
||||
// successful start never reset it (it only resets after a FAILED start) -- without
|
||||
// this, this re-arm's CAS finds kicked already true and silently no-ops.
|
||||
this.kicked.set(false);
|
||||
ensureStartedAsync();
|
||||
}
|
||||
return new UiStatus(started, ready, hostPort, null);
|
||||
}
|
||||
|
||||
@@ -198,9 +234,15 @@ public class FlociUiManager {
|
||||
lifecycleManager.stopAndRemove(containerId, logStream);
|
||||
}
|
||||
|
||||
private List<String> injectedEnv() {
|
||||
List<String> injectedEnv() {
|
||||
List<String> env = new ArrayList<>();
|
||||
env.add("FLOCI_ENDPOINT=" + resolveFlociEndpoint());
|
||||
env.add(FLOCI_ENDPOINT_ENV + "=" + resolveFlociEndpoint());
|
||||
if (config.services().ui().insecureSkipTlsVerify()) {
|
||||
LOG.warn("floci.services.ui.insecure-skip-tls-verify=true — the Floci UI sidecar will "
|
||||
+ "not verify Floci's TLS certificate. Intended for Floci's self-signed "
|
||||
+ "certificate, which carries no IP SAN for its own container address.");
|
||||
env.add("NODE_TLS_REJECT_UNAUTHORIZED=0");
|
||||
}
|
||||
env.add("AWS_REGION=" + regionResolver.getDefaultRegion());
|
||||
env.add("AWS_ACCESS_KEY_ID=test");
|
||||
env.add("AWS_SECRET_ACCESS_KEY=test");
|
||||
@@ -220,11 +262,154 @@ public class FlociUiManager {
|
||||
* working.
|
||||
*/
|
||||
String resolveFlociEndpoint() {
|
||||
Optional<String> override = config.services().ui().endpoint();
|
||||
if (override.isPresent()) {
|
||||
return validateEndpointOverride(override.get());
|
||||
}
|
||||
if (containerDetector.isRunningInContainer() && config.hostname().isPresent()) {
|
||||
return config.effectiveBaseUrl();
|
||||
}
|
||||
String scheme = config.tls().enabled() ? "https" : "http";
|
||||
return scheme + "://" + dockerHostResolver.resolve() + ":" + config.port();
|
||||
String host = dockerHostResolver.resolve();
|
||||
String scheme = derivedScheme(
|
||||
config.tls().enabled(), config.services().ui().insecureSkipTlsVerify(), host);
|
||||
return scheme + "://" + authorityHost(host) + ":" + config.port();
|
||||
}
|
||||
|
||||
/**
|
||||
* A host as it must appear in a URL authority.
|
||||
*
|
||||
* <p>An IPv6 literal has to be bracketed or the port separator is indistinguishable from the
|
||||
* address's own colons and the result is unparseable. Names and IPv4 literals pass through.
|
||||
*/
|
||||
static String authorityHost(String host) {
|
||||
if (host == null || host.indexOf(':') < 0 || host.startsWith("[")) {
|
||||
return host;
|
||||
}
|
||||
return "[" + host + "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Scheme for the derived endpoint.
|
||||
*
|
||||
* <p>With TLS enabled the honest answer is usually {@code https}, but not when the resolver
|
||||
* hands back a bare IP address. Containerized Floci reaches itself by its own Docker-network
|
||||
* IP, which the self-signed certificate cannot carry as a SAN: the address is assigned at
|
||||
* container-create time and changes on every recreate, so baking it into the certificate
|
||||
* would mean regenerating on every boot, and the certificate is generated by a
|
||||
* {@code ConfigSource} that runs before CDI and has no Docker client to ask. An
|
||||
* {@code https://} URL to that address therefore fails altname verification every time, and
|
||||
* the sidecar sits at "Not connected" with no path back.
|
||||
*
|
||||
* <p>Floci's listener does HTTP/HTTPS protocol detection on the same port, so {@code http://}
|
||||
* reaches it with TLS left enabled — this downgrades one hop on an internal Docker network,
|
||||
* not the emulator. A named host such as {@code host.docker.internal} is a DNS SAN on the
|
||||
* certificate and keeps {@code https}. So does an IP literal when the operator has opted into
|
||||
* {@code insecure-skip-tls-verify}, since they have said explicitly that they want TLS on this
|
||||
* hop and verification is no longer the obstacle.
|
||||
*/
|
||||
static String derivedScheme(boolean tlsEnabled, boolean insecureSkipTlsVerify, String host) {
|
||||
if (!tlsEnabled) {
|
||||
return "http";
|
||||
}
|
||||
if (insecureSkipTlsVerify) {
|
||||
return "https";
|
||||
}
|
||||
return isIpLiteral(host) ? "http" : "https";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a host is a bare IP address rather than a name.
|
||||
*
|
||||
* <p>Mirrors the same distinction {@code CertificateGenerator} draws when it types a SAN as
|
||||
* {@code iPAddress} or {@code dNSName} — kept local rather than shared so this package does
|
||||
* not take a dependency on the ACM service for one predicate.
|
||||
*/
|
||||
static boolean isIpLiteral(String host) {
|
||||
if (host == null || host.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return IPV4_LITERAL.matcher(host).matches() || host.indexOf(':') >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an operator-supplied endpoint override. A blank or malformed value is a
|
||||
* configuration error, not a reason to quietly derive an endpoint instead: silently
|
||||
* substituting a different address is exactly the failure mode that leaves the dashboard
|
||||
* reporting "Not connected" with no indication of why.
|
||||
*/
|
||||
static String validateEndpointOverride(String raw) {
|
||||
String value = raw == null ? "" : raw.trim();
|
||||
if (value.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"floci.services.ui.endpoint is set but blank — remove it to derive the "
|
||||
+ "endpoint automatically, or give it an absolute http:// or https:// URL.");
|
||||
}
|
||||
if (!value.startsWith("http://") && !value.startsWith("https://")) {
|
||||
throw new IllegalStateException(
|
||||
"floci.services.ui.endpoint must be an absolute http:// or https:// URL, was: " + value);
|
||||
}
|
||||
String host;
|
||||
try {
|
||||
host = URI.create(value).getHost();
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalStateException(
|
||||
"floci.services.ui.endpoint must be an absolute http:// or https:// URL, was: " + value);
|
||||
}
|
||||
if (host == null || host.isBlank()) {
|
||||
throw new IllegalStateException(
|
||||
"floci.services.ui.endpoint must be an absolute http:// or https:// URL, was: " + value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an adoption candidate must be destroyed and recreated rather than adopted.
|
||||
*
|
||||
* <p>Separate from {@link #endpointDrifted} because the two "no endpoint here" cases are not
|
||||
* the same decision. A container that declares no {@code FLOCI_ENDPOINT} is drifted and must
|
||||
* go. A container whose environment could not be read tells us nothing, and destroying it on
|
||||
* that basis would turn one failed inspect into a deleted, possibly perfectly healthy sidecar.
|
||||
* The unreadable case is therefore adopted, and the endpoint is re-checked on the next start.
|
||||
*
|
||||
* @param existingEnv the candidate's environment, empty if it could not be read
|
||||
* @param expected the endpoint a freshly created sidecar would be given
|
||||
*/
|
||||
static boolean shouldReplace(Optional<List<String>> existingEnv, String expected) {
|
||||
return existingEnv.map(env -> endpointDrifted(env, expected)).orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a sidecar that is not answering has actually gone, and so must be started again.
|
||||
*
|
||||
* <p>Only a container that has vanished or exited is re-armed. A running container that is
|
||||
* not yet answering is a cold boot, not a failure — re-arming there would re-adopt the same
|
||||
* container on every poll of {@link #status()} for as long as it took to come up. Presence
|
||||
* the runtime could not report is treated as "leave it alone" for the same reason: acting on
|
||||
* an unknown is how a transient runtime hiccup turns into a restart loop.
|
||||
*/
|
||||
static boolean shouldReArm(ContainerPresence presence) {
|
||||
return presence == ContainerPresence.ABSENT || presence == ContainerPresence.STOPPED;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when an adoption candidate's baked-in {@code FLOCI_ENDPOINT} no longer matches the
|
||||
* endpoint Floci would hand a freshly created sidecar.
|
||||
*
|
||||
* <p>The sidecar's endpoint is fixed at container-create time, but Floci's container IP
|
||||
* changes on every restart. A sidecar that outlives Floci therefore keeps addressing the
|
||||
* previous instance and polls a dead address forever. A missing endpoint counts as drift:
|
||||
* unknown is not the same as correct, and adopting it would strand the UI just as badly.
|
||||
*/
|
||||
static boolean endpointDrifted(List<String> existingEnv, String expected) {
|
||||
if (existingEnv == null) {
|
||||
return true;
|
||||
}
|
||||
return existingEnv.stream()
|
||||
.filter(entry -> entry.startsWith(FLOCI_ENDPOINT_ENV + "="))
|
||||
.map(entry -> entry.substring(FLOCI_ENDPOINT_ENV.length() + 1))
|
||||
.findFirst()
|
||||
.map(current -> !current.equals(expected))
|
||||
.orElse(true);
|
||||
}
|
||||
|
||||
private Optional<String> resolveDockerNetwork() {
|
||||
@@ -285,6 +470,43 @@ public class FlociUiManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an existing sidecar whose baked-in endpoint no longer addresses this Floci, so the
|
||||
* caller recreates it instead of adopting it.
|
||||
*
|
||||
* <p>Without this, a sidecar that outlives Floci is adopted verbatim and keeps polling the
|
||||
* previous instance's container IP indefinitely — the dashboard shows "Not connected" and the
|
||||
* only way out is to restart the sidecar by hand. Recreating it here keeps recovery entirely
|
||||
* within the sidecar's lifecycle, so nothing about the emulator has to be disturbed.
|
||||
*
|
||||
* @return true when the container was removed and must be recreated
|
||||
*/
|
||||
private boolean replaceIfEndpointDrifted(Container existing) {
|
||||
String expected;
|
||||
try {
|
||||
expected = resolveFlociEndpoint();
|
||||
} catch (IllegalStateException e) {
|
||||
// A misconfigured override must surface as the start error, not as a silent adoption
|
||||
// of whatever the previous run happened to leave behind.
|
||||
this.lastError = e.getMessage();
|
||||
throw e;
|
||||
}
|
||||
if (!shouldReplace(lifecycleManager.containerEnv(existing.getId()), expected)) {
|
||||
return false;
|
||||
}
|
||||
LOG.infov("Existing floci-ui sidecar {0} points at a stale Floci endpoint (expected {1}) "
|
||||
+ "— recreating it so the UI reconnects without touching Floci",
|
||||
existing.getId(), expected);
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(existing.getId(), null);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not remove stale floci-ui sidecar {0}, adopting it instead: {1}",
|
||||
existing.getId(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void adoptExisting(Container existing) {
|
||||
this.containerId = existing.getId();
|
||||
try {
|
||||
@@ -304,6 +526,7 @@ public class FlociUiManager {
|
||||
}
|
||||
|
||||
private void attachLogStream() {
|
||||
closeLogStream();
|
||||
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
|
||||
String logGroup = "/floci/ui";
|
||||
String logStreamName = logStreamer.generateLogStreamName(shortId);
|
||||
@@ -311,6 +534,20 @@ public class FlociUiManager {
|
||||
this.logStream = logStreamer.attach(containerId, logGroup, logStreamName, region, "floci:ui");
|
||||
}
|
||||
|
||||
/** Releases the previous follower, so a restarted sidecar does not leave one behind. */
|
||||
private void closeLogStream() {
|
||||
Closeable previous = this.logStream;
|
||||
this.logStream = null;
|
||||
if (previous == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
previous.close();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not close the previous floci-ui log stream: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the user-facing message for a failed sidecar start. Only a genuinely
|
||||
* unavailable image gets the {@code docker pull} guidance — every other failure
|
||||
|
||||
@@ -447,6 +447,9 @@ floci:
|
||||
container-name: floci-ui
|
||||
port: 4500
|
||||
keep-running-on-shutdown: false
|
||||
# endpoint: unset by default — Floci derives the sidecar's callback address automatically.
|
||||
# Set an absolute http:// or https:// URL here only to override that derivation.
|
||||
insecure-skip-tls-verify: false
|
||||
bedrock-runtime:
|
||||
enabled: true
|
||||
backend: stub
|
||||
|
||||
+364
-1
@@ -5,21 +5,31 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerPresence;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import com.github.dockerjava.api.exception.DockerClientException;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.BindException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class FlociUiManagerTest {
|
||||
@@ -28,6 +38,17 @@ class FlociUiManagerTest {
|
||||
private final DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
private final EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
|
||||
private final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
private final EmulatorConfig.UiServiceConfig ui = mock(EmulatorConfig.UiServiceConfig.class);
|
||||
private final RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
|
||||
/** Wires config.services().ui() with the defaults every UI test starts from. */
|
||||
private void withUiConfig() {
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.ui()).thenReturn(ui);
|
||||
when(ui.endpoint()).thenReturn(Optional.empty());
|
||||
when(ui.insecureSkipTlsVerify()).thenReturn(false);
|
||||
}
|
||||
|
||||
private FlociUiManager newManager() {
|
||||
return new FlociUiManager(
|
||||
@@ -38,11 +59,12 @@ class FlociUiManagerTest {
|
||||
mock(CurrentContainerNetworkResolver.class),
|
||||
dockerHostResolver,
|
||||
config,
|
||||
mock(RegionResolver.class));
|
||||
regionResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerizedUsesResolvedContainerIpNotHostDockerInternal() {
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.port()).thenReturn(4566);
|
||||
@@ -55,6 +77,7 @@ class FlociUiManagerTest {
|
||||
|
||||
@Test
|
||||
void explicitHostnameWinsWhenContainerized() {
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.hostname()).thenReturn(Optional.of("floci"));
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
|
||||
@@ -64,6 +87,7 @@ class FlociUiManagerTest {
|
||||
|
||||
@Test
|
||||
void onHostFallsBackToHostDockerInternal() {
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
@@ -73,6 +97,67 @@ class FlociUiManagerTest {
|
||||
assertEquals("http://host.docker.internal:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsEnabledDerivesHttpForAnIpLiteralHost() {
|
||||
// The self-signed certificate carries no IP SAN for the container address the resolver
|
||||
// returns, so https:// to it can only ever fail altname verification. Port 4566 does
|
||||
// HTTP/HTTPS protocol detection, so http:// reaches the same listener with TLS left on.
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(dockerHostResolver.resolve()).thenReturn("10.88.3.252");
|
||||
|
||||
assertEquals("http://10.88.3.252:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsEnabledKeepsHttpsForANamedHostTheCertificateCovers() {
|
||||
// host.docker.internal is a DNS SAN on the self-signed certificate. Nothing to work
|
||||
// around, so the downgrade must not reach it.
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
|
||||
assertEquals("https://host.docker.internal:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsEnabledKeepsHttpsForAnIpLiteralWhenVerificationIsSkipped() {
|
||||
// An operator who opted into skipping verification has said they want TLS on this hop;
|
||||
// the altname gap no longer blocks it, so honour the explicit choice.
|
||||
withUiConfig();
|
||||
when(ui.insecureSkipTlsVerify()).thenReturn(true);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(dockerHostResolver.resolve()).thenReturn("10.88.3.252");
|
||||
|
||||
assertEquals("https://10.88.3.252:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIpv6LiteralHostIsBracketedSoTheEndpointStaysAParseableUrl() {
|
||||
// Without brackets the port colon is indistinguishable from the address colons and the
|
||||
// sidecar gets a URL no client can parse.
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(false);
|
||||
when(dockerHostResolver.resolve()).thenReturn("fd00::2");
|
||||
|
||||
assertEquals("http://[fd00::2]:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void probeUsesSidecarContainerIpWhenContainerized() {
|
||||
// In a container the published host port is not reachable via localhost; the
|
||||
@@ -170,6 +255,7 @@ class FlociUiManagerTest {
|
||||
|
||||
@Test
|
||||
void usesHttpsSchemeWhenTlsEnabled() {
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
@@ -178,4 +264,281 @@ class FlociUiManagerTest {
|
||||
|
||||
assertEquals("https://host.docker.internal:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
// --- endpoint drift: an adopted sidecar must not keep pointing at a dead Floci ---
|
||||
|
||||
@Test
|
||||
void endpointDriftDetectedWhenAdoptedContainerPointsAtAnotherAddress() {
|
||||
// The sidecar outlives Floci and is re-adopted after a restart, but its
|
||||
// FLOCI_ENDPOINT was baked in at create time against the previous container IP.
|
||||
List<String> staleEnv = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.4.98:4566");
|
||||
|
||||
assertTrue(FlociUiManager.endpointDrifted(staleEnv, "http://10.88.3.252:4566"),
|
||||
"an adopted sidecar pointing at a previous Floci IP must be treated as drifted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEndpointDriftWhenAdoptedContainerAlreadyMatches() {
|
||||
List<String> env = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.3.252:4566");
|
||||
|
||||
assertFalse(FlociUiManager.endpointDrifted(env, "http://10.88.3.252:4566"),
|
||||
"a sidecar already pointing at the current endpoint must be adopted as-is");
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointDriftDetectedWhenAdoptedContainerHasNoEndpointAtAll() {
|
||||
// Missing is not "fine" — it is unknown, and adopting it would strand the UI.
|
||||
assertTrue(FlociUiManager.endpointDrifted(List.of("PORT=4500"), "http://10.88.3.252:4566"));
|
||||
assertTrue(FlociUiManager.endpointDrifted(null, "http://10.88.3.252:4566"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointDriftDetectedAcrossSchemeChange() {
|
||||
// TLS toggled between runs: same host, different scheme, still unreachable.
|
||||
List<String> env = List.of("FLOCI_ENDPOINT=http://10.88.3.252:4566");
|
||||
|
||||
assertTrue(FlociUiManager.endpointDrifted(env, "https://10.88.3.252:4566"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableEnvironmentAdoptsRatherThanDestroyingAPossiblyHealthySidecar() {
|
||||
// A failed inspect says nothing about the sidecar. Treating "I could not read it" as
|
||||
// drift would let one transient container-runtime hiccup destroy a working sidecar.
|
||||
assertFalse(FlociUiManager.shouldReplace(Optional.empty(), "http://10.88.3.252:4566"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readableEnvironmentStillReplacesOnDrift() {
|
||||
Optional<List<String>> env = Optional.of(List.of("FLOCI_ENDPOINT=http://10.88.4.98:4566"));
|
||||
|
||||
assertTrue(FlociUiManager.shouldReplace(env, "http://10.88.3.252:4566"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readableMatchingEnvironmentIsAdopted() {
|
||||
Optional<List<String>> env = Optional.of(List.of("FLOCI_ENDPOINT=http://10.88.3.252:4566"));
|
||||
|
||||
assertFalse(FlociUiManager.shouldReplace(env, "http://10.88.3.252:4566"));
|
||||
}
|
||||
|
||||
// --- re-arming a lost sidecar (must not churn a healthy one) ---
|
||||
|
||||
@Test
|
||||
void removedSidecarReArmsSoTheDashboardRecoversOnItsOwn() {
|
||||
assertTrue(FlociUiManager.shouldReArm(ContainerPresence.ABSENT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exitedSidecarReArms() {
|
||||
assertTrue(FlociUiManager.shouldReArm(ContainerPresence.STOPPED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bootingSidecarThatIsNotAnsweringYetIsLeftAlone() {
|
||||
// The probe fails for the whole of a cold boot. Re-arming here would re-adopt the
|
||||
// container on every poll — a log-stream reattach per poll, forever, for a sidecar
|
||||
// that was about to come up on its own.
|
||||
assertFalse(FlociUiManager.shouldReArm(ContainerPresence.RUNNING));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownPresenceIsNotTreatedAsAMissingSidecar() {
|
||||
assertFalse(FlociUiManager.shouldReArm(ContainerPresence.UNKNOWN));
|
||||
}
|
||||
|
||||
// --- explicit endpoint override ---
|
||||
|
||||
@Test
|
||||
void configuredEndpointOverrideWinsOverDerivation() {
|
||||
withUiConfig();
|
||||
when(ui.endpoint()).thenReturn(Optional.of("http://10.88.3.252:4566"));
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
|
||||
assertEquals("http://10.88.3.252:4566", newManager().resolveFlociEndpoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankEndpointOverrideFailsFastRatherThanSilentlyFallingBack() {
|
||||
withUiConfig();
|
||||
when(ui.endpoint()).thenReturn(Optional.of(" "));
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> newManager().resolveFlociEndpoint());
|
||||
assertTrue(e.getMessage().contains("floci.services.ui.endpoint"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedEndpointOverrideFailsFast() {
|
||||
withUiConfig();
|
||||
when(ui.endpoint()).thenReturn(Optional.of("10.88.3.252:4566"));
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> newManager().resolveFlociEndpoint());
|
||||
assertTrue(e.getMessage().contains("http://"), e.getMessage());
|
||||
}
|
||||
|
||||
// --- TLS trust for the sidecar's Node/Bun proxy ---
|
||||
|
||||
@Test
|
||||
void insecureSkipTlsVerifyInjectsNodeTlsRejectUnauthorized() {
|
||||
// Floci's self-signed cert has no IP SAN for its own container IP, so the sidecar
|
||||
// fails ERR_TLS_CERT_ALTNAME_INVALID even with the CA trusted. Only disabling
|
||||
// verification outright clears both the chain and the altname check.
|
||||
withUiConfig();
|
||||
when(ui.insecureSkipTlsVerify()).thenReturn(true);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
assertTrue(newManager().injectedEnv().contains("NODE_TLS_REJECT_UNAUTHORIZED=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsVerificationLeftIntactByDefault() {
|
||||
withUiConfig();
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.tls()).thenReturn(tls);
|
||||
when(tls.enabled()).thenReturn(true);
|
||||
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
List<String> env = newManager().injectedEnv();
|
||||
assertFalse(env.stream().anyMatch(v -> v.startsWith("NODE_TLS_REJECT_UNAUTHORIZED")),
|
||||
"TLS verification must stay on unless explicitly opted out, was: " + env);
|
||||
}
|
||||
|
||||
// --- re-arming after an async start must not get stuck ---
|
||||
|
||||
@Test
|
||||
void statusReArmsAfterAnAsyncStartActuallyRestartsTheSidecar() {
|
||||
// The sidecar's first start goes through ensureStartedAsync() (the interstitial-page
|
||||
// path). Once it is gone and status() wants to bring it back, the second restart is
|
||||
// also kicked through ensureStartedAsync() — that second kick must not be silently
|
||||
// dropped just because the first one already ran to completion.
|
||||
withUiConfig();
|
||||
when(ui.enabled()).thenReturn(true);
|
||||
when(ui.containerName()).thenReturn("floci-ui");
|
||||
when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getId()).thenReturn("abc123");
|
||||
when(lifecycleManager.findByName("floci-ui")).thenReturn(Optional.of(existing));
|
||||
when(lifecycleManager.containerEnv("abc123")).thenReturn(Optional.empty());
|
||||
EndpointInfo endpoint = new EndpointInfo("localhost", 4500);
|
||||
when(lifecycleManager.adopt("abc123", List.of(4500)))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo("abc123", Map.of(4500, endpoint)));
|
||||
when(lifecycleManager.presenceOf("abc123")).thenReturn(ContainerPresence.ABSENT);
|
||||
|
||||
FlociUiManager manager = new FlociUiManager(
|
||||
mock(ContainerBuilder.class),
|
||||
lifecycleManager,
|
||||
mock(ContainerLogStreamer.class),
|
||||
containerDetector,
|
||||
mock(CurrentContainerNetworkResolver.class),
|
||||
dockerHostResolver,
|
||||
config,
|
||||
regionResolver);
|
||||
|
||||
manager.ensureStartedAsync();
|
||||
await().atMost(2, TimeUnit.SECONDS)
|
||||
.untilAsserted(() -> verify(lifecycleManager, times(1)).adopt("abc123", List.of(4500)));
|
||||
|
||||
// The sidecar is gone (ABSENT) and unreachable (nothing listens on localhost:4500), so
|
||||
// status() must trigger a second async restart.
|
||||
manager.status();
|
||||
|
||||
await().atMost(2, TimeUnit.SECONDS)
|
||||
.untilAsserted(() -> verify(lifecycleManager, times(2)).adopt("abc123", List.of(4500)));
|
||||
}
|
||||
|
||||
// --- a start that fails before the try block must not vanish silently ---
|
||||
|
||||
@Test
|
||||
void ensureStartedRecordsTheFailureWhenTheContainerRuntimeIsUnreachable() {
|
||||
// findByName runs before the try/catch in ensureStarted(). If the container runtime is
|
||||
// unreachable it throws there, and the failure must still be captured for status() --
|
||||
// not escape uncaught (synchronous callers) or vanish into a discarded Future (the
|
||||
// ensureStartedAsync() path).
|
||||
withUiConfig();
|
||||
when(ui.enabled()).thenReturn(true);
|
||||
when(ui.containerName()).thenReturn("floci-ui");
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.findByName("floci-ui"))
|
||||
.thenThrow(new com.github.dockerjava.api.exception.DockerClientException(
|
||||
"Cannot connect to the Docker daemon"));
|
||||
|
||||
FlociUiManager manager = new FlociUiManager(
|
||||
mock(ContainerBuilder.class),
|
||||
lifecycleManager,
|
||||
mock(ContainerLogStreamer.class),
|
||||
containerDetector,
|
||||
mock(CurrentContainerNetworkResolver.class),
|
||||
dockerHostResolver,
|
||||
config,
|
||||
regionResolver);
|
||||
|
||||
manager.ensureStarted();
|
||||
|
||||
assertEquals(false, manager.status().started());
|
||||
assertTrue(manager.status().error() != null && manager.status().error().contains("Docker"),
|
||||
"expected a captured error mentioning the Docker runtime, was: " + manager.status().error());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointOverrideWithNoAuthorityFailsFast() {
|
||||
// "http://" and "http:///path" both pass a bare prefix check but carry no host, so the
|
||||
// sidecar would be started with an endpoint it can never connect to.
|
||||
withUiConfig();
|
||||
when(ui.endpoint()).thenReturn(Optional.of("http://"));
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> newManager().resolveFlociEndpoint());
|
||||
assertTrue(e.getMessage().contains("http://"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointOverrideWithPathOnlyAndNoAuthorityFailsFast() {
|
||||
withUiConfig();
|
||||
when(ui.endpoint()).thenReturn(Optional.of("http:///path"));
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> newManager().resolveFlociEndpoint());
|
||||
assertTrue(e.getMessage().contains("http:///path"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureStartedRecordsTheFailureFromAFreshStartWithNoExistingSidecarToAdopt() {
|
||||
// findByName finds nothing, so replaceIfEndpointDrifted (which records its own message)
|
||||
// never runs -- injectedEnv()/resolveFlociEndpoint() throws IllegalStateException
|
||||
// directly out of the try block on a blank/malformed override, and that catch must
|
||||
// still populate lastError instead of leaving status() reporting error=null forever.
|
||||
withUiConfig();
|
||||
when(ui.enabled()).thenReturn(true);
|
||||
when(ui.containerName()).thenReturn("floci-ui");
|
||||
when(ui.endpoint()).thenReturn(Optional.of("not-a-url"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.findByName("floci-ui")).thenReturn(Optional.empty());
|
||||
|
||||
FlociUiManager manager = new FlociUiManager(
|
||||
mock(ContainerBuilder.class, RETURNS_DEEP_STUBS),
|
||||
lifecycleManager,
|
||||
mock(ContainerLogStreamer.class),
|
||||
containerDetector,
|
||||
mock(CurrentContainerNetworkResolver.class),
|
||||
dockerHostResolver,
|
||||
config,
|
||||
regionResolver);
|
||||
|
||||
manager.ensureStarted();
|
||||
|
||||
assertEquals(false, manager.status().started());
|
||||
assertTrue(manager.status().error() != null && manager.status().error().contains("http://"),
|
||||
"expected a captured error mentioning the required http:// scheme, was: "
|
||||
+ manager.status().error());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user