From 2536b4ab867fb015f57546e90cbe2f359ee4fbf3 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Mon, 15 Jun 2026 20:10:13 -0500 Subject: [PATCH] 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. --- .../floci/config/EmulatorConfig.java | 21 ++ .../floci/lifecycle/EmulatorLifecycle.java | 5 + .../floci/lifecycle/UiController.java | 68 +++++ .../floci/services/s3/S3Controller.java | 18 +- .../floci/services/ui/FlociUiManager.java | 271 ++++++++++++++++ .../hectorvent/floci/services/ui/UiPages.java | 54 ++++ src/main/resources/application.yml | 8 +- src/main/resources/ui/index.html | 289 ++++++++++++++++++ src/main/resources/ui/starting.html | 80 +++++ .../lifecycle/EmulatorLifecycleTest.java | 3 +- .../floci/services/ui/FlociUiManagerTest.java | 80 +++++ .../services/ui/UiLandingIntegrationTest.java | 64 ++++ src/test/resources/application.yml | 2 + 13 files changed, 957 insertions(+), 6 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/lifecycle/UiController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ui/FlociUiManager.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ui/UiPages.java create mode 100644 src/main/resources/ui/index.html create mode 100644 src/main/resources/ui/starting.html create mode 100644 src/test/java/io/github/hectorvent/floci/services/ui/FlociUiManagerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ui/UiLandingIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 8ae11ba62f..5f25f33f3d 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -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 dockerNetwork(); + } + interface EcrServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index e0f70b5ec6..44297fa53d 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -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 ==="); diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/UiController.java b/src/main/java/io/github/hectorvent/floci/lifecycle/UiController.java new file mode 100644 index 0000000000..fcbc44bed1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/UiController.java @@ -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. + * + * + */ +@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 + "/"; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index ac6fb98b34..d339a0be67 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -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 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); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ui/FlociUiManager.java b/src/main/java/io/github/hectorvent/floci/services/ui/FlociUiManager.java new file mode 100644 index 0000000000..beabc39166 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ui/FlociUiManager.java @@ -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). + * + *

Unlike other sidecars, a failed start (typically a missing/unavailable image) + * is not 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 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 injectedEnv() { + List 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. + * + *

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 resolveDockerNetwork() { + Optional 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"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ui/UiPages.java b/src/main/java/io/github/hectorvent/floci/services/ui/UiPages.java new file mode 100644 index 0000000000..cb5c1488b1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ui/UiPages.java @@ -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); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 619e0b027a..bbf36f6826 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -24,7 +24,7 @@ quarkus: # ClassLoader#getResourceAsStream. Quarkus's static resource analysis # cannot detect these dynamically-built paths, so they are registered # explicitly to ensure GraalVM includes every file in the native image. - includes: pricing-snapshots/**,ec2/*.yaml + includes: pricing-snapshots/**,ui/*.html,ec2/*.yaml additional-build-args: - --report-unsupported-elements-at-runtime - --allow-incomplete-classpath @@ -275,6 +275,12 @@ floci: tls-enabled: false keep-running-on-shutdown: true uri-style: hostname + ui: + enabled: true + image: "floci/floci-ui:latest" + container-name: floci-ui + port: 4500 + keep-running-on-shutdown: false bedrock-runtime: enabled: true eks: diff --git a/src/main/resources/ui/index.html b/src/main/resources/ui/index.html new file mode 100644 index 0000000000..c40209e9f4 --- /dev/null +++ b/src/main/resources/ui/index.html @@ -0,0 +1,289 @@ + + + + + + Floci — local AWS emulator + + + + + + +

+
+ + + connecting… + +
+

Any cloud. Locally. — a local AWS emulator speaking real AWS wire protocols.

+

You've reached the Floci endpoint. Point your AWS SDK or CLI here with + --endpoint-url http://localhost:4566 and it behaves like AWS.

+
+
Endpoint
http://localhost:4566
+
Region
us-east-1 (default)
+
Account
000000000000
+
Version
…
+
+
+
+

Services

+ — running · — available +
+ +
+
Loading services…
+
+
+ + Open Floci UI → + +

The UI launches on demand as a sidecar container the first time you open it. +  ·  health · info

+
+ + + + diff --git a/src/main/resources/ui/starting.html b/src/main/resources/ui/starting.html new file mode 100644 index 0000000000..aeda6e5a10 --- /dev/null +++ b/src/main/resources/ui/starting.html @@ -0,0 +1,80 @@ + + + + + + Starting Floci UI… + + + +
+
+

Starting Floci UI…

+

Launching the UI container. This can take a moment the first time while the image is pulled.

+
+ + + diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 20cfd4d839..51d2c60774 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -65,6 +65,7 @@ class EmulatorLifecycleTest { @Mock private PipesService pipesService; @Mock private Ec2MetadataServer ec2MetadataServer; @Mock private EcrRegistryManager ecrRegistryManager; + @Mock private io.github.hectorvent.floci.services.ui.FlociUiManager flociUiManager; @Mock private InitLifecycleState initLifecycleState; @Mock private EmulatorConfig.TlsConfig tlsConfig; @@ -83,7 +84,7 @@ class EmulatorLifecycleTest { elastiCacheContainerManager, elastiCacheMemcachedContainerManager, elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, rdsService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, - pipesService, ec2MetadataServer, ecrRegistryManager, initLifecycleState); + pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState); } private void stubStorageConfig() { diff --git a/src/test/java/io/github/hectorvent/floci/services/ui/FlociUiManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ui/FlociUiManagerTest.java new file mode 100644 index 0000000000..ff1aefbfff --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ui/FlociUiManagerTest.java @@ -0,0 +1,80 @@ +package io.github.hectorvent.floci.services.ui; + +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.ContainerLogStreamer; +import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class FlociUiManagerTest { + + private final ContainerDetector containerDetector = mock(ContainerDetector.class); + private final DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class); + private final EmulatorConfig config = mock(EmulatorConfig.class); + private final EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class); + + private FlociUiManager newManager() { + return new FlociUiManager( + mock(ContainerBuilder.class), + mock(ContainerLifecycleManager.class), + mock(ContainerLogStreamer.class), + containerDetector, + mock(CurrentContainerNetworkResolver.class), + dockerHostResolver, + config, + mock(RegionResolver.class)); + } + + @Test + void containerizedUsesResolvedContainerIpNotHostDockerInternal() { + 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("172.24.0.2"); + + assertEquals("http://172.24.0.2:4566", newManager().resolveFlociEndpoint()); + } + + @Test + void explicitHostnameWinsWhenContainerized() { + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(config.hostname()).thenReturn(Optional.of("floci")); + when(config.effectiveBaseUrl()).thenReturn("http://floci:4566"); + + assertEquals("http://floci:4566", newManager().resolveFlociEndpoint()); + } + + @Test + void onHostFallsBackToHostDockerInternal() { + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(config.port()).thenReturn(4566); + when(config.tls()).thenReturn(tls); + when(tls.enabled()).thenReturn(false); + when(dockerHostResolver.resolve()).thenReturn("host.docker.internal"); + + assertEquals("http://host.docker.internal:4566", newManager().resolveFlociEndpoint()); + } + + @Test + void usesHttpsSchemeWhenTlsEnabled() { + 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ui/UiLandingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ui/UiLandingIntegrationTest.java new file mode 100644 index 0000000000..67af3a7dc0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ui/UiLandingIntegrationTest.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.ui; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; + +/** + * Verifies the browser landing page content-negotiation on {@code /} and the + * {@code /_floci/ui/status} contract. These do not spawn the sidecar (only + * {@code GET /_floci/ui} does), so they need no Docker. + */ +@QuarkusTest +class UiLandingIntegrationTest { + + @Test + void browserAcceptHtmlGetsLandingPage() { + given() + .accept("text/html") + .when() + .get("/") + .then() + .statusCode(200) + .contentType(containsString("text/html")) + .body(containsString("Floci")) + .body(containsString("Open Floci UI")); + } + + @Test + void sdkClientStillGetsListBucketsXml() { + // No Accept: text/html — must fall through to S3 ListBuckets, unchanged. + given() + .accept("application/xml") + .when() + .get("/") + .then() + .statusCode(200) + .body(containsString("ListAllMyBucketsResult")); + } + + @Test + void wildcardAcceptIsTreatedAsSdkNotBrowser() { + // RestAssured default Accept is */* — the strict text/html check must not match. + given() + .when() + .get("/") + .then() + .statusCode(200) + .body(containsString("ListAllMyBucketsResult")); + } + + @Test + void statusEndpointReportsNotReadyBeforeStart() { + given() + .accept("application/json") + .when() + .get("/_floci/ui/status") + .then() + .statusCode(200) + .body("ready", is(false)); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 03d7eaa3ed..ecdfdfb23b 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -170,6 +170,8 @@ floci: enabled: true ecr: enabled: true + ui: + enabled: true bedrock-runtime: enabled: true eks: