feat(ui): serve a landing page and launch the floci-ui console on demand (#1313)

* feat(ui): serve a landing page and launch the floci-ui console on demand

A browser hitting the Floci endpoint (GET / with Accept: text/html) now gets a
small embedded landing page; SDK/CLI traffic falls through to S3 ListBuckets
unchanged. The 'Open Floci UI' button hits /_floci/ui, which lazily starts the
floci-ui sidecar container, injects FLOCI_ENDPOINT so its API can reach Floci,
and serves an interstitial that polls /_floci/ui/status and redirects to the UI
once ready.

The sidecar is a single instance on one configured host port
(floci.services.ui.port, default 8080) and is adopted if already running. A
missing or unavailable image is reported as a friendly message instead of a 500.
Embedded ui/*.html is registered in quarkus.native.resources.includes so it is
present in the native image.

* feat(ui): branded landing dashboard, port 4500, reachable endpoint

Reskin the landing page to floci.io branding and surface live data from
/_floci/* (version, ready state, services grid). Publish the UI sidecar on a
fixed 4500 host+container port. Inject a self-discovered FLOCI_ENDPOINT via
DockerHostResolver so the UI reaches Floci over the Docker network instead of
hardcoded host.docker.internal logic; add FlociUiManagerTest.

* fix(s3): keep ListBuckets Content-Type as application/xml for non-HTML callers

The landing-page content negotiation listed text/html first in @Produces and
returned the ListBuckets XML without an explicit media type, so RESTEasy
negotiated Accept: */* (SDK/CLI default) to text/html and stamped that on the
response. Put application/xml first and pin the XML response type so non-browser
callers always receive application/xml; browser (Accept: text/html) callers
still get the landing page.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-06-15 20:10:13 -05:00
1 parent 647d941ed8
commit 2536b4ab86
13 files changed
+957 -6

No files matched your search

@@ -379,6 +379,7 @@ public interface EmulatorConfig {
CloudFrontServiceConfig cloudfront();
AppSyncServiceConfig appsync();
BatchServiceConfig batch();
UiServiceConfig ui();
}
interface CloudTrailServiceConfig {
@@ -886,6 +887,26 @@ public interface EmulatorConfig {
String emitMode();
}
interface UiServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("floci/floci-ui:latest")
String image();
@WithDefault("floci-ui")
String containerName();
/** Single fixed host port the UI is published on (single-instance service). */
@WithDefault("4500")
int port();
@WithDefault("false")
boolean keepRunningOnShutdown();
Optional<String> dockerNetwork();
}
interface EcrServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ui.FlociUiManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
@@ -66,6 +67,7 @@ public class EmulatorLifecycle {
private final PipesService pipesService;
private final Ec2MetadataServer ec2MetadataServer;
private final EcrRegistryManager ecrRegistryManager;
private final FlociUiManager flociUiManager;
private final InitLifecycleState initLifecycleState;
@Inject
@@ -84,6 +86,7 @@ public class EmulatorLifecycle {
PipesService pipesService,
Ec2MetadataServer ec2MetadataServer,
EcrRegistryManager ecrRegistryManager,
FlociUiManager flociUiManager,
InitLifecycleState initLifecycleState) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
@@ -101,6 +104,7 @@ public class EmulatorLifecycle {
this.pipesService = pipesService;
this.ec2MetadataServer = ec2MetadataServer;
this.ecrRegistryManager = ecrRegistryManager;
this.flociUiManager = flociUiManager;
this.initLifecycleState = initLifecycleState;
}
@@ -218,6 +222,7 @@ public class EmulatorLifecycle {
elastiCacheMemcachedContainerManager.stopAll();
rdsContainerManager.stopAll();
ecrRegistryManager.shutdown();
flociUiManager.shutdown();
storageFactory.shutdownAll();
LOG.info("=== AWS Local Emulator Stopped ===");
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.services.ui.FlociUiManager;
import io.github.hectorvent.floci.services.ui.FlociUiManager.UiStatus;
import io.github.hectorvent.floci.services.ui.UiPages;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* Browser-facing endpoints that launch and redirect to the floci-ui sidecar.
*
* <ul>
* <li>{@code GET /_floci/ui} — kicks off the sidecar start (async) and returns a
* small interstitial page that polls {@code /status} and redirects when ready.</li>
* <li>{@code GET /_floci/ui/status} — JSON {@code {ready, url, error}} the
* interstitial polls.</li>
* </ul>
*/
@Path("{prefix:(_floci|_localstack)}/ui")
public class UiController {
private final FlociUiManager uiManager;
private final UiPages uiPages;
@Inject
public UiController(FlociUiManager uiManager, UiPages uiPages) {
this.uiManager = uiManager;
this.uiPages = uiPages;
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response ui() {
uiManager.ensureStartedAsync();
return Response.ok(uiPages.startingHtml()).build();
}
public record StatusResponse(boolean ready, String url, String error) {}
@GET
@Path("/status")
@Produces(MediaType.APPLICATION_JSON)
public Response status(@HeaderParam("Host") String host) {
UiStatus s = uiManager.status();
if (s.error() != null) {
return Response.ok(new StatusResponse(false, null, s.error())).build();
}
if (s.ready() && s.hostPort() > 0) {
return Response.ok(new StatusResponse(true, redirectUrl(host, s.hostPort()), null)).build();
}
return Response.ok(new StatusResponse(false, null, null)).build();
}
/** Builds the browser-reachable UI URL from the request Host and the published port. */
private static String redirectUrl(String host, int port) {
String hostname = (host == null || host.isBlank()) ? "localhost" : host;
int colon = hostname.indexOf(':');
if (colon >= 0) {
hostname = hostname.substring(0, colon);
}
return "http://" + hostname + ":" + port + "/";
}
}
@@ -87,25 +87,35 @@ public class S3Controller {
private final S3SelectService s3SelectService;
private final RegionResolver regionResolver;
private final io.quarkus.vertx.http.runtime.CurrentVertxRequest currentVertxRequest;
private final io.github.hectorvent.floci.services.ui.UiPages uiPages;
@Inject
public S3Controller(S3Service s3Service, S3SelectService s3SelectService,
RegionResolver regionResolver,
io.quarkus.vertx.http.runtime.CurrentVertxRequest currentVertxRequest) {
io.quarkus.vertx.http.runtime.CurrentVertxRequest currentVertxRequest,
io.github.hectorvent.floci.services.ui.UiPages uiPages) {
this.s3Service = s3Service;
this.s3SelectService = s3SelectService;
this.regionResolver = regionResolver;
this.currentVertxRequest = currentVertxRequest;
this.uiPages = uiPages;
}
// --- Bucket operations ---
@GET
@Produces(MediaType.APPLICATION_XML)
public Response listBuckets(@HeaderParam("X-Amz-Target") String target) {
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_HTML})
public Response listBuckets(@HeaderParam("X-Amz-Target") String target,
@HeaderParam("Accept") String accept) {
if (target != null) {
return null;
}
// A browser hitting the root endpoint (Accept: text/html) gets the Floci
// landing page; SDK/CLI callers (no Accept, */*, or an XML/JSON Accept) fall
// through to the normal S3 ListBuckets behavior untouched.
if (accept != null && accept.contains(MediaType.TEXT_HTML)) {
return Response.ok(uiPages.landingHtml(), MediaType.TEXT_HTML).build();
}
try {
List<Bucket> buckets = s3Service.listBuckets();
XmlBuilder xml = new XmlBuilder()
@@ -123,7 +133,7 @@ public class S3Controller {
.end("Bucket");
}
xml.end("Buckets").end("ListAllMyBucketsResult");
return Response.ok(xml.build()).build();
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
@@ -0,0 +1,271 @@
package io.github.hectorvent.floci.services.ui;
import java.io.Closeable;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import com.github.dockerjava.api.model.Container;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
/**
* Manages the lifecycle of the {@code floci/floci-ui} sidecar container — the
* browser-facing Floci web console. The container is started lazily on the first
* {@code /_floci/ui} hit and reused across restarts (one per Floci instance).
*
* <p>Unlike other sidecars, a failed start (typically a missing/unavailable image)
* is <em>not</em> fatal: it is recorded in {@link #status()} so the interstitial
* page can show a friendly message instead of a 500.
*/
@ApplicationScoped
public class FlociUiManager {
private static final Logger LOG = Logger.getLogger(FlociUiManager.class);
private static final int CONTAINER_INTERNAL_PORT = 4500;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
private final ContainerDetector containerDetector;
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
private final DockerHostResolver dockerHostResolver;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private volatile boolean started;
private volatile int hostPort;
private volatile String containerId;
private volatile Closeable logStream;
private volatile String lastError;
private final ExecutorService starter = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "floci-ui-starter");
t.setDaemon(true);
return t;
});
private final AtomicBoolean kicked = new AtomicBoolean(false);
@Inject
public FlociUiManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
ContainerDetector containerDetector,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
DockerHostResolver dockerHostResolver,
EmulatorConfig config,
RegionResolver regionResolver) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.containerDetector = containerDetector;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.dockerHostResolver = dockerHostResolver;
this.config = config;
this.regionResolver = regionResolver;
}
/** Snapshot of the sidecar state for the interstitial page. */
public record UiStatus(boolean started, boolean ready, int hostPort, String error) {}
/**
* Lazily starts (or adopts) the floci-ui container. Idempotent and thread-safe.
* Does not throw on a failed start — the failure is captured for {@link #status()}.
*/
public synchronized void ensureStarted() {
if (started) {
return;
}
if (!config.services().ui().enabled()) {
this.lastError = "The Floci UI is disabled (set floci.services.ui.enabled=true to enable it).";
return;
}
// 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 = 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 {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(name)
.withEnv(injectedEnv())
.withPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)
.withDockerNetwork(resolveDockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withHostDockerInternalOnLinux();
}
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
this.containerId = info.containerId();
this.hostPort = chosenPort;
this.started = true;
this.lastError = null;
LOG.infov("Started floci-ui sidecar {0} on host port {1}", name, String.valueOf(chosenPort));
attachLogStream();
} catch (Exception e) {
this.lastError = "Could not start the Floci UI from image '" + image + "': " + e.getMessage()
+ ". Ensure the image is available (docker pull " + image
+ ", or build it from the floci-ui repo).";
LOG.errorv(e, "Failed to start floci-ui sidecar from image {0}", image);
}
}
/**
* Triggers {@link #ensureStarted()} on a background thread and returns immediately,
* so the caller can serve the interstitial page while the (possibly slow) image
* pull and boot happen. De-duplicated; re-armed after a failed start so the user
* can fix the image and retry.
*/
public void ensureStartedAsync() {
if (started) {
return;
}
if (kicked.compareAndSet(false, true)) {
starter.submit(() -> {
try {
ensureStarted();
} finally {
if (!started) {
kicked.set(false);
}
}
});
}
}
/** Current state, including a probe of whether the UI is accepting connections. */
public UiStatus status() {
if (lastError != null) {
return new UiStatus(started, false, hostPort, lastError);
}
boolean ready = started && probeReady();
return new UiStatus(started, ready, hostPort, null);
}
/** Host port the UI is published on. Valid once {@link #ensureStarted()} succeeds. */
public int hostPort() {
return hostPort;
}
/** Stops the container unless {@code keep-running-on-shutdown=true}. */
public void shutdown() {
if (!started || containerId == null) {
return;
}
if (config.services().ui().keepRunningOnShutdown()) {
LOG.infov("Leaving floci-ui sidecar {0} running for next start-up", containerId);
return;
}
lifecycleManager.stopAndRemove(containerId, logStream);
}
private List<String> injectedEnv() {
List<String> env = new ArrayList<>();
env.add("FLOCI_ENDPOINT=" + resolveFlociEndpoint());
env.add("AWS_REGION=" + regionResolver.getDefaultRegion());
env.add("AWS_ACCESS_KEY_ID=test");
env.add("AWS_SECRET_ACCESS_KEY=test");
env.add("PORT=" + CONTAINER_INTERNAL_PORT);
return env;
}
/**
* The endpoint the UI's API server uses to reach Floci from inside its container.
*
* <p>Reuses {@link DockerHostResolver}, the same mechanism Lambda and CodeBuild use:
* when Floci runs in a container the sibling UI reaches it directly by Floci's own
* container IP over the shared Docker network (no {@code host.docker.internal}, no
* manual {@code FLOCI_HOSTNAME}); when Floci runs on the host the only path from a
* container is the host gateway ({@code host.docker.internal}). An explicitly
* configured {@code FLOCI_HOSTNAME} still wins so name-based compose setups keep
* working.
*/
String resolveFlociEndpoint() {
if (containerDetector.isRunningInContainer() && config.hostname().isPresent()) {
return config.effectiveBaseUrl();
}
String scheme = config.tls().enabled() ? "https" : "http";
return scheme + "://" + dockerHostResolver.resolve() + ":" + config.port();
}
private Optional<String> resolveDockerNetwork() {
Optional<String> configured = config.services().ui().dockerNetwork();
if (configured.isPresent() && !configured.get().isBlank()) {
return configured;
}
if (containerDetector.isRunningInContainer()) {
return currentContainerNetworkResolver.resolveNetworkName();
}
return Optional.empty();
}
private boolean probeReady() {
String url = containerDetector.isRunningInContainer()
? "http://" + config.services().ui().containerName() + ":" + CONTAINER_INTERNAL_PORT + "/"
: "http://localhost:" + hostPort + "/";
try {
HttpURLConnection conn = (HttpURLConnection) URI.create(url).toURL().openConnection();
conn.setConnectTimeout(800);
conn.setReadTimeout(800);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
conn.disconnect();
return code > 0;
} catch (Exception e) {
return false;
}
}
private void adoptExisting(Container existing) {
this.containerId = existing.getId();
try {
ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT));
var endpoint = info.getEndpoint(CONTAINER_INTERNAL_PORT);
if (endpoint != null) {
this.hostPort = endpoint.port();
}
this.started = true;
this.lastError = null;
LOG.infov("Adopted existing floci-ui sidecar {0} on host port {1}",
containerId, String.valueOf(hostPort));
attachLogStream();
} catch (Exception e) {
LOG.warnv("Failed to adopt existing floci-ui sidecar: {0}", e.getMessage());
this.containerId = null;
}
}
private void attachLogStream() {
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
String logGroup = "/floci/ui";
String logStreamName = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
this.logStream = logStreamer.attach(containerId, logGroup, logStreamName, region, "floci:ui");
}
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.ui;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import jakarta.enterprise.context.ApplicationScoped;
/**
* Loads and caches the small embedded HTML pages served to browsers: the Floci
* landing page and the "starting the UI" interstitial. Resources are read from
* the classpath ({@code ui/*.html}) and must be registered in
* {@code quarkus.native.resources.includes} so they are embedded in the native
* image.
*/
@ApplicationScoped
public class UiPages {
private static final String LANDING_RESOURCE = "ui/index.html";
private static final String STARTING_RESOURCE = "ui/starting.html";
private volatile String landing;
private volatile String starting;
public String landingHtml() {
String result = landing;
if (result == null) {
result = readResource(LANDING_RESOURCE);
landing = result;
}
return result;
}
public String startingHtml() {
String result = starting;
if (result == null) {
result = readResource(STARTING_RESOURCE);
starting = result;
}
return result;
}
private static String readResource(String resourceName) {
ClassLoader loader = UiPages.class.getClassLoader();
try (InputStream input = loader.getResourceAsStream(resourceName)) {
if (input == null) {
throw new IllegalStateException("Missing UI resource: " + resourceName);
}
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("Failed to load UI resource: " + resourceName, e);
}
}
}