Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ui): publish a console contract so any web console can be the sidecar (#3641)

Hector Venturaa5ebda01fba8
diff --git a/README.md b/README.md
index 7bf1b2d65d..8583119c0e 100644
--- a/README.md
+++ b/README.md
@@ -130,6 +130,67 @@ The old `hectorvent/floci` repository no longer receives updates.
</details>
+## Web Console
+
+Floci ships a browser console for inspecting the resources in your local emulator.
+
+**Open it at:** `http://localhost:4566/_floci/ui`
+
+Nothing runs at boot. The first request pulls the console image, starts it as a sidecar container on Floci's Docker network, hands it Floci's own reachable address plus the standard AWS environment, polls its health endpoint, and redirects the browser once it reports it can reach Floci. The sidecar's port is bound by Docker, so it needs no `ports:` entry of your own, and its logs are streamed into CloudWatch Logs under `/floci/ui`.
+
+Starting a container needs the Docker socket:
+
+```yaml
+services:
+ floci:
+ image: floci/floci:latest
+ ports:
+ - "4566:4566"
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+```
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_UI_ENABLED` | `true` | Enable the console sidecar |
+| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
+| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
+| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
+
+### Running a different console
+
+The console is not fixed to the one Floci ships. Any console implementing the [Floci console contract](https://floci.io/floci/ui/console-contract/) runs with nothing but an image name: listen on the port in `PORT`, serve `GET /api/health`, talk to Floci at `AWS_ENDPOINT_URL`.
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_IMAGE: acme/my-console:1.0
+```
+
+A console that differs from the contract's defaults says so in its own `io.floci.console.*` image labels, so its operators do not have to. [StackPort](https://github.com/DaviReisVieira/stackport), for example, listens on 8080 rather than 4500; on an image that predates the labels, say it by hand:
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_IMAGE: davireis/stackport:latest
+ FLOCI_SERVICES_UI_CONTAINER_NAME: floci-stackport
+ FLOCI_SERVICES_UI_PORT: "8080"
+ FLOCI_SERVICES_UI_INTERNAL_PORT: "8080"
+```
+
+[Floci Dash](https://github.com/ofsazib/floci-dash) is another. It honours `PORT`, so only the two things it does differ on need naming:
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_IMAGE: ghcr.io/ofsazib/floci-dash:latest
+ FLOCI_SERVICES_UI_CONTAINER_NAME: floci-dash
+ FLOCI_SERVICES_UI_ENDPOINT_ENV: FLOCI_URL
+ FLOCI_SERVICES_UI_STATUS_PATH: /api/healthz
+```
+
+The endpoint itself is never configured by hand: Floci resolves its own reachable address at start time and injects it as `AWS_ENDPOINT_URL`.
+
+Full reference: [Web Console](https://floci.io/floci/ui/) and [Console Contract v1](https://floci.io/floci/ui/console-contract/).
+
## Features
<details open>
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index e7678ac154..b2a81f2e44 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -472,6 +472,35 @@ These services spawn Docker containers. They require access to the Docker socket
---
+### Web Console (UI)
+
+Floci starts the web console as a sidecar container the first time `/_floci/ui` is opened.
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_UI_ENABLED` | `true` | Enable the web console sidecar |
+| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
+| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
+| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
+| `FLOCI_SERVICES_UI_DOCKER_NETWORK` | _(none)_ | Docker network for the sidecar (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
+| `FLOCI_SERVICES_UI_ENDPOINT` | _(derived)_ | Floci endpoint handed to the console, instead of deriving it from the Docker host and TLS settings |
+| `FLOCI_SERVICES_UI_EXTRA_ENV` | _(none)_ | Extra `KEY=VALUE` entries for the console, comma-separated (escape a literal comma as `\,`). Applied last, so an entry may override an injected default |
+| `FLOCI_SERVICES_UI_INSECURE_SKIP_TLS_VERIFY` | `false` | Have the console skip TLS verification on its connection to Floci |
+| `FLOCI_SERVICES_UI_INTERNAL_PORT` | _(discovered, else `4500`)_ | Port the console listens on inside its container |
+| `FLOCI_SERVICES_UI_ENDPOINT_ENV` | _(none)_ | An extra variable to repeat the Floci endpoint in, for a console reading neither `AWS_ENDPOINT_URL` nor `FLOCI_ENDPOINT` |
+| `FLOCI_SERVICES_UI_STATUS_PATH` | _(discovered, else `/api/health`)_ | Path the readiness probe requests on the console |
+| `FLOCI_SERVICES_UI_STATUS_READY_FIELD` | _(discovered, else `status`)_ | JSON field in that response reporting readiness. Set to `none` to make any `200` count as ready |
+| `FLOCI_SERVICES_UI_STATUS_READY_VALUE` | _(discovered, else `ok`)_ | Value of that field meaning the console reached Floci |
+| `FLOCI_SERVICES_UI_STATUS_UNAVAILABLE_VALUE` | _(discovered, else `unavailable`)_ | Value meaning the console is up but cannot reach Floci |
+
+The last six exist only for a console that neither follows the
+[console contract](../ui/console-contract.md) nor describes itself in its image labels. Leave them
+unset otherwise: setting one overrides both discovery paths.
+
+See [Web Console](../ui/index.md) for running the console and swapping in a third-party one, and
+[Console Contract v1](../ui/console-contract.md) for writing one.
+
## Services — Additional
| Variable | Default | Description |
diff --git a/docs/configuration/ports.md b/docs/configuration/ports.md
index e8a4e7836c..38f105986c 100644
--- a/docs/configuration/ports.md
+++ b/docs/configuration/ports.md
@@ -5,6 +5,7 @@
| Port / Range | Protocol | Purpose | docker-compose mapping required? |
|---|---|---|---|
| `4566` | HTTP | AWS APIs and ECR Docker Distribution | Yes |
+| `4500` | HTTP | Web console sidecar, bound directly by the console container | **No** (see note) |
| `5100–5199` | HTTP | ECR Registry backing container, loopback-only implementation ports | No |
| `5672–5699` | AMQP | Amazon MQ (RabbitMQ) AMQP listener, bound directly by each broker container | **No** |
| `6379–6399` | TCP | ElastiCache Redis proxy (inside Floci) | Yes |
@@ -31,7 +32,7 @@ host:6379 → [docker-compose ports mapping] → Floci container:6379 →
Because the listener is inside the Floci container, `ports:` in `docker-compose.yml` is required to make it reachable from the host.
-### Direct container binding (EKS, OpenSearch, Amazon MQ)
+### Direct container binding (web console, EKS, OpenSearch, Amazon MQ)
Floci tells the Docker daemon to start a sidecar/service container and bind its port **directly on the host**. Floci itself communicates with the container via the shared Docker network (container name + internal port). The host port is bound by Docker, not by Floci.
diff --git a/docs/ui/console-contract.md b/docs/ui/console-contract.md
new file mode 100644
index 0000000000..2c012aa5a9
--- /dev/null
+++ b/docs/ui/console-contract.md
@@ -0,0 +1,246 @@
+# Floci Console Contract v1
+
+**Status:** stable. Implemented by Floci since the release this page shipped in.
+**Audience:** authors of a web console that wants to run against Floci.
+
+Floci can run any web console as a sidecar container, not only the one it ships. This page is the
+contract between the two. A console that implements it runs with no configuration at all: the
+operator sets one image name and Floci does the rest.
+
+If you are running a console rather than writing one, see [Web Console](index.md).
+
+## The short version
+
+Three things make a console a Floci console:
+
+1. It listens for HTTP on the port given in the `PORT` environment variable, default `4500`.
+2. It serves `GET /api/health`.
+3. It talks to Floci at the URL in `AWS_ENDPOINT_URL`.
+
+Everything else on this page is detail.
+
+The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be interpreted as described in
+[RFC 2119](https://www.rfc-editor.org/rfc/rfc2119).
+
+## What Floci gives the console
+
+Floci starts the console container with the same AWS baseline it gives every container it launches,
+so a console built on any AWS SDK is configured entirely by that SDK's ordinary endpoint and
+credential discovery.
+
+| Variable | Example | Notes |
+|---|---|---|
+| `AWS_ENDPOINT_URL` | `http://floci:4566` | The canonical endpoint. Every SDK reads it. |
+| `FLOCI_ENDPOINT` | `http://floci:4566` | The same value, for a console that predates the contract. |
+| `FLOCI_HOSTNAME` | `floci` | Host part of the endpoint. |
+| `AWS_REGION` | `us-east-1` | Floci's default region. |
+| `AWS_DEFAULT_REGION` | `us-east-1` | The same value. |
+| `AWS_ACCESS_KEY_ID` | `test` | Placeholder. Floci's own credentials are never forwarded. |
+| `AWS_SECRET_ACCESS_KEY` | `test` | Placeholder. |
+| `AWS_SESSION_TOKEN` | `test` | Placeholder. |
+| `PORT` | `4500` | The port the console MUST listen on. |
+| `FLOCI_CLOUD` | `aws` | Which emulator this is: `aws`, `gcp`, `az` or `oci`. |
+| `FLOCI_TLS_SKIP_VERIFY` | `1` | Present only when the operator opted out of TLS verification. |
+| `NODE_TLS_REJECT_UNAUTHORIZED` | `0` | The same instruction in the form a Node or Bun client honours. |
+
+Operator-supplied `extra-env` entries are applied last and may override any of these, except
+`PORT` and `AWS_ENDPOINT_URL`. Those two are structural: Floci has already used them to publish
+the container's port, to aim the readiness probe, and to decide whether an existing sidecar is
+still addressing this Floci. Setting them through `extra-env` would change only the console's
+copy, leaving a sidecar that listens where nothing is published or that is recreated on every
+check. Floci ignores such an entry and logs which key to use instead:
+`floci.services.ui.internal-port` and `floci.services.ui.endpoint` set the environment and the
+structural path together.
+
+## What the console gives Floci
+
+### The health endpoint
+
+The console MUST serve `GET /api/health`. Floci polls it while the browser waits on the
+interstitial page, and again whenever the console's status is checked.
+
+```json
+{
+ "status": "ok",
+ "endpoint": "http://floci:4566",
+ "error": null,
+ "console": { "name": "my-console", "version": "1.2.3" }
+}
+```
+
+| Field | Required | Meaning |
+|---|---|---|
+| `status` | yes | `ok`, `unavailable`, or anything else for "still coming up" |
+| `endpoint` | no | The Floci endpoint the console is actually using. Shown to the user when it cannot be reached. |
+| `error` | no | Why the console cannot reach Floci. Shown to the user verbatim. |
+| `console` | no | Informational; carried in logs and diagnostics. |
+
+How Floci reads it:
+
+| Response | Floci's conclusion |
+|---|---|
+| `200` and `status` is `ok` | ready: the browser is redirected to the console |
+| `200` and `status` is `unavailable` | not ready, and `endpoint` plus `error` are shown to the user |
+| `200` and any other `status` | not ready, keep polling (a cold boot looks like this) |
+| anything other than `200`, or no response | not ready, keep polling |
+
+`status` MUST report whether the console can actually reach Floci, not merely whether its own
+process is alive. Reporting `ok` while Floci is unreachable turns a diagnosable failure into a
+console that loads and then shows nothing. A console that genuinely cannot tell SHOULD say so with
+[an empty `health-ready-field` label](#self-description-labels), which makes any `200` count as
+ready.
+
+The health endpoint MUST NOT require authentication, and SHOULD respond within a second.
+
+### Reaching Floci
+
+- The console MUST take its endpoint from `AWS_ENDPOINT_URL` and MUST NOT hardcode
+ `localhost:4566`. The address is resolved at start time and is usually a container IP on a shared
+ Docker network, not localhost.
+- The console MUST sign requests with SigV4 using the injected credentials. Floci accepts the
+ placeholder values; it does not accept unsigned requests on the AWS APIs.
+- The console MUST tolerate an endpoint whose host is a bare IP address and whose scheme is plain
+ `http` even when Floci is running with TLS enabled. Floci's self-signed certificate carries no IP
+ SAN for its own container address, and its listener does HTTP/HTTPS protocol detection on one
+ port, so `http://<container-ip>:4566` is the reachable form. See
+ [TLS / HTTPS](../configuration/tls.md).
+- When `FLOCI_TLS_SKIP_VERIFY` is set, the console SHOULD skip certificate verification on its
+ connection to Floci, and only on that connection.
+- The console SHOULD re-resolve rather than cache a dead endpoint. Floci's container IP changes
+ when Floci restarts.
+
+### The container
+
+- The console MUST serve its application at `/`. Floci redirects the browser to
+ `http://<host>:<published-port>/` and has no way to add a path prefix.
+- The console MUST bind `0.0.0.0`, not `127.0.0.1`, or the published port reaches nothing.
+- The console MUST NOT require the Docker socket, a mounted volume, or any host path. Floci gives
+ it none of them.
+- The console SHOULD run as a non-root user.
+- The console SHOULD start in well under a minute. Floci polls indefinitely, but the user is
+ watching an interstitial page the whole time.
+- The console MAY be stateless and MUST tolerate being stopped and recreated at any time: Floci
+ recreates it whenever the endpoint it was built with no longer addresses the running Floci.
+
+## Self-description labels
+
+A console whose shape differs from the contract's defaults can say so in its own image labels,
+rather than making every operator configure it by hand. Floci reads them from the image at start
+time.
+
+Labels are read only when the image declares the contract version Floci implements:
+
+```dockerfile
+LABEL io.floci.console.contract="1"
+LABEL io.floci.console.name="StackPort"
+LABEL io.floci.console.port="8080"
+LABEL io.floci.console.health-path="/api/health"
+LABEL io.floci.console.health-ready-field="status"
+LABEL io.floci.console.health-ready-value="ok"
+LABEL io.floci.console.health-unavailable-value="unavailable"
+LABEL io.floci.console.endpoint-env="CONSOLE_API_URL"
+LABEL io.floci.console.clouds="aws"
+LABEL io.floci.console.url="https://example.com/my-console"
+```
+
+| Label | Default | Meaning |
+|---|---|---|
+| `contract` | _(none)_ | Must be `1`. Without it every other label is ignored. |
+| `name` | _(none)_ | Display name used in Floci's logs and error messages. |
+| `port` | `4500` | Port the console listens on. A value that is not a usable port number is ignored with a warning. |
+| `health-path` | `/api/health` | Path Floci probes. A leading slash is added if missing. |
+| `health-ready-field` | `status` | Field in the health response that reports readiness. Declare it **empty** to say the endpoint is a plain liveness check, which makes any `200` count as ready. |
+| `health-ready-value` | `ok` | Value of that field meaning the console reached Floci. |
+| `health-unavailable-value` | `unavailable` | Value meaning the console is up but cannot reach Floci. |
+| `endpoint-env` | _(none)_ | An **additional** variable to repeat the endpoint in, for a console that reads neither `AWS_ENDPOINT_URL` nor `FLOCI_ENDPOINT`. |
+| `clouds` | `aws` | Comma-separated emulators the console supports. Informational today. |
+
+Only the labels you set are applied; the rest keep their resolved values.
+
+## How Floci resolves a console's shape
+
+Four layers, first match wins, resolved separately for each setting:
+
+1. explicit `floci.services.ui.*` configuration set by the operator
+2. `io.floci.console.*` labels on the image
+3. a built-in profile for a console Floci recognises by image name
+4. the contract v1 defaults
+
+Layer 3 exists for one console today: `floci/floci-ui` answers `/api/clouds/aws/status` with a
+`runtime` field rather than `/api/health` with a `status` field, because it predates the contract.
+The entry retires once floci-ui serves `/api/health`.
+
+The practical consequence is that an operator running a contract-conformant console sets nothing
+beyond the image name, and an operator running a console that neither conforms nor labels itself
+can still make it work from configuration alone.
+
+## Conformance checklist
+
+- [ ] Listens on `0.0.0.0:$PORT`, defaulting to `4500` when `PORT` is unset
+- [ ] Serves `GET /api/health` unauthenticated, returning JSON with a `status` field
+- [ ] `status` is `ok` only when Floci is actually reachable
+- [ ] Reports `unavailable` with `endpoint` and `error` when Floci is not reachable
+- [ ] Reads `AWS_ENDPOINT_URL`; nothing is hardcoded to `localhost:4566`
+- [ ] Signs with SigV4 using the injected credentials
+- [ ] Works when the endpoint is `http://<ip>:4566` and when it is `https://<name>:4566`
+- [ ] Honours `FLOCI_TLS_SKIP_VERIFY`
+- [ ] Serves the application at `/`
+- [ ] Needs no Docker socket, no volume, no host path
+- [ ] Declares `io.floci.console.contract="1"` and any label whose value differs from the default
+
+## Reference health handlers
+
+=== "Node"
+
+ ```js
+ import express from "express";
+ import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
+
+ const endpoint = process.env.AWS_ENDPOINT_URL;
+ const sts = new STSClient({ endpoint, region: process.env.AWS_REGION });
+ const app = express();
+
+ app.get("/api/health", async (_req, res) => {
+ try {
+ await sts.send(new GetCallerIdentityCommand({}));
+ res.json({ status: "ok", endpoint });
+ } catch (err) {
+ res.json({ status: "unavailable", endpoint, error: String(err) });
+ }
+ });
+
+ app.listen(Number(process.env.PORT ?? 4500), "0.0.0.0");
+ ```
+
+=== "Go"
+
+ ```go
+ endpoint := os.Getenv("AWS_ENDPOINT_URL")
+
+ http.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
+ body := map[string]any{"status": "ok", "endpoint": endpoint}
+ if _, err := sts.GetCallerIdentity(r.Context(), &sts.GetCallerIdentityInput{}); err != nil {
+ body = map[string]any{"status": "unavailable", "endpoint": endpoint, "error": err.Error()}
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(body)
+ })
+
+ port := os.Getenv("PORT")
+ if port == "" {
+ port = "4500"
+ }
+ http.ListenAndServe("0.0.0.0:"+port, nil)
+ ```
+
+## Known consoles
+
+| Console | Image | Notes |
+|---|---|---|
+| Floci UI | `floci/floci-ui` | Floci's own console, the default. Served by a built-in profile until it adopts `/api/health`. |
+| [Floci Dash](https://github.com/ofsazib/floci-dash) | `ghcr.io/ofsazib/floci-dash` | AWS Console-style dashboard. Honours `PORT`; reads `FLOCI_URL` and answers `/api/healthz`, so it needs those two named. [Setup](index.md#example-floci-dash). |
+| [StackPort](https://github.com/DaviReisVieira/stackport) | `davireis/stackport` | Third-party; listens on 8080 and answers `/api/health`. |
+
+Built a console against this contract? Open a pull request adding it to this table, or an issue at
+[floci-io/floci](https://github.com/floci-io/floci/issues) if something in the contract got in your
+way.
diff --git a/docs/ui/index.md b/docs/ui/index.md
new file mode 100644
index 0000000000..192753f177
--- /dev/null
+++ b/docs/ui/index.md
@@ -0,0 +1,171 @@
+# Web Console
+
+Floci ships a browser-based console for inspecting the resources in your local emulator. It runs as
+a sidecar container that Floci starts for you on demand.
+
+**Open it at:** `http://localhost:4566/_floci/ui`
+
+The first request starts the console container, so you land on a short "starting the console" page
+that redirects as soon as it is ready. Later requests redirect straight away.
+
+## How it works
+
+Floci starts nothing at boot. On the first `/_floci/ui` request it:
+
+1. pulls the console image if it is not present locally,
+2. starts it with `-p 4500:4500` on Floci's Docker network,
+3. hands it Floci's own reachable address plus the standard AWS environment,
+4. polls the console's health endpoint until it reports it can reach Floci,
+5. redirects your browser to `http://<host>:4500/`.
+
+A console container that survives a Floci restart is adopted rather than recreated, unless the
+address it was built with no longer points at the running Floci, in which case it is replaced so
+the console reconnects without you doing anything.
+
+Console container logs are streamed into CloudWatch Logs under the log group `/floci/ui`, so
+`awslocal logs tail /floci/ui` shows them.
+
+## Ports
+
+Port `4500` is bound on the host by Docker, not by Floci, so it needs **no** `ports:` entry in your
+`docker-compose.yml`. See [Ports Reference](../configuration/ports.md).
+
+## Configuration
+
+All keys live under `floci.services.ui.*`, so `FLOCI_SERVICES_UI_*` as environment variables.
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_UI_ENABLED` | `true` | Enable the console sidecar |
+| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
+| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
+| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
+| `FLOCI_SERVICES_UI_DOCKER_NETWORK` | _(none)_ | Docker network for the sidecar (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
+| `FLOCI_SERVICES_UI_ENDPOINT` | _(derived)_ | Floci endpoint handed to the console, instead of deriving it from the Docker host and TLS settings |
+| `FLOCI_SERVICES_UI_EXTRA_ENV` | _(none)_ | Extra `KEY=VALUE` entries for the console, comma-separated (escape a literal comma as `\,`). Applied last, so an entry may override an injected default |
+| `FLOCI_SERVICES_UI_INSECURE_SKIP_TLS_VERIFY` | `false` | Have the console skip TLS verification on its connection to Floci |
+
+The next group exists only for a console that neither follows the
+[console contract](console-contract.md) nor describes itself in its image labels. Leave them unset
+otherwise: setting one overrides both of those discovery paths.
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_UI_INTERNAL_PORT` | _(discovered, else `4500`)_ | Port the console listens on inside its container |
+| `FLOCI_SERVICES_UI_ENDPOINT_ENV` | _(none)_ | An extra variable to repeat the Floci endpoint in, for a console reading neither `AWS_ENDPOINT_URL` nor `FLOCI_ENDPOINT` |
+| `FLOCI_SERVICES_UI_STATUS_PATH` | _(discovered, else `/api/health`)_ | Path the readiness probe requests |
+| `FLOCI_SERVICES_UI_STATUS_READY_FIELD` | _(discovered, else `status`)_ | JSON field reporting readiness. Set to `none` for a console whose health endpoint is a plain liveness check, which makes any `200` count as ready |
+| `FLOCI_SERVICES_UI_STATUS_READY_VALUE` | _(discovered, else `ok`)_ | Value of that field meaning the console reached Floci |
+| `FLOCI_SERVICES_UI_STATUS_UNAVAILABLE_VALUE` | _(discovered, else `unavailable`)_ | Value meaning the console is up but cannot reach Floci |
+
+## Running a different console
+
+Any console implementing the [Floci console contract](console-contract.md) works with nothing but
+an image name:
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_IMAGE: acme/my-console:1.0
+```
+
+A console that listens elsewhere, or answers a different health route, needs that much said. For
+[StackPort](https://github.com/DaviReisVieira/stackport), which listens on 8080 and answers
+`/api/health`:
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_IMAGE: davireis/stackport:latest
+ FLOCI_SERVICES_UI_CONTAINER_NAME: floci-stackport
+ FLOCI_SERVICES_UI_PORT: "8080"
+ FLOCI_SERVICES_UI_INTERNAL_PORT: "8080"
+```
+
+### Example: Floci Dash
+
+[Floci Dash](https://github.com/ofsazib/floci-dash) is an AWS Console-style dashboard for Floci. It
+deviates from the contract in exactly two places, so two settings are all it takes:
+
+```yaml
+services:
+ floci:
+ image: floci/floci:latest
+ ports:
+ - "4566:4566"
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ environment:
+ FLOCI_HOSTNAME: floci
+ FLOCI_BASE_URL: http://floci:4566
+ FLOCI_SERVICES_UI_IMAGE: ghcr.io/ofsazib/floci-dash:latest
+ FLOCI_SERVICES_UI_CONTAINER_NAME: floci-dash
+ # Floci Dash reads its endpoint from FLOCI_URL, not AWS_ENDPOINT_URL
+ FLOCI_SERVICES_UI_ENDPOINT_ENV: FLOCI_URL
+ # and answers /api/healthz rather than /api/health
+ FLOCI_SERVICES_UI_STATUS_PATH: /api/healthz
+```
+
+Then open `http://localhost:4566/_floci/ui` and Floci starts the dashboard on port 4500.
+
+Nothing else is needed, and it is worth seeing why:
+
+- **The port is not configured.** Floci Dash defaults to 3000 but honours `PORT`, which Floci sets
+ to the resolved internal port, so it listens on 4500 and Floci publishes it there. A console that
+ ignores `PORT` needs `FLOCI_SERVICES_UI_INTERNAL_PORT` instead, as StackPort does above.
+- **The health fields are not configured.** Floci Dash answers `{"status": "ok"}`, which already
+ matches the contract's `status` field and `ok` value. Only its path differs.
+- **The endpoint is not configured, only its name.** Floci resolves its own reachable address at
+ start time; `FLOCI_SERVICES_UI_ENDPOINT_ENV` just repeats that value under a second name.
+
+Two caveats:
+
+- Its EC2 terminal feature wants the Docker socket, which a Floci-managed sidecar is not given. The
+ rest of the dashboard works; that one feature does not.
+- `/api/healthz` is a liveness check: it answers `{"status": "ok"}` whether or not the dashboard can
+ reach Floci. So Floci reports it ready as soon as it is up. If the dashboard loads but every page
+ is empty, check that `FLOCI_SERVICES_UI_ENDPOINT_ENV: FLOCI_URL` is actually set. Without it the
+ dashboard falls back to its own `localhost:4566`, which inside its container is nothing, and the
+ readiness probe cannot tell.
+
+!!! tip "Two labels would remove both settings"
+
+ A console can carry its own quirks in its image instead of asking every operator to configure
+ them. Adding `io.floci.console.contract="1"`, `io.floci.console.health-path="/api/healthz"` and
+ `io.floci.console.endpoint-env="FLOCI_URL"` to the image would reduce the above to
+ `FLOCI_SERVICES_UI_IMAGE` alone. See [Console Contract v1](console-contract.md#self-description-labels).
+
+The endpoint itself is never configured by hand. Floci resolves its own reachable address at start
+time and injects it as `AWS_ENDPOINT_URL`, which is also what tells a console left over from a
+previous run that it is pointing at a dead address.
+
+## Troubleshooting
+
+!!! note "The page says the image is unavailable"
+
+ Floci could not pull the console image. Pull it yourself to see the real error:
+ `docker pull floci/floci-ui:latest`.
+
+!!! note "The page says Floci could not reach the container runtime"
+
+ Floci needs the Docker socket. Check that `/var/run/docker.sock` is mounted into the Floci
+ container. On SELinux hosts the bind-mount may need relabeling (`:z`) or
+ `--security-opt label=disable`. See [Docker Configuration](../configuration/docker.md).
+
+!!! note "The console loads but says it cannot reach Floci"
+
+ The message includes the address the console tried. If Floci is running with TLS, the derived
+ endpoint may be `https://<container-ip>:4566`, which fails certificate verification because
+ Floci's self-signed certificate carries no IP SAN for its own container address. Either point
+ the console at the plain-HTTP form, which reaches the same TLS-enabled listener:
+
+ ```yaml
+ FLOCI_SERVICES_UI_ENDPOINT: http://floci:4566
+ ```
+
+ or set `FLOCI_SERVICES_UI_INSECURE_SKIP_TLS_VERIFY: "true"`. See [TLS / HTTPS](../configuration/tls.md).
+
+!!! note "The console keeps saying it is starting"
+
+ Check the container's own logs: `awslocal logs tail /floci/ui --follow`, or
+ `docker logs floci-ui`. A console whose health endpoint is at a different path than Floci is
+ probing never reports ready; `FLOCI_SERVICES_UI_STATUS_PATH` fixes that.
diff --git a/mkdocs.yml b/mkdocs.yml
index a98cd39aad..344a7e57c2 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -212,6 +212,9 @@ nav:
- Cost and Usage Reports: services/cur.md
- BCM Pricing Calculator: services/bcm-pricing-calculator.md
- BCM Data Exports: services/bcm-data-exports.md
+ - Web Console:
+ - Overview: ui/index.md
+ - Console Contract v1: ui/console-contract.md
- Testcontainers:
- Overview: testcontainers/index.md
- Java: testcontainers/java.md
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 cd1dcfc7c1..243bf9693b 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -1992,6 +1992,16 @@ public interface EmulatorConfig {
String emitMode();
}
+ /**
+ * The web console Floci runs as a sidecar. Any console implementing the Floci console
+ * contract works with no configuration beyond {@link #image()}; these keys exist to run one
+ * that deviates from it. See {@code docs/ui/console-contract.md}.
+ *
+ * <p>Every contract key is optional on purpose. "Unset" is what lets Floci fall back to the
+ * image's own {@code io.floci.console.*} labels, then to a built-in profile, then to the
+ * contract defaults, so a value here is only ever needed for a console that describes itself
+ * neither way.
+ */
interface UiServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -2006,21 +2016,78 @@ public interface EmulatorConfig {
@WithDefault("4500")
int port();
+ /**
+ * Port the console listens on <em>inside</em> its container, published as {@link #port()}.
+ * Env: {@code FLOCI_SERVICES_UI_INTERNAL_PORT}
+ *
+ * <p>Contract default 4500. The console is told the resolved value through {@code PORT},
+ * so this only needs setting for a console with a fixed port of its own that does not
+ * declare it as an {@code io.floci.console.port} label.
+ */
+ OptionalInt internalPort();
+
+ /**
+ * An <em>additional</em> environment variable the resolved Floci endpoint is repeated in.
+ * Env: {@code FLOCI_SERVICES_UI_ENDPOINT_ENV}
+ *
+ * <p>Every console already receives the endpoint as {@code AWS_ENDPOINT_URL} (the contract's
+ * canonical name) and as {@code FLOCI_ENDPOINT}, so this is only for a console that reads
+ * neither. The endpoint's <em>value</em> cannot be set by hand in the containerized case: it
+ * is Floci's own container IP, discovered at start time.
+ */
+ Optional<String> endpointEnv();
+
+ /**
+ * Extra environment entries for the console, each {@code KEY=VALUE}.
+ * Env: {@code FLOCI_SERVICES_UI_EXTRA_ENV} (comma-separated; escape a literal comma as
+ * {@code \,}).
+ *
+ * <p>Applied last, so an entry may also override one of the injected defaults.
+ */
+ Optional<List<String>> extraEnv();
+
+ /**
+ * Path the readiness probe requests on the console.
+ * Env: {@code FLOCI_SERVICES_UI_STATUS_PATH}
+ *
+ * <p>Contract default {@code /api/health}.
+ */
+ Optional<String> statusPath();
+
+ /**
+ * JSON field in the health response that says whether the console can reach Floci, and the
+ * values that mean it can and that it cannot.
+ * Env: {@code FLOCI_SERVICES_UI_STATUS_READY_FIELD},
+ * {@code FLOCI_SERVICES_UI_STATUS_READY_VALUE},
+ * {@code FLOCI_SERVICES_UI_STATUS_UNAVAILABLE_VALUE}
+ *
+ * <p>Contract defaults {@code status}, {@code ok} and {@code unavailable}. Set the field to
+ * {@code none} for a console whose health endpoint is a plain liveness check, which makes
+ * any {@code 200} count as ready. An empty value cannot express that: an environment
+ * variable set to nothing arrives as an absent property and would silently mean "use the
+ * default field".
+ */
+ Optional<String> statusReadyField();
+
+ Optional<String> statusReadyValue();
+
+ Optional<String> statusUnavailableValue();
+
@WithDefault("false")
boolean keepRunningOnShutdown();
Optional<String> dockerNetwork();
/**
- * Overrides the Floci endpoint handed to the UI sidecar, instead of deriving it from
+ * Overrides the Floci endpoint handed to the console, 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
+ * which a Node/Bun console's 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>}
+ * HTTP/HTTPS protocol detection, so pointing the console 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
@@ -2029,12 +2096,13 @@ public interface EmulatorConfig {
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}
+ * Disables TLS certificate verification in the console's HTTP client by injecting
+ * {@code FLOCI_TLS_SKIP_VERIFY=1} (and {@code NODE_TLS_REJECT_UNAUTHORIZED=0} for a
+ * Node/Bun console). 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
+ * endpoint work. Scoped to the console's connection to Floci; it does not affect Floci's
* own TLS. Prefer {@link #endpoint()} where an {@code http://} endpoint is acceptable.
*/
@WithDefault("false")
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index c7f26b13b5..1e6feef48f 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -595,6 +595,25 @@ public class ContainerLifecycleManager {
}
}
+ /**
+ * Labels declared on an image, empty when they could not be read.
+ *
+ * <p>Ensures the image is present first, so the labels of an image that has never been pulled
+ * are still readable. A failure is reported as empty rather than thrown: labels are advisory
+ * metadata, and a caller that cannot read them must fall back to its own defaults rather than
+ * fail the start it was preparing.
+ */
+ public Optional<Map<String, String>> imageLabels(String image) {
+ try {
+ String resolved = imageCacheService.ensureImageExists(image);
+ Map<String, String> labels = dockerClient.inspectImageCmd(resolved).exec().getConfig().getLabels();
+ return Optional.of(labels == null ? Map.of() : Map.copyOf(labels));
+ } catch (Exception e) {
+ LOG.debugv("Could not read labels of image {0}: {1}", image, 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. */
diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfile.java b/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfile.java
new file mode 100644
index 0000000000..168709b6be
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfile.java
@@ -0,0 +1,42 @@
+package io.github.hectorvent.floci.services.floci.ui;
+
+/**
+ * The resolved shape of the web console Floci is running as its sidecar: the port it listens on,
+ * the extra name it wants Floci's endpoint under, and how to read its health response.
+ *
+ * <p>Every field has a contract-v1 default, so a console that implements
+ * <a href="https://floci.io/floci/ui/console-contract/">the console contract</a> needs no
+ * configuration at all. The values are resolved once per sidecar start by
+ * {@link ConsoleProfileResolver}.
+ *
+ * @param internalPort port the console listens on inside its container, handed to it as
+ * {@code PORT} and published as {@code floci.services.ui.port}
+ * @param endpointEnv additional environment variable the Floci endpoint is repeated in,
+ * for a console that reads neither {@code AWS_ENDPOINT_URL} nor
+ * {@code FLOCI_ENDPOINT}; blank when the baseline names are enough
+ * @param healthPath path the readiness probe requests, always with a leading slash
+ * @param healthReadyField JSON field in the health response that reports readiness; blank
+ * means any {@code 200} counts as ready
+ * @param healthReadyValue value of that field which means the console reached Floci
+ * @param healthUnavailableValue value of that field which means the console is up but cannot reach
+ * Floci, so the failure is worth showing rather than polling through
+ * @param displayName what to call the console in logs and user-facing errors
+ */
+public record ConsoleProfile(int internalPort,
+ String endpointEnv,
+ String healthPath,
+ String healthReadyField,
+ String healthReadyValue,
+ String healthUnavailableValue,
+ String displayName) {
+
+ /** Whether the health response carries a readiness field, rather than being a bare liveness check. */
+ public boolean hasReadyField() {
+ return healthReadyField != null && !healthReadyField.isBlank();
+ }
+
+ /** Whether the console wants Floci's endpoint under a name the AWS baseline does not already set. */
+ public boolean hasEndpointAlias() {
+ return endpointEnv != null && !endpointEnv.isBlank();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolver.java b/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolver.java
new file mode 100644
index 0000000000..d1475774ec
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolver.java
@@ -0,0 +1,205 @@
+package io.github.hectorvent.floci.services.floci.ui;
+
+import java.util.Map;
+import java.util.Optional;
+
+import io.github.hectorvent.floci.config.EmulatorConfig.UiServiceConfig;
+import org.jboss.logging.Logger;
+
+/**
+ * Resolves the {@link ConsoleProfile} for the configured console image.
+ *
+ * <p>Four layers, most specific first, each field resolved independently:
+ *
+ * <ol>
+ * <li>explicit {@code floci.services.ui.*} configuration</li>
+ * <li>{@code io.floci.console.*} labels on the image, when it declares
+ * {@code io.floci.console.contract=1}</li>
+ * <li>a built-in profile for a console Floci recognises by image name</li>
+ * <li>the contract-v1 defaults</li>
+ * </ol>
+ *
+ * <p>The layering is what keeps a console that predates the contract working without asking its
+ * operator for six environment variables, while a console that implements the contract needs none
+ * of them. Everything here is static and free of Docker so the resolution order is directly
+ * testable.
+ */
+public final class ConsoleProfileResolver {
+
+ private static final Logger LOG = Logger.getLogger(ConsoleProfileResolver.class);
+
+ /** Label prefix a console self-describes with. */
+ public static final String LABEL_PREFIX = "io.floci.console.";
+ /** Opt-in label. Only an image declaring this contract version has its other labels read. */
+ public static final String LABEL_CONTRACT = LABEL_PREFIX + "contract";
+ /** Contract version this Floci implements. */
+ public static final String CONTRACT_VERSION = "1";
+
+ /**
+ * Value that turns the readiness field off from configuration. An empty string cannot be relied
+ * on: an environment variable set to nothing reaches SmallRye as an absent property, which would
+ * silently mean "use the default field" instead of "this console has no readiness field".
+ */
+ static final String NO_READY_FIELD = "none";
+
+ private static final String FLOCI_UI_REPOSITORY = "floci-ui";
+
+ private ConsoleProfileResolver() {
+ }
+
+ /** The defaults every console gets for free by implementing the contract. */
+ public static ConsoleProfile contractV1() {
+ return new ConsoleProfile(4500, "", "/api/health", "status", "ok", "unavailable",
+ "the Floci web console");
+ }
+
+ /**
+ * Resolves the full profile for an image.
+ *
+ * @param resolvedImage the image reference after registry resolution
+ * ({@code ContainerBuilder.resolveImage})
+ * @param labels the image's labels, empty when they could not be read
+ * @param config the {@code floci.services.ui.*} configuration
+ */
+ public static ConsoleProfile resolve(String resolvedImage,
+ Optional<Map<String, String>> labels,
+ UiServiceConfig config) {
+ ConsoleProfile profile = builtIn(resolvedImage);
+ profile = fromLabels(labels.orElse(Map.of()), profile);
+ return withOverrides(config, profile);
+ }
+
+ /**
+ * The built-in profile for a console Floci ships with, or the contract defaults for anything else.
+ *
+ * <p>{@code floci/floci-ui} answers {@code /api/clouds/aws/status} with a {@code runtime} field,
+ * which predates the contract. It is recognised by name so upgrading Floci does not strand the
+ * console it already runs; the entry retires once floci-ui serves {@code /api/health}.
+ */
+ public static ConsoleProfile builtIn(String resolvedImage) {
+ if (FLOCI_UI_REPOSITORY.equals(repositoryOf(resolvedImage))) {
+ return new ConsoleProfile(4500, "", "/api/clouds/aws/status", "runtime", "reachable",
+ "unavailable", "the Floci web console");
+ }
+ return contractV1();
+ }
+
+ /**
+ * Applies an image's self-description over a base profile.
+ *
+ * <p>Ignored entirely unless the image declares the contract version Floci implements: an image
+ * that happens to carry an {@code io.floci.console.*} label for some future contract must not
+ * have it read under this one's meaning.
+ */
+ public static ConsoleProfile fromLabels(Map<String, String> labels, ConsoleProfile base) {
+ if (labels == null || !CONTRACT_VERSION.equals(trimmed(labels.get(LABEL_CONTRACT)))) {
+ return base;
+ }
+ return new ConsoleProfile(
+ labelPort(labels, base.internalPort()),
+ label(labels, "endpoint-env", base.endpointEnv()),
+ normalizePath(label(labels, "health-path", base.healthPath())),
+ labelReadyField(labels, base.healthReadyField()),
+ label(labels, "health-ready-value", base.healthReadyValue()),
+ label(labels, "health-unavailable-value", base.healthUnavailableValue()),
+ label(labels, "name", base.displayName()));
+ }
+
+ /** Applies explicit configuration over a base profile. Configuration always wins. */
+ public static ConsoleProfile withOverrides(UiServiceConfig config, ConsoleProfile base) {
+ return new ConsoleProfile(
+ config.internalPort().orElse(base.internalPort()),
+ override(config.endpointEnv(), base.endpointEnv()),
+ normalizePath(override(config.statusPath(), base.healthPath())),
+ configuredReadyField(config.statusReadyField(), base.healthReadyField()),
+ override(config.statusReadyValue(), base.healthReadyValue()),
+ override(config.statusUnavailableValue(), base.healthUnavailableValue()),
+ base.displayName());
+ }
+
+ /**
+ * The repository name of an image reference, without registry, namespace, tag or digest:
+ * {@code ghcr.io/floci-io/floci-ui@sha256:abc} and {@code floci/floci-ui:latest} both yield
+ * {@code floci-ui}. A fork republished under another namespace is still the same console, so
+ * only the final path segment is compared.
+ */
+ static String repositoryOf(String image) {
+ if (image == null || image.isBlank()) {
+ return "";
+ }
+ String reference = image.trim();
+ int digest = reference.indexOf('@');
+ if (digest >= 0) {
+ reference = reference.substring(0, digest);
+ }
+ int lastSlash = reference.lastIndexOf('/');
+ String lastSegment = reference.substring(lastSlash + 1);
+ int tag = lastSegment.lastIndexOf(':');
+ if (tag >= 0) {
+ lastSegment = lastSegment.substring(0, tag);
+ }
+ return lastSegment;
+ }
+
+ /** Normalizes a health path to a leading slash, so a bare {@code api/health} still forms a URL. */
+ static String normalizePath(String path) {
+ if (path == null || path.isBlank()) {
+ return contractV1().healthPath();
+ }
+ String trimmed = path.trim();
+ return trimmed.startsWith("/") ? trimmed : "/" + trimmed;
+ }
+
+ private static int labelPort(Map<String, String> labels, int fallback) {
+ String raw = trimmed(labels.get(LABEL_PREFIX + "port"));
+ if (raw.isEmpty()) {
+ return fallback;
+ }
+ try {
+ int port = Integer.parseInt(raw);
+ if (port > 0 && port <= 65535) {
+ return port;
+ }
+ LOG.warnv("Ignoring image label {0}port=\"{1}\": not a usable port number.", LABEL_PREFIX, raw);
+ } catch (NumberFormatException e) {
+ LOG.warnv("Ignoring image label {0}port=\"{1}\": not a number ({2}).",
+ LABEL_PREFIX, raw, e.getMessage());
+ }
+ return fallback;
+ }
+
+ /**
+ * The readiness field from a label. Unlike every other label, a declared-but-empty value is
+ * meaningful: it is how a console with a plain liveness endpoint says it has no field to read.
+ */
+ private static String labelReadyField(Map<String, String> labels, String fallback) {
+ String key = LABEL_PREFIX + "health-ready-field";
+ if (!labels.containsKey(key)) {
+ return fallback;
+ }
+ String value = trimmed(labels.get(key));
+ return NO_READY_FIELD.equalsIgnoreCase(value) ? "" : value;
+ }
+
+ private static String configuredReadyField(Optional<String> configured, String fallback) {
+ String value = configured.map(String::trim).orElse("");
+ if (value.isEmpty()) {
+ return fallback;
+ }
+ return NO_READY_FIELD.equalsIgnoreCase(value) ? "" : value;
+ }
+
+ private static String label(Map<String, String> labels, String suffix, String fallback) {
+ String value = trimmed(labels.get(LABEL_PREFIX + suffix));
+ return value.isEmpty() ? fallback : value;
+ }
+
+ private static String override(Optional<String> configured, String fallback) {
+ String value = configured.map(String::trim).orElse("");
+ return value.isEmpty() ? fallback : value;
+ }
+
+ private static String trimmed(String value) {
+ return value == null ? "" : value.trim();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java b/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
index 7fe2f25000..f6159f2cef 100644
--- a/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
@@ -4,7 +4,9 @@ import java.io.Closeable;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -26,6 +28,8 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
+import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
+import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
@@ -34,9 +38,14 @@ 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).
+ * Manages the lifecycle of the web-console sidecar container, the browser-facing Floci console.
+ * The container is started lazily on the first {@code /_floci/ui} hit and reused across restarts
+ * (one per Floci instance).
+ *
+ * <p>The console is not required to be {@code floci/floci-ui}. Any image implementing the Floci
+ * console contract (listen on {@code PORT}, serve {@code GET /api/health}, reach Floci at
+ * {@code AWS_ENDPOINT_URL}) runs here unconfigured; {@link ConsoleProfileResolver} works out the
+ * rest from the image's labels, a built-in profile, or {@code floci.services.ui.*}.
*
* <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
@@ -46,10 +55,45 @@ import org.jboss.logging.Logger;
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 static final String RUNTIME_STATUS_PATH = "/api/clouds/aws/status";
+
+ /**
+ * The contract's canonical endpoint variable. Every console receives the endpoint under this
+ * name, so it is also the one entry adoption compares to spot a sidecar left addressing a
+ * previous Floci.
+ */
+ static final String CANONICAL_ENDPOINT_ENV = "AWS_ENDPOINT_URL";
+
+ /** The port the console listens on. Structural: the port binding and the readiness probe use it too. */
+ static final String PORT_ENV = "PORT";
+
+ /**
+ * Environment entries {@code extra-env} must not set, because the manager has already used their
+ * values structurally and setting them here would change only the console's copy.
+ *
+ * <p>{@code PORT} decides where the console listens, but the Docker port binding and the
+ * readiness probe are both built from {@code profile.internalPort()}, so an override here
+ * produces a sidecar that listens on one port while Floci publishes and polls another.
+ * {@code AWS_ENDPOINT_URL} is the entry adoption compares to detect a sidecar left pointing at a
+ * previous Floci, so an override here reads as permanent drift and the container is recreated on
+ * every check.
+ *
+ * <p>Both have a supported key that feeds the structural path as well as the environment:
+ * {@code floci.services.ui.internal-port} and {@code floci.services.ui.endpoint}.
+ */
+ private static final Map<String, String> RESERVED_EXTRA_ENV = Map.of(
+ PORT_ENV, "floci.services.ui.internal-port",
+ CANONICAL_ENDPOINT_ENV, "floci.services.ui.endpoint");
+
+ /** Which emulator the console is talking to, so one console can serve several Floci flavours. */
+ private static final String FLOCI_CLOUD = "aws";
+
+ /**
+ * Credentials the console signs with. Passed explicitly rather than left to the baseline's
+ * fallback, which forwards Floci's <em>own</em> ambient AWS credentials into the container:
+ * acceptable for a workload the user wrote, not for a third-party console image.
+ */
+ private static final SessionCreds PLACEHOLDER_CREDENTIALS = new SessionCreds("test", "test", "test");
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -57,6 +101,7 @@ public class FlociUiManager {
private final ContainerDetector containerDetector;
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
private final DockerHostResolver dockerHostResolver;
+ private final LaunchedContainerAwsEnv awsEnv;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@@ -66,6 +111,8 @@ public class FlociUiManager {
private volatile String containerId;
private volatile Closeable logStream;
private volatile String lastError;
+ /** Shape of the configured console, resolved once per start. */
+ private volatile ConsoleProfile profile = ConsoleProfileResolver.contractV1();
/**
* URL the readiness probe connects to, resolved from the Docker API at start time.
* Published host ports (e.g. {@code -p 4500:4500}) only exist on the host's network
@@ -90,6 +137,7 @@ public class FlociUiManager {
ContainerDetector containerDetector,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
DockerHostResolver dockerHostResolver,
+ LaunchedContainerAwsEnv awsEnv,
EmulatorConfig config,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
@@ -99,6 +147,7 @@ public class FlociUiManager {
this.containerDetector = containerDetector;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.dockerHostResolver = dockerHostResolver;
+ this.awsEnv = awsEnv;
this.config = config;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
@@ -116,7 +165,8 @@ public class FlociUiManager {
return;
}
if (!config.services().ui().enabled()) {
- this.lastError = "The Floci UI is disabled (set floci.services.ui.enabled=true to enable it).";
+ this.lastError = "The Floci web console 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
@@ -124,19 +174,23 @@ public class FlociUiManager {
this.lastError = null;
String image = config.services().ui().image();
try {
+ this.profile = resolveProfile(image);
String name = ContainerStorageHelper.dockerName(config, config.services().ui().containerName());
Optional<Container> existing = lifecycleManager.findByName(name);
- if (existing.isPresent() && !replaceIfEndpointDrifted(existing.get())) {
+ if (existing.isPresent()
+ && !replaceIfNotRunning(existing.get())
+ && !replaceIfEndpointDrifted(existing.get())) {
adoptExisting(existing.get());
return;
}
int chosenPort = config.services().ui().port();
+ int internalPort = profile.internalPort();
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(name)
- .withEnv(injectedEnv())
- .withPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)
+ .withEnv(injectedEnv(profile))
+ .withPortBinding(internalPort, chosenPort)
.withDockerNetwork(resolveDockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
@@ -145,13 +199,14 @@ public class FlociUiManager {
ContainerSpec spec = specBuilder.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
- EndpointInfo endpoint = info.getEndpoint(CONTAINER_INTERNAL_PORT);
+ EndpointInfo endpoint = info.getEndpoint(internalPort);
this.containerId = info.containerId();
this.hostPort = resolveHostPort(endpoint, chosenPort);
- this.probeUrl = resolveProbeUrl(endpoint, hostPort);
+ this.probeUrl = resolveProbeUrl(profile, endpoint, hostPort);
this.started = true;
this.lastError = null;
- LOG.infov("Started floci-ui sidecar {0} on host port {1}", name, String.valueOf(hostPort));
+ LOG.infov("Started web console sidecar {0} from {1} on host port {2}",
+ name, image, String.valueOf(hostPort));
attachLogStream();
} catch (IllegalStateException e) {
// replaceIfEndpointDrifted() records its own specific message for a container with an
@@ -161,13 +216,27 @@ public class FlociUiManager {
if (this.lastError == null) {
this.lastError = e.getMessage();
}
- LOG.errorv(e, "Failed to start floci-ui sidecar: {0}", e.getMessage());
+ LOG.errorv(e, "Failed to start the web console 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);
+ LOG.errorv(e, "Failed to start the web console sidecar from image {0}", image);
}
}
+ /**
+ * Works out the shape of the configured console: its labels first, then a built-in profile,
+ * then the contract defaults, with {@code floci.services.ui.*} winning over all of them.
+ *
+ * <p>Reading the labels needs the image present, which is why this runs on the starter thread
+ * and not at injection time. A label read that fails is not an error here: the pull is
+ * attempted again by {@code createAndStart}, which reports the failure properly.
+ */
+ ConsoleProfile resolveProfile(String image) {
+ String resolvedImage = containerBuilder.resolveImage(image);
+ Optional<Map<String, String>> labels = lifecycleManager.imageLabels(resolvedImage);
+ return ConsoleProfileResolver.resolve(resolvedImage, labels, config.services().ui());
+ }
+
/**
* Triggers {@link #ensureStarted()} on a background thread and returns immediately,
* so the caller can serve the interstitial page while the (possibly slow) image
@@ -214,7 +283,7 @@ public class FlociUiManager {
}
RuntimeProbe probe = probeRuntime();
if (!probe.ready() && shouldReArm(lifecycleManager.presenceOf(containerId))) {
- LOG.infov("floci-ui sidecar {0} is gone — starting it again so the dashboard "
+ LOG.infov("The web console sidecar {0} is gone, starting it again so the console "
+ "recovers without Floci being restarted", containerId);
this.started = false;
// ensureStartedAsync() only submits on kicked's false->true edge, but a prior
@@ -237,26 +306,85 @@ public class FlociUiManager {
return;
}
if (config.services().ui().keepRunningOnShutdown()) {
- LOG.infov("Leaving floci-ui sidecar {0} running for next start-up", containerId);
+ LOG.infov("Leaving the web console sidecar {0} running for next start-up", containerId);
return;
}
lifecycleManager.stopAndRemove(containerId, logStream);
}
- List<String> injectedEnv() {
- List<String> env = new ArrayList<>();
- env.add(FLOCI_ENDPOINT_ENV + "=" + resolveFlociEndpoint());
+ /**
+ * The console contract's side of the bargain: what Floci hands every console it starts.
+ *
+ * <p>The AWS baseline is the same one Lambda, ECS and CodeBuild containers get, so a console
+ * built on any AWS SDK is configured by its ordinary credential and endpoint discovery, with no
+ * Floci-specific code. On top of it the console is told its listen port, which emulator it is
+ * talking to, and, only for a console that reads neither of the baseline endpoint names, the
+ * endpoint once more under a name of its own.
+ *
+ * <p>Ordered so the rendered list is stable, and keyed so a configured extra replaces the
+ * injected default rather than being appended as a second entry for the same variable, which
+ * runtimes resolve inconsistently.
+ */
+ List<String> injectedEnv(ConsoleProfile console) {
+ String endpoint = resolveFlociEndpoint();
+
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+ for (String entry : awsEnv.sdkBaselineEnv(regionResolver.getDefaultRegion(), Optional.empty(),
+ endpoint, Optional.of(PLACEHOLDER_CREDENTIALS))) {
+ int split = entry.indexOf('=');
+ env.put(entry.substring(0, split), entry.substring(split + 1));
+ }
+ if (console.hasEndpointAlias() && !env.containsKey(console.endpointEnv())) {
+ env.put(console.endpointEnv(), endpoint);
+ }
+ env.put(PORT_ENV, String.valueOf(console.internalPort()));
+ env.put("FLOCI_CLOUD", FLOCI_CLOUD);
if (config.services().ui().insecureSkipTlsVerify()) {
- LOG.warn("floci.services.ui.insecure-skip-tls-verify=true — the Floci UI sidecar will "
+ LOG.warn("floci.services.ui.insecure-skip-tls-verify=true: the web console 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.put("FLOCI_TLS_SKIP_VERIFY", "1");
+ // The same instruction in the form a Node or Bun console's HTTP client already honours.
+ env.put("NODE_TLS_REJECT_UNAUTHORIZED", "0");
+ }
+ applyExtraEnv(env, config.services().ui().extraEnv());
+
+ List<String> rendered = new ArrayList<>(env.size());
+ env.forEach((key, value) -> rendered.add(key + "=" + value));
+ return rendered;
+ }
+
+ /**
+ * Merges operator-supplied {@code KEY=VALUE} entries over the injected defaults.
+ *
+ * <p>An entry without {@code =}, or with a blank key, is dropped with a warning rather than
+ * failing the start: a typo in one extra variable should not cost the whole console, and the
+ * warning is what tells the operator which entry was ignored. A value may itself contain
+ * {@code =} (a URL query, a base64 pad), so only the first one splits.
+ */
+ static void applyExtraEnv(LinkedHashMap<String, String> env, Optional<List<String>> extra) {
+ if (extra.isEmpty()) {
+ return;
+ }
+ for (String entry : extra.get()) {
+ if (entry == null || entry.isBlank()) {
+ continue;
+ }
+ int split = entry.indexOf('=');
+ String key = split < 0 ? "" : entry.substring(0, split).trim();
+ if (key.isEmpty()) {
+ LOG.warnv("Ignoring floci.services.ui.extra-env entry \"{0}\": expected KEY=VALUE.", entry);
+ continue;
+ }
+ String supportedKey = RESERVED_EXTRA_ENV.get(key);
+ if (supportedKey != null) {
+ LOG.warnv("Ignoring floci.services.ui.extra-env entry \"{0}\": {1} is set from the "
+ + "console profile and is used by the port binding, the readiness probe "
+ + "and adoption. Set {2} instead.", entry, key, supportedKey);
+ continue;
+ }
+ env.put(key, entry.substring(split + 1));
}
- 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;
}
/**
@@ -401,21 +529,24 @@ public class FlociUiManager {
}
/**
- * True when an adoption candidate's baked-in {@code FLOCI_ENDPOINT} no longer matches the
+ * True when an adoption candidate's baked-in endpoint variable 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.
+ * unknown is not the same as correct, and adopting it would strand the console just as badly.
+ * That is also what recreates, exactly once, a sidecar left by a Floci old enough to have
+ * injected only {@code FLOCI_ENDPOINT}.
*/
static boolean endpointDrifted(List<String> existingEnv, String expected) {
if (existingEnv == null) {
return true;
}
+ String prefix = CANONICAL_ENDPOINT_ENV + "=";
return existingEnv.stream()
- .filter(entry -> entry.startsWith(FLOCI_ENDPOINT_ENV + "="))
- .map(entry -> entry.substring(FLOCI_ENDPOINT_ENV.length() + 1))
+ .filter(entry -> entry.startsWith(prefix))
+ .map(entry -> entry.substring(prefix.length()))
.findFirst()
.map(current -> !current.equals(expected))
.orElse(true);
@@ -454,11 +585,12 @@ public class FlociUiManager {
* container (where the published host port is not reachable from inside).
* Falls back to {@code localhost:hostPort} if the endpoint is unavailable.
*/
- String resolveProbeUrl(EndpointInfo endpoint, int fallbackHostPort) {
+ String resolveProbeUrl(ConsoleProfile console, EndpointInfo endpoint, int fallbackHostPort) {
+ String path = console.healthPath();
if (endpoint != null) {
- return "http://" + endpoint.host() + ":" + endpoint.port() + RUNTIME_STATUS_PATH;
+ return "http://" + endpoint.host() + ":" + endpoint.port() + path;
}
- return "http://localhost:" + fallbackHostPort + RUNTIME_STATUS_PATH;
+ return "http://localhost:" + fallbackHostPort + path;
}
private record RuntimeProbe(boolean ready, String error) {
@@ -479,20 +611,26 @@ public class FlociUiManager {
if (code != HttpURLConnection.HTTP_OK) {
return new RuntimeProbe(false, null);
}
- JsonNode status;
+ ConsoleProfile console = this.profile;
+ if (!console.hasReadyField()) {
+ // A console whose health endpoint is a plain liveness check has nothing more to
+ // say than 200: reading a field that is not there would report it as never ready.
+ return new RuntimeProbe(true, null);
+ }
+ JsonNode health;
try (var input = conn.getInputStream()) {
- status = objectMapper.readTree(input);
+ health = objectMapper.readTree(input);
}
- String runtime = status.path("runtime").asText("");
- if ("reachable".equalsIgnoreCase(runtime)) {
+ String reported = health.path(console.healthReadyField()).asText("");
+ if (console.healthReadyValue().equalsIgnoreCase(reported)) {
return new RuntimeProbe(true, null);
}
- if ("unavailable".equalsIgnoreCase(runtime)) {
- return new RuntimeProbe(false, runtimeUnavailableMessage(status));
+ if (console.healthUnavailableValue().equalsIgnoreCase(reported)) {
+ return new RuntimeProbe(false, unavailableMessage(console, health));
}
return new RuntimeProbe(false, null);
} catch (Exception e) {
- LOG.debugv(e, "Failed to probe floci-ui runtime at {0}", url);
+ LOG.debugv(e, "Failed to probe the web console health endpoint at {0}", url);
return new RuntimeProbe(false, null);
} finally {
if (conn != null) {
@@ -501,6 +639,38 @@ public class FlociUiManager {
}
}
+ /**
+ * Whether an adoption candidate must be recreated because it is not running.
+ *
+ * <p>Adopting an exited container leaves {@link #status()} in a loop: the probe fails, the
+ * container reads as gone, the re-arm calls back into here, and the same dead container is
+ * adopted again on every poll with nothing ever starting it. Recreating is the only exit, and
+ * it is also the right answer: a console that exited did so for a reason its next start will
+ * either clear or report.
+ *
+ * <p>Presence the runtime could not report is left alone, the same judgement
+ * {@link #shouldReArm} makes: acting on an unknown is how a transient hiccup destroys a
+ * healthy sidecar.
+ */
+ static boolean mustRecreate(ContainerPresence presence) {
+ return presence == ContainerPresence.STOPPED || presence == ContainerPresence.ABSENT;
+ }
+
+ private boolean replaceIfNotRunning(Container existing) {
+ if (!mustRecreate(lifecycleManager.presenceOf(existing.getId()))) {
+ return false;
+ }
+ LOG.infov("Existing web console sidecar {0} is not running, recreating it rather than "
+ + "adopting a container that would never answer", existing.getId());
+ try {
+ lifecycleManager.stopAndRemove(existing.getId(), null);
+ } catch (Exception e) {
+ LOG.warnv("Could not remove the stopped web console sidecar {0}: {1}",
+ existing.getId(), e.getMessage());
+ }
+ return true;
+ }
+
/**
* Removes an existing sidecar whose baked-in endpoint no longer addresses this Floci, so the
* caller recreates it instead of adopting it.
@@ -525,23 +695,29 @@ public class FlociUiManager {
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",
+ LOG.infov("Existing web console sidecar {0} points at a stale Floci endpoint (expected {1}) "
+ + "recreating it so the console 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}",
+ LOG.warnv("Could not remove the stale web console sidecar {0}, adopting it instead: {1}",
existing.getId(), e.getMessage());
return false;
}
}
- private static String runtimeUnavailableMessage(JsonNode status) {
- String endpoint = status.path("endpoint").asText("");
- String error = status.path("error").asText("");
- StringBuilder message = new StringBuilder("The Floci UI cannot reach Floci");
+ /**
+ * Turns a console's own "I cannot reach Floci" report into the message the interstitial shows.
+ * The contract asks for {@code endpoint} and {@code error} alongside the status; both are
+ * optional, and a console that omits them still gets a usable sentence.
+ */
+ private static String unavailableMessage(ConsoleProfile console, JsonNode health) {
+ String endpoint = health.path("endpoint").asText("");
+ String error = health.path("error").asText("");
+ StringBuilder message = new StringBuilder(capitalize(console.displayName()))
+ .append(" cannot reach Floci");
if (!endpoint.isBlank()) {
message.append(" at ").append(endpoint);
}
@@ -551,20 +727,28 @@ public class FlociUiManager {
return message.append('.').toString();
}
+ private static String capitalize(String text) {
+ if (text == null || text.isEmpty()) {
+ return "The web console";
+ }
+ return Character.toUpperCase(text.charAt(0)) + text.substring(1);
+ }
+
private void adoptExisting(Container existing) {
this.containerId = existing.getId();
try {
- ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT));
- EndpointInfo endpoint = info.getEndpoint(CONTAINER_INTERNAL_PORT);
+ int internalPort = profile.internalPort();
+ ContainerInfo info = lifecycleManager.adopt(containerId, List.of(internalPort));
+ EndpointInfo endpoint = info.getEndpoint(internalPort);
this.hostPort = resolveHostPort(endpoint, config.services().ui().port());
- this.probeUrl = resolveProbeUrl(endpoint, hostPort);
+ this.probeUrl = resolveProbeUrl(profile, endpoint, hostPort);
this.started = true;
this.lastError = null;
- LOG.infov("Adopted existing floci-ui sidecar {0} on host port {1}",
+ LOG.infov("Adopted existing web console 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());
+ LOG.warnv("Failed to adopt the existing web console sidecar: {0}", e.getMessage());
this.containerId = null;
}
}
@@ -588,7 +772,7 @@ public class FlociUiManager {
try {
previous.close();
} catch (Exception e) {
- LOG.debugv("Could not close the previous floci-ui log stream: {0}", e.getMessage());
+ LOG.debugv("Could not close the previous web console log stream: {0}", e.getMessage());
}
}
@@ -605,16 +789,18 @@ public class FlociUiManager {
static String describeStartFailure(String image, Throwable e) {
String detail = messageOf(e);
if (isImageUnavailable(e)) {
- return "Could not start the Floci UI: image '" + image + "' is unavailable (" + detail
- + "). Pull it with 'docker pull " + image + "', or build it from the floci-ui repo.";
+ return "Could not start the Floci web console: image '" + image + "' is unavailable ("
+ + detail + "). Pull it with 'docker pull " + image
+ + "', or build it from the console's repository.";
}
if (isRuntimeUnreachable(e)) {
- return "Could not start the Floci UI: Floci could not reach the container runtime (" + detail
+ return "Could not start the Floci web console: Floci could not reach the container runtime ("
+ + detail
+ "). Check that the Docker/Podman socket is mounted into the Floci container and "
+ "accessible — on SELinux hosts the socket bind-mount may need relabeling "
+ "(e.g. ':z') or '--security-opt label=disable'.";
}
- return "Could not start the Floci UI from image '" + image + "': " + detail + ".";
+ return "Could not start the Floci web console from image '" + image + "': " + detail + ".";
}
/** True when the failure chain indicates the image itself is missing locally and in the registry. */
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 5b3c1b3389..37f65fe4c4 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -536,6 +536,18 @@ floci:
# 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
+ # The console-contract keys below are deliberately unset. Floci reads the console's own
+ # io.floci.console.* image labels first, then a built-in profile, then the contract defaults
+ # (/api/health, port 4500, status: ok). Setting a value here overrides all of that, so only
+ # do it for a console that describes itself neither way. See docs/ui/console-contract.md.
+ # internal-port: 4500
+ # endpoint-env: AWS_ENDPOINT_URL
+ # status-path: /api/health
+ # status-ready-field: status # "none" means any 200 counts as ready
+ # status-ready-value: ok
+ # status-unavailable-value: unavailable
+ # extra-env: # PORT and AWS_ENDPOINT_URL are ignored here: use
+ # - MY_CONSOLE_FLAG=true # internal-port and endpoint above instead
bedrock:
enabled: true
bedrock-runtime:
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerImageLabelsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerImageLabelsTest.java
new file mode 100644
index 0000000000..db9d655ffc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerImageLabelsTest.java
@@ -0,0 +1,98 @@
+package io.github.hectorvent.floci.core.common.docker;
+
+import java.util.Map;
+import java.util.Optional;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.InspectImageCmd;
+import com.github.dockerjava.api.command.InspectImageResponse;
+import com.github.dockerjava.api.exception.NotFoundException;
+import com.github.dockerjava.api.model.ContainerConfig;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * An image's labels are advisory metadata: the web console reads them to learn the console's shape.
+ * A failure to read them must therefore never break the start they were being read for.
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class ContainerLifecycleManagerImageLabelsTest {
+
+ @Mock
+ DockerClient dockerClient;
+
+ @Mock
+ ImageCacheService imageCacheService;
+
+ @Mock
+ ContainerDetector containerDetector;
+
+ @Mock
+ PortAllocator portAllocator;
+
+ @Mock
+ EmulatorConfig config;
+
+ private ContainerLifecycleManager manager() {
+ return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector,
+ portAllocator, config);
+ }
+
+ private void imageInspectReturns(Map<String, String> labels) {
+ ContainerConfig containerConfig = new ContainerConfig().withLabels(labels);
+ InspectImageResponse response = mock(InspectImageResponse.class);
+ when(response.getConfig()).thenReturn(containerConfig);
+ InspectImageCmd cmd = mock(InspectImageCmd.class);
+ when(cmd.exec()).thenReturn(response);
+ when(dockerClient.inspectImageCmd("acme/console:1")).thenReturn(cmd);
+ }
+
+ @Test
+ void labelsAreReadFromTheImageThePullResolvedTo() {
+ when(imageCacheService.ensureImageExists("acme/console")).thenReturn("acme/console:1");
+ imageInspectReturns(Map.of("io.floci.console.contract", "1"));
+
+ assertEquals(Optional.of(Map.of("io.floci.console.contract", "1")),
+ manager().imageLabels("acme/console"));
+ }
+
+ @Test
+ void anImageWithNoLabelsReadsAsEmptyRatherThanAsUnreadable() {
+ // "This image declares nothing" and "I could not ask" are different answers: only the
+ // second should send the caller looking for another source.
+ when(imageCacheService.ensureImageExists("acme/console")).thenReturn("acme/console:1");
+ imageInspectReturns(null);
+
+ assertEquals(Optional.of(Map.of()), manager().imageLabels("acme/console"));
+ }
+
+ @Test
+ void anUnavailableImageReportsUnreadableLabelsRatherThanThrowing() {
+ when(imageCacheService.ensureImageExists("acme/console"))
+ .thenThrow(new NotFoundException("no such image"));
+
+ assertTrue(manager().imageLabels("acme/console").isEmpty(),
+ "a failed pull must leave the caller to its own defaults, not fail the start");
+ }
+
+ @Test
+ void anUnreachableRuntimeReportsUnreadableLabelsRatherThanThrowing() {
+ when(imageCacheService.ensureImageExists("acme/console")).thenReturn("acme/console:1");
+ when(dockerClient.inspectImageCmd("acme/console:1"))
+ .thenThrow(new RuntimeException("Cannot connect to the Docker daemon"));
+
+ assertTrue(manager().imageLabels("acme/console").isEmpty());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolverTest.java
new file mode 100644
index 0000000000..fe3bbc97e0
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/floci/ui/ConsoleProfileResolverTest.java
@@ -0,0 +1,206 @@
+package io.github.hectorvent.floci.services.floci.ui;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ConsoleProfileResolverTest {
+
+ private final EmulatorConfig.UiServiceConfig ui = mock(EmulatorConfig.UiServiceConfig.class);
+
+ /** Nothing configured: the state an operator who only set an image is in. */
+ private void nothingConfigured() {
+ when(ui.internalPort()).thenReturn(OptionalInt.empty());
+ when(ui.endpointEnv()).thenReturn(Optional.empty());
+ when(ui.statusPath()).thenReturn(Optional.empty());
+ when(ui.statusReadyField()).thenReturn(Optional.empty());
+ when(ui.statusReadyValue()).thenReturn(Optional.empty());
+ when(ui.statusUnavailableValue()).thenReturn(Optional.empty());
+ }
+
+ private static Map<String, String> contractLabels(String... pairs) {
+ Map<String, String> labels = new HashMap<>();
+ labels.put(ConsoleProfileResolver.LABEL_CONTRACT, ConsoleProfileResolver.CONTRACT_VERSION);
+ for (int i = 0; i < pairs.length; i += 2) {
+ labels.put(ConsoleProfileResolver.LABEL_PREFIX + pairs[i], pairs[i + 1]);
+ }
+ return labels;
+ }
+
+ // --- layer 4: the contract itself ---
+
+ @Test
+ void aConsoleThatImplementsTheContractNeedsNoConfigurationAtAll() {
+ nothingConfigured();
+
+ ConsoleProfile profile = ConsoleProfileResolver.resolve("acme/console:1", Optional.empty(), ui);
+
+ assertEquals(4500, profile.internalPort());
+ assertEquals("/api/health", profile.healthPath());
+ assertEquals("status", profile.healthReadyField());
+ assertEquals("ok", profile.healthReadyValue());
+ assertEquals("unavailable", profile.healthUnavailableValue());
+ assertFalse(profile.hasEndpointAlias(),
+ "AWS_ENDPOINT_URL is in the baseline, so a contract console needs no alias");
+ }
+
+ // --- layer 3: a console Floci recognises by name ---
+
+ @Test
+ void flociUiKeepsItsOwnHealthShapeHoweverTheImageIsSpelled() {
+ for (String image : new String[]{
+ "floci-ui",
+ "floci/floci-ui",
+ "floci/floci-ui:latest",
+ "docker.io/floci/floci-ui:2.0.1",
+ "ghcr.io/floci-io/floci-ui@sha256:0123456789abcdef",
+ "registry.example.com:5000/mirror/floci/floci-ui:latest"}) {
+ ConsoleProfile profile = ConsoleProfileResolver.builtIn(image);
+
+ assertEquals("/api/clouds/aws/status", profile.healthPath(), image);
+ assertEquals("runtime", profile.healthReadyField(), image);
+ assertEquals("reachable", profile.healthReadyValue(), image);
+ }
+ }
+
+ @Test
+ void anImageThatMerelyLooksLikeFlociUiGetsTheContractDefaults() {
+ for (String image : new String[]{"floci/floci-uix:1", "acme/floci-ui-next", "floci/console"}) {
+ assertEquals("/api/health", ConsoleProfileResolver.builtIn(image).healthPath(), image);
+ }
+ }
+
+ // --- layer 2: the image describes itself ---
+
+ @Test
+ void labelsDescribeAConsoleFlociHasNeverHeardOf() {
+ nothingConfigured();
+ Map<String, String> labels = contractLabels(
+ "port", "8080",
+ "health-path", "healthz",
+ "health-ready-field", "state",
+ "health-ready-value", "up",
+ "health-unavailable-value", "down",
+ "endpoint-env", "CONSOLE_API_URL",
+ "name", "StackPort");
+
+ ConsoleProfile profile = ConsoleProfileResolver.resolve("acme/console:1", Optional.of(labels), ui);
+
+ assertEquals(8080, profile.internalPort());
+ assertEquals("/healthz", profile.healthPath(), "a label without a leading slash still forms a URL");
+ assertEquals("state", profile.healthReadyField());
+ assertEquals("up", profile.healthReadyValue());
+ assertEquals("down", profile.healthUnavailableValue());
+ assertEquals("CONSOLE_API_URL", profile.endpointEnv());
+ assertEquals("StackPort", profile.displayName());
+ }
+
+ @Test
+ void labelsForAContractVersionFlociDoesNotImplementAreIgnored() {
+ // Reading a future contract's labels under this one's meaning is worse than ignoring them:
+ // the console would be probed at a path that means something else.
+ Map<String, String> labels = new HashMap<>(contractLabels("health-path", "/v2/health"));
+ labels.put(ConsoleProfileResolver.LABEL_CONTRACT, "2");
+
+ ConsoleProfile profile = ConsoleProfileResolver.fromLabels(labels, ConsoleProfileResolver.contractV1());
+
+ assertEquals("/api/health", profile.healthPath());
+ }
+
+ @Test
+ void labelsWithoutTheOptInAreIgnored() {
+ Map<String, String> labels = Map.of(
+ ConsoleProfileResolver.LABEL_PREFIX + "health-path", "/v2/health");
+
+ assertEquals("/api/health",
+ ConsoleProfileResolver.fromLabels(labels, ConsoleProfileResolver.contractV1()).healthPath());
+ }
+
+ @Test
+ void anUnusablePortLabelIsIgnoredRatherThanBreakingTheStart() {
+ // A typo in one label should cost the label, not the console.
+ for (String port : new String[]{"eighty-eighty", "0", "70000", "8080 "}) {
+ ConsoleProfile profile = ConsoleProfileResolver.fromLabels(
+ contractLabels("port", port), ConsoleProfileResolver.contractV1());
+
+ assertEquals("8080 ".equals(port) ? 8080 : 4500, profile.internalPort(), port);
+ }
+ }
+
+ @Test
+ void aDeclaredButEmptyReadyFieldLabelMeansAnyTwoHundredIsReady() {
+ // The one label where "declared as empty" differs from "not declared": it is how a console
+ // with a plain liveness endpoint says it has no field worth reading.
+ ConsoleProfile profile = ConsoleProfileResolver.fromLabels(
+ contractLabels("health-ready-field", ""), ConsoleProfileResolver.contractV1());
+
+ assertFalse(profile.hasReadyField());
+ }
+
+ @Test
+ void labelsRefineTheBuiltInProfileTheyDoNotReplaceIt() {
+ // A floci-ui image that starts declaring only its health path keeps the rest of its profile.
+ ConsoleProfile profile = ConsoleProfileResolver.fromLabels(
+ contractLabels("health-path", "/api/health"),
+ ConsoleProfileResolver.builtIn("floci/floci-ui:latest"));
+
+ assertEquals("/api/health", profile.healthPath());
+ assertEquals("runtime", profile.healthReadyField());
+ }
+
+ // --- layer 1: explicit configuration ---
+
+ @Test
+ void configurationBeatsLabelsWhichBeatTheBuiltInProfile() {
+ nothingConfigured();
+ when(ui.statusPath()).thenReturn(Optional.of("/operator/health"));
+ Map<String, String> labels = contractLabels(
+ "health-path", "/label/health",
+ "health-ready-field", "state");
+
+ ConsoleProfile profile = ConsoleProfileResolver.resolve("floci/floci-ui:latest", Optional.of(labels), ui);
+
+ assertEquals("/operator/health", profile.healthPath(), "configuration wins");
+ assertEquals("state", profile.healthReadyField(), "an unconfigured field falls through to the label");
+ }
+
+ @Test
+ void configuringTheReadyFieldToNoneTurnsItOff() {
+ nothingConfigured();
+ when(ui.statusReadyField()).thenReturn(Optional.of("none"));
+
+ assertFalse(ConsoleProfileResolver.withOverrides(ui, ConsoleProfileResolver.contractV1())
+ .hasReadyField());
+ }
+
+ @Test
+ void anEmptyConfiguredValueIsTreatedAsUnsetRatherThanAsAnEmptyPath() {
+ // An environment variable set to nothing reaches SmallRye as an absent property; treating a
+ // blank the same way keeps the two spellings from meaning different things.
+ nothingConfigured();
+ when(ui.statusPath()).thenReturn(Optional.of(" "));
+
+ assertEquals("/api/clouds/aws/status",
+ ConsoleProfileResolver.resolve("floci/floci-ui:latest", Optional.empty(), ui).healthPath());
+ }
+
+ @Test
+ void unreadableLabelsFallThroughToTheProfileRatherThanFailing() {
+ nothingConfigured();
+
+ ConsoleProfile profile = ConsoleProfileResolver.resolve("floci/floci-ui:latest", Optional.empty(), ui);
+
+ assertEquals("/api/clouds/aws/status", profile.healthPath());
+ assertTrue(profile.hasReadyField());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
index 1c2a39d813..71cda8ce31 100644
--- a/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.iam.model.SessionCreds;
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;
@@ -12,7 +13,9 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.C
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.ContainerReachableEndpoint;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
+import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
@@ -22,9 +25,11 @@ import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.OptionalInt;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
@@ -33,6 +38,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -51,22 +58,37 @@ class FlociUiManagerTest {
private final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
private final EmulatorConfig.UiServiceConfig ui = mock(EmulatorConfig.UiServiceConfig.class);
- /** Wires config.services().ui() with the defaults every UI test starts from. */
+ /** The profile floci-ui resolves to, which most of these tests exercise. */
+ private static final ConsoleProfile FLOCI_UI = ConsoleProfileResolver.builtIn("floci/floci-ui:latest");
+
+ /** Wires config.services().ui() with the defaults every console 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);
+ when(ui.internalPort()).thenReturn(OptionalInt.empty());
+ when(ui.endpointEnv()).thenReturn(Optional.empty());
+ when(ui.extraEnv()).thenReturn(Optional.empty());
+ when(ui.statusPath()).thenReturn(Optional.empty());
+ when(ui.statusReadyField()).thenReturn(Optional.empty());
+ when(ui.statusReadyValue()).thenReturn(Optional.empty());
+ when(ui.statusUnavailableValue()).thenReturn(Optional.empty());
}
private FlociUiManager newManager() {
+ return newManager(mock(ContainerBuilder.class));
+ }
+
+ private FlociUiManager newManager(ContainerBuilder containerBuilder) {
return new FlociUiManager(
- mock(ContainerBuilder.class),
+ containerBuilder,
lifecycleManager,
logStreamer,
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
+ new LaunchedContainerAwsEnv(mock(ContainerReachableEndpoint.class)),
config,
regionResolver,
new ObjectMapper());
@@ -172,24 +194,27 @@ class FlociUiManagerTest {
void probeUsesSidecarContainerIpWhenContainerized() {
// In a container the published host port is not reachable via localhost; the
// probe must target the sidecar's container IP on the shared Docker network.
+ withUiConfig();
EndpointInfo endpoint = new EndpointInfo("10.88.0.20", 4500);
assertEquals("http://10.88.0.20:4500/api/clouds/aws/status",
- newManager().resolveProbeUrl(endpoint, 4500));
+ newManager().resolveProbeUrl(FLOCI_UI, endpoint, 4500));
}
@Test
void probeUsesLocalhostHostPortNatively() {
+ withUiConfig();
EndpointInfo endpoint = new EndpointInfo("localhost", 4500);
assertEquals("http://localhost:4500/api/clouds/aws/status",
- newManager().resolveProbeUrl(endpoint, 4500));
+ newManager().resolveProbeUrl(FLOCI_UI, endpoint, 4500));
}
@Test
void probeFallsBackToLocalhostWhenEndpointMissing() {
+ withUiConfig();
assertEquals("http://localhost:4500/api/clouds/aws/status",
- newManager().resolveProbeUrl(null, 4500));
+ newManager().resolveProbeUrl(FLOCI_UI, null, 4500));
}
@Test
@@ -324,8 +349,8 @@ class FlociUiManagerTest {
@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");
+ // AWS_ENDPOINT_URL was baked in at create time against the previous container IP.
+ List<String> staleEnv = List.of("PORT=4500", "AWS_ENDPOINT_URL=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");
@@ -333,7 +358,7 @@ class FlociUiManagerTest {
@Test
void noEndpointDriftWhenAdoptedContainerAlreadyMatches() {
- List<String> env = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.3.252:4566");
+ List<String> env = List.of("PORT=4500", "AWS_ENDPOINT_URL=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");
@@ -341,7 +366,7 @@ class FlociUiManagerTest {
@Test
void endpointDriftDetectedWhenAdoptedContainerHasNoEndpointAtAll() {
- // Missing is not "fine" — it is unknown, and adopting it would strand the UI.
+ // Missing is not "fine": it is unknown, and adopting it would strand the console.
assertTrue(FlociUiManager.endpointDrifted(List.of("PORT=4500"), "http://10.88.3.252:4566"));
assertTrue(FlociUiManager.endpointDrifted(null, "http://10.88.3.252:4566"));
}
@@ -349,7 +374,7 @@ class FlociUiManagerTest {
@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");
+ List<String> env = List.of("AWS_ENDPOINT_URL=http://10.88.3.252:4566");
assertTrue(FlociUiManager.endpointDrifted(env, "https://10.88.3.252:4566"));
}
@@ -363,14 +388,14 @@ class FlociUiManagerTest {
@Test
void readableEnvironmentStillReplacesOnDrift() {
- Optional<List<String>> env = Optional.of(List.of("FLOCI_ENDPOINT=http://10.88.4.98:4566"));
+ Optional<List<String>> env = Optional.of(List.of("AWS_ENDPOINT_URL=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"));
+ Optional<List<String>> env = Optional.of(List.of("AWS_ENDPOINT_URL=http://10.88.3.252:4566"));
assertFalse(FlociUiManager.shouldReplace(env, "http://10.88.3.252:4566"));
}
@@ -447,7 +472,8 @@ class FlociUiManagerTest {
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
- assertTrue(newManager().injectedEnv().contains("NODE_TLS_REJECT_UNAUTHORIZED=0"));
+ assertTrue(newManager().injectedEnv(ConsoleProfileResolver.contractV1())
+ .contains("NODE_TLS_REJECT_UNAUTHORIZED=0"));
}
@Test
@@ -460,7 +486,7 @@ class FlociUiManagerTest {
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
- List<String> env = newManager().injectedEnv();
+ List<String> env = newManager().injectedEnv(ConsoleProfileResolver.contractV1());
assertFalse(env.stream().anyMatch(v -> v.startsWith("NODE_TLS_REJECT_UNAUTHORIZED")),
"TLS verification must stay on unless explicitly opted out, was: " + env);
}
@@ -486,7 +512,9 @@ class FlociUiManagerTest {
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);
+ // Running when it is first adopted, gone by the time status() checks on it.
+ when(lifecycleManager.presenceOf("abc123"))
+ .thenReturn(ContainerPresence.RUNNING, ContainerPresence.ABSENT);
FlociUiManager manager = new FlociUiManager(
mock(ContainerBuilder.class),
@@ -495,6 +523,7 @@ class FlociUiManagerTest {
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
+ new LaunchedContainerAwsEnv(mock(ContainerReachableEndpoint.class)),
config,
regionResolver,
new ObjectMapper());
@@ -504,11 +533,25 @@ class FlociUiManagerTest {
.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.
+ // status() must trigger a second async restart. That restart no longer re-adopts the dead
+ // container, so the kick is observed by the start running a second time at all.
manager.status();
await().atMost(2, TimeUnit.SECONDS)
- .untilAsserted(() -> verify(lifecycleManager, times(2)).adopt("abc123", List.of(4500)));
+ .untilAsserted(() -> verify(lifecycleManager, times(2)).findByName("floci-ui"));
+ }
+
+ @Test
+ void aStoppedSidecarIsRecreatedRatherThanAdoptedForever() {
+ // Adopting an exited container is a loop: the probe fails, the container reads as gone,
+ // the re-arm comes back here, and the same dead container is adopted again on every poll
+ // with nothing ever starting it.
+ assertTrue(FlociUiManager.mustRecreate(ContainerPresence.STOPPED));
+ assertTrue(FlociUiManager.mustRecreate(ContainerPresence.ABSENT));
+ assertFalse(FlociUiManager.mustRecreate(ContainerPresence.RUNNING),
+ "a running sidecar must still be adopted, not churned");
+ assertFalse(FlociUiManager.mustRecreate(ContainerPresence.UNKNOWN),
+ "acting on an unknown is how a transient runtime hiccup destroys a healthy sidecar");
}
// --- a start that fails before the try block must not vanish silently ---
@@ -534,6 +577,7 @@ class FlociUiManagerTest {
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
+ new LaunchedContainerAwsEnv(mock(ContainerReachableEndpoint.class)),
config,
regionResolver,
new ObjectMapper());
@@ -587,6 +631,7 @@ class FlociUiManagerTest {
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
+ new LaunchedContainerAwsEnv(mock(ContainerReachableEndpoint.class)),
config,
regionResolver,
new ObjectMapper());
@@ -599,31 +644,313 @@ class FlociUiManagerTest {
+ manager.status().error());
}
+ @Test
+ void healthPathFollowsTheProfileSoAThirdPartyConsoleCanBeProbed() {
+ // A console other than floci-ui answers the contract's /api/health, which floci-ui's
+ // own /api/clouds/aws/status route would miss entirely.
+ withUiConfig();
+
+ assertEquals("http://10.88.0.20:8080/api/health",
+ newManager().resolveProbeUrl(ConsoleProfileResolver.contractV1(),
+ new EndpointInfo("10.88.0.20", 8080), 8080));
+ }
+
+ @Test
+ void statusPathWithoutALeadingSlashStillFormsAUrl() {
+ withUiConfig();
+ when(ui.statusPath()).thenReturn(Optional.of("api/health"));
+
+ ConsoleProfile profile = ConsoleProfileResolver.withOverrides(ui, ConsoleProfileResolver.contractV1());
+
+ assertEquals("http://localhost:8080/api/health",
+ newManager().resolveProbeUrl(profile, null, 8080));
+ }
+
+ @Test
+ void everyConsoleGetsTheStandardAwsEnvironmentAndItsListenPort() {
+ // The contract's side of the bargain: an SDK-based console is configured entirely by its
+ // ordinary endpoint and credential discovery, with no Floci-specific code.
+ withUiConfig();
+ when(containerDetector.isRunningInContainer()).thenReturn(true);
+ when(config.hostname()).thenReturn(Optional.of("floci"));
+ when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ List<String> env = newManager().injectedEnv(ConsoleProfileResolver.contractV1());
+
+ assertTrue(env.contains("AWS_ENDPOINT_URL=http://floci:4566"), env.toString());
+ assertTrue(env.contains("FLOCI_ENDPOINT=http://floci:4566"), env.toString());
+ assertTrue(env.contains("FLOCI_HOSTNAME=floci"), env.toString());
+ assertTrue(env.contains("AWS_REGION=us-east-1"), env.toString());
+ assertTrue(env.contains("AWS_DEFAULT_REGION=us-east-1"), env.toString());
+ assertTrue(env.contains("FLOCI_CLOUD=aws"), env.toString());
+ assertTrue(env.contains("PORT=4500"), env.toString());
+ }
+
+ @Test
+ void theConsoleIsNeverHandedFlocisOwnAwsCredentials() {
+ // The baseline forwards Floci's ambient credentials when none are supplied, which is
+ // acceptable for a workload the user wrote and not for a third-party console image. So
+ // placeholders must be passed explicitly rather than left to that fallback.
+ withUiConfig();
+ when(containerDetector.isRunningInContainer()).thenReturn(true);
+ when(config.hostname()).thenReturn(Optional.of("floci"));
+ when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
+ when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any()))
+ .thenReturn(List.of("AWS_ACCESS_KEY_ID=test"));
+ FlociUiManager manager = new FlociUiManager(
+ mock(ContainerBuilder.class), lifecycleManager, logStreamer, containerDetector,
+ mock(CurrentContainerNetworkResolver.class), dockerHostResolver,
+ awsEnv, config, regionResolver, new ObjectMapper());
+
+ List<String> env = manager.injectedEnv(ConsoleProfileResolver.contractV1());
+
+ assertTrue(env.contains("AWS_ACCESS_KEY_ID=test"), env.toString());
+ verify(awsEnv).sdkBaselineEnv("us-east-1", Optional.empty(), "http://floci:4566",
+ Optional.of(new SessionCreds("test", "test", "test")));
+ }
+
+ @Test
+ void aConsoleReadingItsOwnEndpointVariableGetsTheEndpointUnderThatNameToo() {
+ withUiConfig();
+ when(containerDetector.isRunningInContainer()).thenReturn(true);
+ when(config.hostname()).thenReturn(Optional.of("floci"));
+ when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ ConsoleProfile profile = new ConsoleProfile(8080, "CONSOLE_API_URL", "/api/health",
+ "status", "ok", "unavailable", "the console");
+
+ List<String> env = newManager().injectedEnv(profile);
+
+ assertTrue(env.contains("CONSOLE_API_URL=http://floci:4566"), env.toString());
+ assertTrue(env.contains("AWS_ENDPOINT_URL=http://floci:4566"), env.toString());
+ assertTrue(env.contains("PORT=8080"), env.toString());
+ }
+
+ @Test
+ void skippingTlsVerificationIsAnnouncedInBothTheContractAndTheNodeForm() {
+ withUiConfig();
+ when(ui.insecureSkipTlsVerify()).thenReturn(true);
+ when(containerDetector.isRunningInContainer()).thenReturn(true);
+ when(config.hostname()).thenReturn(Optional.of("floci"));
+ when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ List<String> env = newManager().injectedEnv(ConsoleProfileResolver.contractV1());
+
+ assertTrue(env.contains("FLOCI_TLS_SKIP_VERIFY=1"), env.toString());
+ assertTrue(env.contains("NODE_TLS_REJECT_UNAUTHORIZED=0"), env.toString());
+ }
+
+ @Test
+ void extraEnvIsAppliedAndReplacesAnInjectedDefaultRatherThanDuplicatingIt() {
+ withUiConfig();
+ when(ui.extraEnv()).thenReturn(Optional.of(List.of(
+ "STACKPORT_ALLOW_WRITES=false",
+ "AWS_ACCESS_KEY_ID=custom")));
+ when(containerDetector.isRunningInContainer()).thenReturn(false);
+ when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
+ when(config.tls()).thenReturn(tls);
+ when(tls.enabled()).thenReturn(false);
+ when(config.port()).thenReturn(4566);
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ List<String> env = newManager().injectedEnv(ConsoleProfileResolver.contractV1());
+
+ assertTrue(env.contains("STACKPORT_ALLOW_WRITES=false"), env.toString());
+ assertTrue(env.contains("AWS_ACCESS_KEY_ID=custom"), env.toString());
+ assertEquals(1, env.stream().filter(entry -> entry.startsWith("AWS_ACCESS_KEY_ID=")).count(),
+ "an overridden variable must appear once, not twice: " + env);
+ }
+
+ @Test
+ void extraEnvCannotOverrideThePortThePortBindingAndProbeAreBuiltFrom() {
+ // PORT is structural: withPortBinding() and the readiness probe both read
+ // profile.internalPort(). Honouring an override here would leave the console listening on
+ // 8080 while Floci published and polled 4500, so the sidecar never becomes reachable.
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+ env.put(FlociUiManager.PORT_ENV, "4500");
+
+ FlociUiManager.applyExtraEnv(env, Optional.of(List.of("PORT=8080")));
+
+ assertEquals("4500", env.get(FlociUiManager.PORT_ENV),
+ "extra-env must not move the port the binding and probe were built from");
+ }
+
+ @Test
+ void extraEnvCannotOverrideTheEndpointAdoptionComparesAgainst() {
+ // AWS_ENDPOINT_URL is what endpointDrifted() compares to spot a sidecar left addressing a
+ // previous Floci. An override here reads as permanent drift, so the container would be
+ // recreated on every check.
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+ env.put(FlociUiManager.CANONICAL_ENDPOINT_ENV, "http://floci:4566");
+
+ FlociUiManager.applyExtraEnv(env, Optional.of(List.of("AWS_ENDPOINT_URL=http://elsewhere:9999")));
+
+ assertEquals("http://floci:4566", env.get(FlociUiManager.CANONICAL_ENDPOINT_ENV),
+ "extra-env must not move the endpoint adoption compares against");
+ }
+
+ @Test
+ void reservingTheStructuralKeysDoesNotBlockTheEntriesBesideThem() {
+ // The guard is two keys, not a general refusal: everything else still applies.
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+ env.put(FlociUiManager.PORT_ENV, "4500");
+
+ FlociUiManager.applyExtraEnv(env, Optional.of(List.of(
+ "PORT=8080",
+ "MY_CONSOLE_FLAG=true")));
+
+ assertEquals("4500", env.get(FlociUiManager.PORT_ENV));
+ assertEquals("true", env.get("MY_CONSOLE_FLAG"));
+ }
+
+ @Test
+ void extraEnvKeepsEveryEqualsSignAfterTheFirstInTheValue() {
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+
+ FlociUiManager.applyExtraEnv(env, Optional.of(List.of("TOKEN=a=b==c")));
+
+ assertEquals("a=b==c", env.get("TOKEN"));
+ }
+
+ @Test
+ void malformedExtraEnvEntryIsDroppedRatherThanFailingTheStart() {
+ LinkedHashMap<String, String> env = new LinkedHashMap<>();
+ env.put("PORT", "4500");
+
+ FlociUiManager.applyExtraEnv(env, Optional.of(java.util.Arrays.asList(
+ "NOT_A_PAIR", "=orphan", " ", null, "GOOD=yes")));
+
+ assertEquals(Map.of("PORT", "4500", "GOOD", "yes"), env);
+ }
+
+ @Test
+ void readinessFollowsTheConfiguredFieldAndValue() throws Exception {
+ HttpServer server = startStatusServer("/api/health", """
+ {"status":"ok","endpoint_url":"http://floci:4566"}
+ """);
+ try {
+ FlociUiManager manager = adoptSidecar(
+ server.getAddress().getPort(), "/api/health", "status", "ok");
+
+ assertTrue(manager.status().ready());
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void aReadyFieldOfNoneTreatsAnyTwoHundredAsReady() throws Exception {
+ // All a plain liveness endpoint can report. Reading a field that is not in the
+ // response would otherwise leave the console reported as never ready. The opt-out is
+ // the literal "none": an empty value arrives as an absent property and would silently
+ // mean "use the default field".
+ HttpServer server = startStatusServer("/healthz", "OK");
+ try {
+ FlociUiManager manager = adoptSidecar(
+ server.getAddress().getPort(), "/healthz", "none", "reachable");
+
+ assertTrue(manager.status().ready());
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void aConfiguredReadyFieldThatDoesNotMatchIsNotReady() throws Exception {
+ HttpServer server = startStatusServer("/api/health", """
+ {"status":"degraded"}
+ """);
+ try {
+ FlociUiManager manager = adoptSidecar(
+ server.getAddress().getPort(), "/api/health", "status", "ok");
+
+ assertFalse(manager.status().ready());
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ @Test
+ void driftIsDetectedAgainstTheCanonicalEndpointVariable() {
+ List<String> env = List.of("AWS_ENDPOINT_URL=http://10.88.3.251:4566", "PORT=8080");
+
+ assertTrue(FlociUiManager.endpointDrifted(env, "http://10.88.3.252:4566"));
+ assertFalse(FlociUiManager.endpointDrifted(env, "http://10.88.3.251:4566"),
+ "a sidecar already pointing at this Floci must be adopted, not recreated");
+ }
+
+ @Test
+ void aSidecarFromAFlociThatOnlySetFlociEndpointIsRecreatedOnce() {
+ // Before the console contract only FLOCI_ENDPOINT was injected. Such a container cannot be
+ // checked for drift, so it is recreated on the first start after the upgrade and adopted
+ // normally from then on.
+ List<String> env = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.3.252:4566");
+
+ assertTrue(FlociUiManager.endpointDrifted(env, "http://10.88.3.252:4566"),
+ "a pre-contract sidecar must be recreated so it gains the canonical variable");
+ }
+
+ /** Adopts a console that resolves to the built-in floci-ui profile. */
private FlociUiManager adoptSidecar(int port) {
+ return adoptSidecar(port, "floci/floci-ui:latest",
+ Optional.empty(), Optional.empty(), Optional.empty());
+ }
+
+ /** Adopts a console whose health shape is pinned by explicit configuration. */
+ private FlociUiManager adoptSidecar(int port, String statusPath, String readyField, String readyValue) {
+ return adoptSidecar(port, "acme/console:1", Optional.of(statusPath),
+ Optional.of(readyField), Optional.of(readyValue));
+ }
+
+ private FlociUiManager adoptSidecar(int port, String image, Optional<String> statusPath,
+ Optional<String> readyField, Optional<String> readyValue) {
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.UiServiceConfig ui = mock(EmulatorConfig.UiServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.ui()).thenReturn(ui);
when(ui.enabled()).thenReturn(true);
+ when(ui.image()).thenReturn(image);
when(ui.containerName()).thenReturn("floci-ui");
when(ui.port()).thenReturn(port);
+ when(ui.internalPort()).thenReturn(OptionalInt.empty());
+ when(ui.endpointEnv()).thenReturn(Optional.empty());
+ when(ui.extraEnv()).thenReturn(Optional.empty());
+ when(ui.statusPath()).thenReturn(statusPath);
+ when(ui.statusReadyField()).thenReturn(readyField);
+ when(ui.statusReadyValue()).thenReturn(readyValue);
+ when(ui.statusUnavailableValue()).thenReturn(Optional.empty());
when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
+ when(containerBuilder.resolveImage(image)).thenReturn(image);
+
Container existing = mock(Container.class);
when(existing.getId()).thenReturn("ui-container");
when(lifecycleManager.findByName("floci-ui")).thenReturn(Optional.of(existing));
+ when(lifecycleManager.containerEnv("ui-container"))
+ .thenReturn(Optional.of(List.of("AWS_ENDPOINT_URL=http://custom:4566")));
when(lifecycleManager.adopt("ui-container", List.of(4500))).thenReturn(
new ContainerInfo("ui-container", Map.of(4500, new EndpointInfo("127.0.0.1", port))));
- FlociUiManager manager = newManager();
+ FlociUiManager manager = newManager(containerBuilder);
manager.ensureStarted();
return manager;
}
private static HttpServer startRuntimeStatusServer(String response) throws IOException {
+ return startStatusServer("/api/clouds/aws/status", response);
+ }
+
+ private static HttpServer startStatusServer(String path, String response) throws IOException {
byte[] body = response.getBytes(StandardCharsets.UTF_8);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
- server.createContext("/api/clouds/aws/status", exchange -> {
+ server.createContext(path, exchange -> {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
try (var output = exchange.getResponseBody()) {