diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4ad9eca8..6d98af9d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -221,9 +221,9 @@ containers have no mount for that export. - Fleet updates use rolling replacement and an explicit rollback version. - Controller routing, capacity, lifecycle, and engine updates use reviewed full commits from private desired-state configuration; hosts never follow an unreviewed moving branch. -## Planned endpoint observation +## Endpoint observation -The [endpoint observation UI design](ENDPOINT-UI-DESIGN.md) defines a future optional host service on loopback port 80, authenticated through an independently provisioned HTTPS gateway. Its [acceptance record](ENDPOINT-UI-DESIGN.md#acceptance-record) distinguishes the proposal from a reviewed decision. It keeps observation independent of Docker and preserves role, credential, configuration, and outbound-reporting boundaries. No endpoint UI or inbound listener is implemented by that design. +The [endpoint observation UI design](ENDPOINT-UI-DESIGN.md) defines an optional host service on loopback port 80, authenticated through an independently provisioned HTTPS gateway. The [read-only worker views](WORKER-VIEWS.md) read protected exports independently of Docker. Host installation, listener activation, and gateway integration are tracked in #122. ## Project adoption diff --git a/docs/DESIGN-DECISIONS.md b/docs/DESIGN-DECISIONS.md index e931708d..a8aa8b5c 100644 --- a/docs/DESIGN-DECISIONS.md +++ b/docs/DESIGN-DECISIONS.md @@ -75,7 +75,7 @@ Stop the proxy and unmount the volume to remove the route. The disposable Docker proof covers the repository contract. Staging cutover requires separate acceptance on the intended dedicated rootless deployer. [Issue #194](https://github.com/RandomDevelopment/ci-fleet/issues/194) -The [endpoint observation UI ADR](ENDPOINT-UI-DESIGN.md) has an explicit [acceptance record](ENDPOINT-UI-DESIGN.md#acceptance-record) under [issue #117](https://github.com/RandomDevelopment/ci-fleet/issues/117). It is proposed while PR #126 is open and accepted after that reviewed PR merges into `main`. It records port-80 access, local data contracts, retention, outage behavior, and a conditional management-access exception to the outbound-only worker model. Implementation remains planned; it adds no runtime, schema field, or host activation and preserves the decisions below. +The [endpoint observation UI ADR](ENDPOINT-UI-DESIGN.md) was accepted when PR #126 merged. It records port-80 access, local data contracts, retention, outage behavior, and a conditional management-access exception to the outbound-only worker model. The [worker views](WORKER-VIEWS.md) consume the protected exports. The schema and host activation are tracked in #122. ## Managed controller desired state after the isolated proof diff --git a/docs/ENDPOINT-SNAPSHOTS.md b/docs/ENDPOINT-SNAPSHOTS.md index 6273fb6e..593d6cfc 100644 --- a/docs/ENDPOINT-SNAPSHOTS.md +++ b/docs/ENDPOINT-SNAPSHOTS.md @@ -1,6 +1,6 @@ # Worker snapshots -This is the read-only worker snapshot contract for [#118](https://github.com/RandomDevelopment/ci-fleet/issues/118) under the accepted [endpoint UI design](ENDPOINT-UI-DESIGN.md). The repository provides one privileged publication command and an authenticated file reader. Browser delivery remains in #121. Packaging, service activation, and live-host acceptance remain in #122. Bootstrap still uses its temporary authenticated callback. Reconciliation captures the desired engine only after existing validation and the opt-in independent configuration-approval check. +This is the read-only worker snapshot contract for [#118](https://github.com/RandomDevelopment/ci-fleet/issues/118) under the accepted [endpoint UI design](ENDPOINT-UI-DESIGN.md). The repository provides one privileged publication command and an authenticated file reader used by the [worker views](WORKER-VIEWS.md). Packaging, service activation, and live-host acceptance remain in #122. Bootstrap still uses its temporary authenticated callback. Reconciliation captures the desired engine only after existing validation and the opt-in independent configuration-approval check. ## Producer and consumer interfaces @@ -16,7 +16,7 @@ sudo python3 scripts/endpoint_snapshot.py \ This is a foundation interface, not an enrollment or installation procedure. Preparation, approved credentials, role admission, and service activation belong to #122. The command does not create directories, groups, units, credentials, or network rules. It prints only a controlled success/failure code and returns nonzero when publication fails. A future caller must isolate that failure from CI and reconciliation. -`SnapshotReader` accepts a fixed export base, observer GID, expected controller identity, and an already provisioned backend bearer. Its `read(headers)` method authenticates before any filesystem access and ignores forwarded identity headers. The caller must supply the bearer through the separately approved credential mechanism; it must never derive configuration from browser input or reuse controller credentials. This PR adds no credential loader or HTTP listener. The transport must enforce the ADR's request and response limits and `Cache-Control: no-store`. +`SnapshotReader` accepts a fixed export base, observer GID, expected controller identity, and an already provisioned backend bearer. Its `read(headers)` method authenticates before any filesystem access and ignores forwarded identity headers. The caller must supply the bearer through the separately approved credential mechanism. The worker HTTP application accepts a prepared loopback listener and applies the ADR's request and response limits and `Cache-Control: no-store`. ## Snapshot version 1 @@ -133,7 +133,9 @@ results and original observation times. The aggregate activity flag also accounts for retained coverage gaps and loss of nonterminal records. A directly observed running job can remain current while aggregate coverage is unknown. Missing summary evidence defaults -to unknown activity. The API accepts only the fixed job file. +to unknown activity. The authenticated read also returns the validated +publication fingerprint for pagination and the endpoint evidence used to +assess current activity. The API accepts only the fixed job file. ## Verification diff --git a/docs/ENDPOINT-UI-DESIGN.md b/docs/ENDPOINT-UI-DESIGN.md index 0f0a9851..3136fcef 100644 --- a/docs/ENDPOINT-UI-DESIGN.md +++ b/docs/ENDPOINT-UI-DESIGN.md @@ -1,8 +1,6 @@ # Endpoint observation UI -Implementation status: planned. This ADR addresses [issue #117](https://github.com/RandomDevelopment/ci-fleet/issues/117). It adds no supported command, schema field, service, listener, or engine capability. - -The [worker snapshot contract](ENDPOINT-SNAPSHOTS.md) records the current #118 interfaces and which producers can supply each observation. The UI and its host activation remain planned. +This ADR records the accepted design for [issue #117](https://github.com/RandomDevelopment/ci-fleet/issues/117). The [worker snapshot contract](ENDPOINT-SNAPSHOTS.md) records the producers and their evidence. The [worker views](WORKER-VIEWS.md) provide a repository HTTP application. Host activation and gateway integration remain in #122. ## Acceptance record diff --git a/docs/README.md b/docs/README.md index 109cf8e2..93ecef13 100644 --- a/docs/README.md +++ b/docs/README.md @@ -27,7 +27,7 @@ Operators can start with the task below. Agents use the [task-routing checklist] | Configure automatic updates and cleanup | [Host maintenance](HOST-MAINTENANCE.md) and [reproducible managed images](MANAGED-IMAGES.md) | | Install or operate a dedicated deployment host | [Deployer host installation](DEPLOYER-HOST.md) | | Monitor hosts and detect missed reports | [Fleet health monitoring](HEALTH-MONITORING.md), [local capacity telemetry](CAPACITY-TELEMETRY.md), and [authenticated status reporting](STATUS-REPORTING.md) | -| Review the planned endpoint web UI and its access/data contracts | [Endpoint observation UI design](ENDPOINT-UI-DESIGN.md), design only; no supported UI yet | +| Inspect the worker UI and its evidence and access boundaries | [Read-only worker views](WORKER-VIEWS.md), [endpoint observation design](ENDPOINT-UI-DESIGN.md) | | Handle GitHub App, workflow, or deployment secrets | [Secrets model](SECRETS.md) and [security policy](../SECURITY.md) | | Review accepted implementation scope | [Design decisions](DESIGN-DECISIONS.md) | | Run private CI or deployment for a public project | [Public projects, private delivery, and private configuration](PUBLIC-PRIVATE-CONFIGURATION.md) | diff --git a/docs/SECRETS.md b/docs/SECRETS.md index cb9d1930..9951c458 100644 --- a/docs/SECRETS.md +++ b/docs/SECRETS.md @@ -40,7 +40,7 @@ For a distributed fleet, use a secret manager or encrypted configuration system ### Planned endpoint observer access -The [endpoint observation design](ENDPOINT-UI-DESIGN.md#access-on-port-80) introduces a separate backend read bearer only when its packaging and access gates are implemented and separately authorized. No observer credential or listener is supported by this design change alone. +The [worker HTTP application](WORKER-VIEWS.md#repository-interface) checks the separate backend read bearer described in the [endpoint observation design](ENDPOINT-UI-DESIGN.md#access-on-port-80). Credential provisioning, gateway integration, and listener activation remain in #122. Provision 32 random bytes as 43 unpadded base64url ASCII characters without a trailing newline, in root-owned mode-`0600` files outside Git. The privileged installer reads the protected access references in `/etc/ci-fleet/observer/access.json`. Systemd `LoadCredential` supplies the observer's copy through its isolated credential directory; the observer does not read the private `/etc/ci-fleet` tree. Provision the gateway copy independently through its approved secret mechanism. diff --git a/docs/WORKER-VIEWS.md b/docs/WORKER-VIEWS.md new file mode 100644 index 00000000..2e0e77b4 --- /dev/null +++ b/docs/WORKER-VIEWS.md @@ -0,0 +1,91 @@ +# Read-only worker views + +The ordinary-CI worker UI reads the protected `endpoint.json` and `jobs.json` +exports described in the [worker snapshot contract](ENDPOINT-SNAPSHOTS.md). +The [endpoint UI design](ENDPOINT-UI-DESIGN.md) defines the access and +isolation boundary. Packaging, gateway integration, and live acceptance +are tracked in [#122](https://github.com/RandomDevelopment/ci-fleet/issues/122). + +## What the views show + +- **Overview.** Applied lifecycle and policy, busy and current runners, + configured and reviewed limits, reported problems, and observation times. + The effective configuration can record an intentional drain or disablement. + Snapshot v1 has no live admission decision or gate reason for maintenance, + disk, network reserve, authentication, or inspection. Check results and + spare runner slots cannot establish readiness. +- **Jobs.** Filter retained observations by repository, recorded state, and + result. Running activity depends on fresh publisher and listener evidence + for the matching export. Pending publisher gaps have their own evidence + time. Exported gaps and omitted records remain visible. Clock uncertainty + leaves terminal results available with their original evidence. Elapsed + time identifies the local start and whether the finish came from the source + or a local completion observation. GitHub run links use the validated owner, + repository, and workflow run ID. +- **Health.** The five-minute health report supplies check outcomes, including + subnet headroom, OOM evidence, controller restarts, and timer checks. It does + not supply numeric values for those checks. Anonymous seven-day capacity + percentiles cover the exported CPU, memory, swap, disk, and inode metrics. + The latest included sample has its own timestamp. Capacity samples run + every 30 seconds while runners are active and pause at idle. +- **Configuration.** Compare desired and applied commits and engine revisions, + manager and runtime selections, the running controller, resource limits, + and routing. The desired-engine observation records validation of the + approved configuration. Individual review records are unavailable. + Local image binding verification has its own time and revision. +- **Enrollment.** Installation, credential presence, successful + authentication, scale-set match, listener polling, signed reporting, and + owner confirmation each have separate evidence. A GitHub App owner must + confirm visibility. The export has no durable confirmation of that step. + +During a controller or Docker outage an available observer can still serve +the views. A retained value shows its original time and last-success status. +An unavailable or invalid export leaves the relevant view navigable with +unknown observations. A missing metric does not show as zero or passed. + +## Repository interface + +`scripts/endpoint_ui.py` takes a validated `SnapshotReader` through +`WorkerObserver(reader)`. `ObserverServer(listener, observer)` owns an +already listening IPv4 loopback socket. The caller owns provisioning and +activation under #122. The observer reads only the existing export reader +and its bundled static assets. It does not use Docker, host probes, or +private job history. + +The authenticated routes support `GET` and `HEAD`. + +| Route | Response | +| --- | --- | +| `/`, `/jobs`, `/health`, `/configuration`, `/enrollment` | Worker HTML views | +| `/worker.css`, `/worker.js` | Bundled styles and polling script | +| `/api/v1/endpoint` | Snapshot v1 with derived freshness | +| `/api/v1/capacity` | Capacity evidence from the same snapshot | +| `/api/v1/jobs` | Retained job history, its liveness and coverage, and up to 50 matching records | + +Read APIs include `read_schema_version: 1`. Job routes accept +`repository` as a case-insensitive substring of the owner and repository, +`state` as the recorded state, `result` as the recorded result, and +`cursor` from the prior page. A cursor expires when its validated export +changes, its anchor falls out of retention, or the observer restarts. A +`409` prompts the client to reload the first page. Missing or invalid +exports return `503` from the affected API. + +Every request requires the backend bearer. The server caps connections at +16 and authenticated handlers at four. It allows one request per +connection, caps headers at 16 KiB with a five-second receive deadline, +and caps responses at 1 MiB with a 30-second write deadline. Responses have +no cross-origin access and use `Cache-Control: no-store`. The browser +refreshes an active view every 15 seconds, backs off to at most two minutes +when data or transport is unavailable, and pauses while hidden. The page +explains when focus pauses refresh. It resumes when focus leaves, subject +to a five-second minimum between requests and the failure backoff. Browser +polling uses the published files at their existing producer cadences. + +## Verification + +Run `python3 scripts/test_endpoint_ui.py` for protected temporary export +and HTTP integration tests. The `endpoint-ui` group in +[local validation](LOCAL-VALIDATION.md) records test durations and output. +Gateway authentication, service activation, loopback port conflicts, +installation lifecycle, and outage tests on an approved worker remain part +of #122. diff --git a/scripts/endpoint_snapshot.py b/scripts/endpoint_snapshot.py index 1f8f1bd0..c6d5df9c 100644 --- a/scripts/endpoint_snapshot.py +++ b/scripts/endpoint_snapshot.py @@ -807,7 +807,7 @@ def __init__(self, base: Path, *, observer_gid: int, controller: str, backend_be self.base, self.observer_gid, self.controller, self._bearer = base, observer_gid, controller, backend_bearer self._job_cache = None - def _authenticate(self, headers: Mapping[str, str]) -> None: + def authenticate(self, headers: Mapping[str, str]) -> None: if not isinstance(headers, Mapping): raise SnapshotError("authentication_failed") authorization = [value for key, value in headers.items() if isinstance(key, str) and key.lower() == "authorization"] @@ -816,7 +816,7 @@ def _authenticate(self, headers: Mapping[str, str]) -> None: raise SnapshotError("authentication_failed") def read(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: - self._authenticate(headers) + self.authenticate(headers) value = read_endpoint(self.base, self.observer_gid) validate_snapshot(value, controller=self.controller) for name in SOURCE_NAMES - value["sources"].keys(): @@ -840,7 +840,7 @@ def read(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: return value def read_job_history(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: - self._authenticate(headers) + self.authenticate(headers) now = int(time.time()) if now is None else now if not integer(now): raise SnapshotError("invalid_argument") @@ -853,13 +853,19 @@ def read_job_history(self, headers: Mapping[str, str], *, now: int | None = None self._job_cache = None raise self._job_cache = (identity, history) + export_fingerprint = fingerprint(identity) + activity_evidence = None try: endpoint = self.read(headers, now=now) source = endpoint["sources"]["jobs"] data = source["data"] - current = (endpoint["publisher_freshness"] == source["freshness"] == "current" - and data["generation"] == history["generation"] and data["scale_set"] == history["scale_set"] - and data["export_fingerprint"] == fingerprint(identity) + matches = (data.get("generation") == history["generation"] and data.get("scale_set") == history["scale_set"] + and data.get("export_fingerprint") == export_fingerprint) + activity_evidence = {"published_at": endpoint["published_at"], "clock_state": endpoint["clock_state"], + "publisher_freshness": endpoint["publisher_freshness"], + "source": source, "generation_matches": matches} + current = (endpoint["publisher_freshness"] == source["freshness"] == "current" and matches + and history["published_at"] <= now and not data["pending"] and data["source_available"] and 0 <= now - data["last_poll_at"] <= 120 and history["omitted_nonterminal"] == 0) except (KeyError, StoreError, SnapshotError): @@ -867,6 +873,7 @@ def read_job_history(self, headers: Mapping[str, str], *, now: int | None = None rows = [{**row, "current_activity": "unknown" if row["state"] == "running" and not current else row["state"]} for row in history["records"] if row["last_observed_at"] > now - JOB_MAX_AGE] return {**history, "gaps": dict(history["gaps"]), "records": rows, + "export_fingerprint": export_fingerprint, "activity_evidence": activity_evidence, "current_activity_verified": current and not (CURRENT_COVERAGE_GAPS & history["gaps"].keys())} diff --git a/scripts/endpoint_ui.py b/scripts/endpoint_ui.py new file mode 100644 index 00000000..64e33b61 --- /dev/null +++ b/scripts/endpoint_ui.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""Read-only worker HTTP application for an already prepared loopback listener.""" + +from __future__ import annotations + +from hashlib import sha256 +from http import HTTPStatus +import hmac +from pathlib import Path +import re +import secrets +import socket +from socketserver import ThreadingTCPServer +from threading import BoundedSemaphore, Lock +import time +from urllib.parse import parse_qsl + +from endpoint_jobs import RESULTS, record_key +from endpoint_snapshot import SnapshotError, SnapshotReader +from endpoint_snapshot_store import StoreError, encode_json +import endpoint_views as views + +MAX_HEADERS = 16 * 1024 +MAX_RESPONSE = 1024 * 1024 +HEADER_SECONDS = 5 +IO_SECONDS = 30 +MAX_CONNECTIONS = 16 +MAX_HANDLERS = 4 +PAGE_SIZE = 50 +TOKEN = re.compile(rb"[!#$%&'*+.^_`|~0-9A-Za-z-]+") +CURSOR = re.compile(r"([0-9a-f]{64})\.([0-9a-f]{64})") +JSON = "application/json" +HTML = "text/html; charset=utf-8" +ASSET_DIR = Path(__file__).with_name("endpoint_ui_assets") +ASSETS = {"/worker.css": ("text/css; charset=utf-8", "worker.css"), + "/worker.js": ("text/javascript; charset=utf-8", "worker.js")} +API = {"/api/v1/endpoint", "/api/v1/jobs", "/api/v1/capacity"} +JOB_STATES = ("running", "completed", "unknown") +NO_STORE = ( + b"Cache-Control: no-store\r\n" + b"Connection: close\r\n" + b"Content-Security-Policy: default-src 'none'; style-src 'self'; script-src 'self'; " + b"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'\r\n" + b"X-Content-Type-Options: nosniff\r\n" + b"Referrer-Policy: no-referrer\r\n" +) + + +class RequestError(ValueError): + def __init__(self, status, code): + super().__init__(code) + self.status, self.code = status, code + + +def receive_headers(connection, deadline): + raw = bytearray() + while not raw.endswith(b"\r\n\r\n"): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError + if len(raw) == MAX_HEADERS: + raise RequestError(431, "headers_too_large") + connection.settimeout(remaining) + chunk = connection.recv(min(4096, MAX_HEADERS - len(raw))) + if not chunk: + raise EOFError + raw.extend(chunk) + if b"\r\n\r\n" in raw and not raw.endswith(b"\r\n\r\n"): + raise RequestError(400, "invalid_request") + return parse_headers(raw[:-4]) + + +def parse_headers(raw): + request, *lines = raw.split(b"\r\n") + match = re.fullmatch(rb"([^ ]+) (/[^ ]*) HTTP/1\.[01]", request) + if not match or not TOKEN.fullmatch(match[1]) or not re.fullmatch(rb"[!-~]+", match[2]): + raise RequestError(400, "invalid_request") + headers = {} + for line in lines: + name, colon, value = line.partition(b":") + if not colon or not TOKEN.fullmatch(name) or not re.fullmatch(rb"[\t -~]*", value): + raise RequestError(400, "invalid_request") + name = name.decode("ascii").lower() + if name in headers: + raise RequestError(400, "invalid_request") + headers[name] = value.decode("ascii").strip(" \t") + if (request.endswith(b"HTTP/1.1") and not headers.get("host") + or {"transfer-encoding", "expect"} & headers.keys() + or headers.get("content-length", "0") != "0"): + raise RequestError(400, "invalid_request") + return match[1].decode("ascii"), match[2].decode("ascii"), headers + + +def job_query(query): + if len(query) > 1024 or re.search(r"%(?![0-9a-fA-F]{2})", query): + raise RequestError(400, "invalid_filters") + try: + pairs = parse_qsl(query, keep_blank_values=True, strict_parsing=True, errors="strict", max_num_fields=4) + except ValueError: + raise RequestError(400, "invalid_filters") from None + params = dict(pairs) + repo, state, result, cursor = (params.get(field, "") for field in ("repository", "state", "result", "cursor")) + if (len(params) != len(pairs) or set(params) - {"repository", "state", "result", "cursor"} + or not re.fullmatch(r"[A-Za-z0-9_./-]{0,140}", repo) + or state and state not in JOB_STATES or result and result not in RESULTS): + raise RequestError(400, "invalid_filters") + if cursor and not CURSOR.fullmatch(cursor): + raise RequestError(400, "invalid_cursor") + return {key: value for key, value in (("repository", repo), ("state", state), ("result", result)) if value}, cursor + + +def row_anchor(row): + kind, value = record_key(row) + return sha256((kind + "\x00" + value).encode()).hexdigest() + + +def jobs_page(history, filters, cursor, cursor_key): + generation = history["generation"] + context = encode_json({"generation": generation, "export": history["export_fingerprint"], "filters": filters}) + + def sign(anchor): + return hmac.digest(cursor_key, context + anchor.encode("ascii"), "sha256").hex() + + rows = history["records"] + repo, state, result = (filters.get(field, "") for field in ("repository", "state", "result")) + matching = [row for row in rows + if (not repo or repo.lower() in views.repository(row).lower()) + and (not state or state == row["state"]) and (not result or result == row.get("result"))] + start = 0 + if cursor: + anchor, signature = cursor.split(".") + if not hmac.compare_digest(sign(anchor), signature): + raise RequestError(409, "cursor_expired") + for start, row in enumerate(matching, 1): + if row_anchor(row) == anchor: + break + else: + raise RequestError(409, "cursor_expired") + page = matching[start:start + PAGE_SIZE] + next_cursor = None + if start + len(page) < len(matching): + anchor = row_anchor(page[-1]) + next_cursor = anchor + "." + sign(anchor) + return {key: value for key, value in history.items() if key not in {"records", "export_fingerprint"}} | { + "read_schema_version": 1, "records": page, "matching": len(matching), "offset": start, + "next_cursor": next_cursor, + } + + +class WorkerObserver: + def __init__(self, reader: SnapshotReader): + self.reader = reader + self._cursor_key = secrets.token_bytes(32) + # The file reader keeps one validated job generation. + self._read_lock = Lock() + self.assets = {} + for route, (content_type, name) in ASSETS.items(): + with (ASSET_DIR / name).open("rb") as asset: + body = asset.read(MAX_RESPONSE + 1) + if len(body) > MAX_RESPONSE: + raise ValueError("asset_too_large") + self.assets[route] = (content_type, body) + + def _response(self, method, target, headers): + if method not in {"GET", "HEAD"}: + raise RequestError(405, "method_not_allowed") + path, _, query = target.partition("?") + if path not in views.PAGES and path not in API and path not in self.assets: + raise RequestError(404, "not_found") + is_jobs = path in {"/jobs", "/api/v1/jobs"} + if query and not is_jobs: + raise RequestError(400, "invalid_request") + if path in self.assets: + content_type, body = self.assets[path] + return 200, content_type, body + + filters, cursor = job_query(query) if is_jobs else ({}, "") + with self._read_lock: + now = int(time.time()) + return self._read(path, headers, now, filters, cursor) + + def _read(self, path, headers, now, filters, cursor): + is_jobs = path in {"/jobs", "/api/v1/jobs"} + try: + if is_jobs: + history = self.reader.read_job_history(headers, now=now) + evidence = jobs_page(history, filters, cursor, self._cursor_key) + else: + evidence = self.reader.read(headers, now=now) + except (StoreError, SnapshotError) as error: + if path in API: + raise RequestError(503, "observation_unavailable") from None + return 200, HTML, views.page(path, None, now, filters, unavailable=error.code) + except RequestError as error: + if path != "/jobs" or error.code != "cursor_expired": + raise + return 409, HTML, views.page(path, None, now, filters, unavailable=error.code) + + if path == "/api/v1/capacity": + evidence = {"read_schema_version": 1, "schema_version": evidence["schema_version"], + "controller": evidence["controller"], "clock_state": evidence["clock_state"], + "published_at": evidence["published_at"], "publisher_freshness": evidence["publisher_freshness"], + "capacity": evidence["sources"]["capacity"]} + if path == "/api/v1/endpoint": + evidence = {"read_schema_version": 1, **evidence} + if path in API: + return 200, JSON, encode_json(evidence) + return 200, HTML, views.page(path, evidence, now, filters) + + +class ObserverServer(ThreadingTCPServer): + """Owns an already listening IPv4 loopback socket and never binds a port.""" + + def __init__(self, listener: socket.socket, observer: WorkerObserver): + if (listener.family != socket.AF_INET or listener.getsockname()[0] != "127.0.0.1" + or not listener.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN)): + raise ValueError("invalid_listener") + super().__init__(listener.getsockname(), None, bind_and_activate=False) + self.socket.close() + self.socket = listener + self.observer = observer + self.connections = BoundedSemaphore(MAX_CONNECTIONS) + self.handlers = BoundedSemaphore(MAX_HANDLERS) + + def process_request(self, request, address): + if not self.connections.acquire(blocking=False): + self.close_request(request) + return + try: + super().process_request(request, time.monotonic() + HEADER_SECONDS) + except BaseException: + self.connections.release() + raise + + def process_request_thread(self, request, deadline): + head = False + try: + try: + method, target, headers = receive_headers(request, deadline) + except RequestError as error: + send_failure(request, error) + return + head = method == "HEAD" + try: + self.observer.reader.authenticate(headers) + except SnapshotError: + send_failure(request, RequestError(401, "authentication_failed"), head=head) + return + if not self.handlers.acquire(blocking=False): + send_failure(request, RequestError(503, "observer_busy"), head=head) + return + try: + try: + status, content_type, body = self.observer._response(method, target, headers) + if len(body) > MAX_RESPONSE: + raise RequestError(503, "response_too_large") + send_response(request, status, content_type, body, head=head) + except RequestError as error: + send_failure(request, error, head=head) + finally: + self.handlers.release() + except (OSError, EOFError): + pass + except Exception: + try: + send_failure(request, RequestError(503, "observer_unavailable"), head=head) + except OSError: + pass + finally: + self.shutdown_request(request) + self.connections.release() + + +def send_failure(connection, error, *, head=False): + send_response(connection, error.status, JSON, encode_json({"error": error.code}), head=head) + + +def send_response(connection, status, content_type, body, *, head): + extra = {401: b'WWW-Authenticate: Bearer realm="ci-fleet-observer"\r\n', + 405: b"Allow: GET, HEAD\r\n"}.get(status, b"") + headers = (f"HTTP/1.1 {status} {HTTPStatus(status).phrase}\r\nContent-Type: {content_type}\r\n" + f"Content-Length: {len(body)}\r\n").encode("ascii") + NO_STORE + extra + b"\r\n" + connection.settimeout(IO_SECONDS) + connection.sendall(headers if head else headers + body) diff --git a/scripts/endpoint_ui_assets/worker.css b/scripts/endpoint_ui_assets/worker.css new file mode 100644 index 00000000..3281176d --- /dev/null +++ b/scripts/endpoint_ui_assets/worker.css @@ -0,0 +1,107 @@ +:root { + color-scheme: light; + font-family: system-ui, sans-serif; + line-height: 1.5; + color: #1c2630; + background: #f4f6f8; + --muted: #50606d; + --line: #d9e0e6; + --accent: #075d62; + --paper: #fff; +} + +* { box-sizing: border-box; } +body { margin: 0; } +a { color: var(--accent); text-underline-offset: .22em; } +:focus-visible { outline: 3px solid #08777c; outline-offset: 3px; } +.skip { position: absolute; top: .5rem; left: .5rem; background: var(--paper); padding: .65rem; z-index: 1; } +.skip:not(:focus) { clip-path: inset(50%); } + +.site-header { background: #152c39; color: white; } +.site-inner, main { max-width: 78rem; margin-inline: auto; padding-inline: clamp(1rem, 4vw, 3rem); } +.brand { margin: 0; padding-block: 1rem .4rem; font-weight: 750; font-size: 1.2rem; } +.brand span { margin-left: .55rem; color: #d1dce3; font-size: .875rem; font-weight: 450; } +.site-header nav { display: flex; flex-wrap: wrap; gap: .25rem 1.4rem; } +.site-header a { color: white; border-bottom: 3px solid transparent; padding-block: .6rem; text-decoration: none; } +.site-header a:hover { text-decoration: underline; } +.site-header a[aria-current] { border-color: #89e0d5; font-weight: 700; } +.site-header a:focus-visible { outline-color: #89e0d5; outline-offset: 0; } + +main { padding-block: clamp(1rem, 3vw, 2.25rem) 4rem; } +h1 { margin: 0 0 .65rem; font-size: clamp(1.85rem, 4vw, 2.65rem); letter-spacing: -.04em; line-height: 1.2; } +h2 { margin: 0; font-size: 1.15rem; letter-spacing: -.015em; } +p { margin: .6rem 0 0; } +small { display: block; color: var(--muted); font-size: .8rem; } +time { font-variant-numeric: tabular-nums; } +.context { color: var(--muted); margin: 0 0 1rem; } +.refresh-status { margin: 0 0 1rem; padding: .6rem .85rem; border: 1px solid #906c2b; background: #fff8e7; } +.refresh-status:empty { margin: 0; padding: 0; border: 0; } + +.panel, .count, .admission { + background: var(--paper); + border: 1px solid var(--line); + border-radius: .65rem; + padding: clamp(.9rem, 2vw, 1.35rem); + overflow-wrap: anywhere; +} +.panel, .counts, .admission { margin-bottom: 1rem; } +.admission { border-left: .3rem solid var(--accent); } +.admission h2 { font-size: 1.3rem; } +.counts, .columns { display: grid; gap: 1rem; align-items: start; } +.counts { grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: stretch; } +.columns { grid-template-columns: repeat(2, minmax(0, 1fr)); row-gap: 0; } +.count span { font-weight: 650; } +.count strong { display: block; font-size: 1.65rem; font-variant-numeric: tabular-nums; margin-block: .15rem; } +.evidence { margin-top: .35rem; color: var(--muted); font-size: .85rem; } +.status { display: inline-block; padding: .12rem .55rem; border: 1px solid var(--line); border-radius: .4rem; font-size: .82rem; font-weight: 650; } + +.definitions { margin: .6rem 0 0; } +.definitions div { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); gap: .75rem; border-top: 1px solid var(--line); padding-block: .5rem; } +.definitions dt { color: var(--muted); font-size: .9rem; } +.definitions dd { margin: 0; } +.definitions small { margin-top: .15rem; } + +.filters { display: flex; flex-wrap: wrap; align-items: end; gap: .65rem; margin-top: .85rem; } +.filters label { display: grid; gap: .3rem; color: var(--muted); font-size: .88rem; font-weight: 600; } +.filters input, .filters select, button { + min-height: 2.5rem; + max-width: 100%; + padding: .38rem .55rem; + border: 1px solid #82929d; + border-radius: .4rem; + background: var(--paper); + color: inherit; + font: inherit; +} +button { color: white; background: var(--accent); border-color: var(--accent); cursor: pointer; font-weight: 650; } +.pagination { display: flex; gap: 1rem; margin-top: .85rem; } +.result-count { color: var(--muted); font-size: .9rem; } +.table-wrap { overflow-x: auto; margin-top: .8rem; } +table { width: 100%; border-collapse: collapse; text-align: left; } +thead { background: #eef3f6; } +th, td { padding: .55rem .65rem; border-bottom: 1px solid var(--line); vertical-align: top; } +th { font-weight: 650; } +.job-table { min-width: 43rem; } +.job-table th[scope="row"] { width: 29%; } + +@media (max-width: 48rem) { + .columns { grid-template-columns: minmax(0, 1fr); } +} + +@media (max-width: 35rem) { + .site-header nav { column-gap: .9rem; } + .site-header a { font-size: .88rem; } + .counts { grid-template-columns: minmax(0, 1fr); gap: .55rem; } + .count { display: grid; grid-template-columns: 1fr auto; align-items: center; column-gap: .75rem; } + .count small { grid-column: 1 / -1; } + .definitions div { grid-template-columns: minmax(0, 1fr); gap: .2rem; } + .filters label:first-child { flex: 1 0 100%; } + .filters input, .filters select { font-size: 1rem; } + .job-table { min-width: 0; } + .job-table thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } + .job-table, .job-table tbody, .job-table tr { display: block; } + .job-table tbody tr { border-top: 1px solid var(--line); padding-block: .5rem; } + .job-table td, .job-table th[scope="row"] { display: block; width: auto; border: 0; padding: .25rem 0; } + .job-table td::before { content: attr(data-label) " "; color: var(--muted); font-weight: 650; } + .job-table td small { margin-left: .15rem; } +} diff --git a/scripts/endpoint_ui_assets/worker.js b/scripts/endpoint_ui_assets/worker.js new file mode 100644 index 00000000..a19deac1 --- /dev/null +++ b/scripts/endpoint_ui_assets/worker.js @@ -0,0 +1,107 @@ +"use strict"; + +const interval = 15000; +const minimumInterval = 5000; +const maxInterval = 120000; +const maxBytes = 1024 * 1024; +const pauseMessage = "Refresh paused while you use this view. Displayed measurements are from the last update."; +const refreshStatus = document.getElementById("refresh-status"); +let observations = document.getElementById("observations"); +let delay = interval; +let nextRefresh = performance.now() + interval; +let timer; +let request; + +function report(message) { + if (refreshStatus.textContent !== message) { + refreshStatus.textContent = message; + } +} + +function schedule() { + clearTimeout(timer); + if (document.hidden || request) return; + const remaining = Math.max(0, nextRefresh - performance.now()); + if (!remaining && observations.contains(document.activeElement)) { + report(pauseMessage); + return; + } + timer = setTimeout(refresh, remaining); +} + +async function readPage(response) { + if (![200, 409].includes(response.status) || + !response.headers.get("content-type")?.startsWith("text/html;") || + Number(response.headers.get("content-length")) > maxBytes) { + throw new Error("Invalid refresh response"); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder("utf-8", { fatal: true }); + let html = ""; + let bytes = 0; + try { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > maxBytes) throw new Error("Refresh response too large"); + html += decoder.decode(value, { stream: true }); + } + return new DOMParser().parseFromString(html + decoder.decode(), "text/html"); + } finally { + await reader.cancel(); + } +} + +async function refresh() { + if (document.hidden) return; + if (observations.contains(document.activeElement)) { + schedule(); + return; + } + + const started = performance.now(); + request = new AbortController(); + const timeout = setTimeout(() => request.abort(), 8000); + let retryAfterFocus = false; + try { + const response = await fetch(location.pathname + location.search, { + cache: "no-store", + mode: "same-origin", + redirect: "error", + signal: request.signal, + }); + const updated = (await readPage(response)).getElementById("observations"); + if (!updated) throw new Error("Worker view missing"); + const available = updated.dataset.available === "true"; + if (!document.hidden) { + if (observations.contains(document.activeElement)) { + retryAfterFocus = available; + report(pauseMessage); + } else { + observations.replaceWith(updated); + observations = updated; + report(""); + } + } + delay = available ? interval : Math.min(delay * 2, maxInterval); + } catch { + if (!document.hidden) { + report("Refresh unavailable. Any displayed measurements are from the last loaded page."); + delay = Math.min(delay * 2, maxInterval); + } + } finally { + clearTimeout(timeout); + request = undefined; + nextRefresh = started + (retryAfterFocus ? minimumInterval : delay); + schedule(); + } +} + +document.addEventListener("visibilitychange", () => { + if (document.hidden) request?.abort(); + schedule(); +}); +document.addEventListener("focusout", () => queueMicrotask(schedule)); +schedule(); diff --git a/scripts/endpoint_views.py b/scripts/endpoint_views.py new file mode 100644 index 00000000..9550d766 --- /dev/null +++ b/scripts/endpoint_views.py @@ -0,0 +1,482 @@ +"""Server-rendered worker views. All observations come from validated exports.""" + +from __future__ import annotations + +from datetime import datetime, timezone +from html import escape +from urllib.parse import urlencode + +from endpoint_jobs import RESULTS, run_link +from endpoint_snapshot import SOURCE_NAMES + +PAGES = {"/": "Overview", "/jobs": "Jobs", "/health": "Health", + "/configuration": "Configuration", "/enrollment": "Enrollment"} +DOCS = "https://github.com/RandomDevelopment/ci-fleet/blob/main/docs/" +HEALTH_LABELS = { + "load": "CPU load", "oom": "Out-of-memory evidence", "memory": "Memory", "swap": "Swap", + "disk_root": "Root disk", "disk_docker": "Docker disk", "inode_root": "Root inodes", + "inode_docker": "Docker inodes", "docker": "Docker daemon", "restarts": "Controller restarts", + "docker_network_headroom": "Docker subnet headroom", "docker_network_inspection": "Docker network inspection", + "capacity": "Capacity health check", "capacity_service": "Capacity sampler service", + "timer_health": "Health timer", "timer_cleanup": "Cleanup timer", "timer_drift": "Drift timer", + "timer_updates": "Package update timer", "timer_reconcile": "Reconciliation timer", + "timer_capacity": "Capacity timer", "updates": "Package update status", "updates_service": "Package update service", +} +CORE_HEALTH = ( + "load", "memory", "swap", "disk_root", "disk_docker", "inode_root", "inode_docker", "oom", + "docker", "docker_network_inspection", "docker_network_headroom", "controller", "controller_status", + "restarts", "capacity", "capacity_service", "timer_health", "timer_cleanup", "timer_drift", + "timer_updates", "timer_reconcile", "timer_capacity", "cleanup", "drift", "reconcile", "updates", "updates_service", +) +METRICS = { + "host_cpu_percent": ("Host CPU", "%"), "runner_cpu_percent": ("Runner CPU", "%"), + "host_memory_used_bytes": ("Host memory used", "bytes"), + "runner_memory_used_bytes": ("Runner memory used", "bytes"), + "runner_memory_limit_bytes": ("Runner memory limit", "bytes"), + "host_swap_used_bytes": ("Host swap used", "bytes"), + "host_disk_used_bytes_root": ("Root disk used", "bytes"), + "host_disk_used_bytes_docker": ("Docker disk used", "bytes"), + "host_inode_used_root": ("Root inodes used", "count"), + "host_inode_used_docker": ("Docker inodes used", "count"), +} + + +def text(value): + if value is None: + return "Unknown" + if type(value) is bool: + return "Yes" if value else "No" + if isinstance(value, list): + return ", ".join(text(item) for item in value) + return escape(str(value)) + + +def words(code): + return text(code.replace("_", " ").capitalize() if code else None) + + +def time_text(value): + if value is None: + return "Unknown time" + try: + stamp = datetime.fromtimestamp(value, timezone.utc) + except (ValueError, OverflowError, OSError): + return "Unknown time" + return f'' + + +def elapsed(seconds): + if seconds is None or seconds < 0: + return "Unknown" + hours, remainder = divmod(seconds, 3600) + minutes, seconds = divmod(remainder, 60) + if hours >= 24: + return f"{hours // 24}d {hours % 24}h" + if hours: + return f"{hours}h {minutes}m" + if minutes: + return f"{minutes}m {seconds}s" + return f"{seconds}s" + + +def source_note(source, now): + availability = source["availability"] + status = words(source["freshness"] if availability == "available" else availability) + if source["error"] and source["error"] != availability: + status += f' · {words(source["error"])}' + observed = source["observed_at"] + successful = source["last_success_at"] + when = observed if observed is not None else successful + if when is None: + return status + " · No measurement time" + label = "Observed" if observed is not None else "Last successful observation" + age = elapsed(now - when) + " ago" if now is not None and now >= when else "age unknown" + return f'{status} · {label} {time_text(when)} · {age}' + + +def section(title, content, *, note=None): + evidence = f'
{note}
' if note else "" + return f'{explanation}
The reported controller maximum differs from the reviewed maximum.
" + problems = [(HEALTH_LABELS.get(check["id"], words(check["id"])), chip(words(check["status"]))) + for check in health["data"].get("checks", []) if check["status"] != "ok"] + if not problems: + problems_html = ("No problems in the latest health report.
" if health["freshness"] == "current" + else "Current problems are unknown.
") + else: + problems_html = definitions(problems) + if health["data"]: + problems_html = f'Reported health {chip(words(health["data"]["status"]))}
' + problems_html + + latest = definitions((label, source_note(sources[name], now)) for label, name in ( + ("Controller counts", "controller"), ("Health checks", "health"), ("Capacity sample", "capacity"), + ("Listener poll", "enrollment_listener"), ("Reconciliation check", "reconciliation"), ("Host boot", "boot"), + )) + return (head + 'The five-minute report contains check results. Numeric subnet headroom, OOM events and " + "restart counts are unavailable in snapshot v1.
" + definitions(rows)) + paused = (snapshot["publisher_freshness"] == controller["freshness"] == "current" + and controller["data"].get("current") == 0) + capacity_body = ("Capacity sampling runs every 30 seconds while runners are active and pauses at idle. " + "The seven-day percentiles use anonymous samples.
") + if paused: + capacity_body += "No active runners were reported. The last sample can be older while the worker is idle.
" + data = capacity["data"] + if data: + capacity_body += definitions((("Samples", text(data["samples"])), + ("Runner observations", text(data["runner_observations"])))) + capacity_body += ('| Metric | p50 | ' + 'p95 |
|---|---|---|
| {label} | {metric(values.get("p50"), unit)} | ' + f'{metric(values.get("p95"), unit)} |
Weekly capacity measurements are unavailable.
" + if paused and capacity["freshness"] == "stale": + capacity_note = f'Last sample while active · {time_text(capacity["observed_at"])}' + else: + capacity_note = source_note(capacity, now) + return ('The desired-engine source records validation of the approved configuration. " + "Snapshot v1 has no individual reviewer or approval record.
") + runtime = [] + for label, name, field in ( + ("Selected runtime", "runtime_revision", "revision"), ("Running controller engine", "controller", "software_version"), + ("Installed manager selection", "manager_revision", "revision"), + ("Staged manager", "staged_manager_revision", "revision"), + ): + source = sources[name] + runtime.append((label, f'{text(source["data"].get(field))}{source_note(source, now)}')) + image = sources["image_verification"] + revisions = definitions(runtime) + labeled_data(image["data"], ( + ("Image verification", "state", words), ("Verified engine revision", "revision", text), + ("Verified architecture", "architecture", text), + )) + f'{source_note(image, now)}
' + revisions += "Image verification covers local bindings recorded by the verifier. The running engine comes from controller status.
" + limits = labeled_data(configured["data"], ( + ("Runner CPU cores", "runner_cpu_cores", text), ("Runner memory (MiB)", "runner_memory_mib", text), + ("Minimum runners", "minimum_runners", text), ("Configured maximum", "maximum_runners", text), + ("Routing labels", "routing_labels", text), ("Storage retention configured", "storage_retention_configured", text), + )) + limits += definitions((("Pool", text(policy["data"].get("pool"))), + ("Scale set", text(policy["data"].get("scale_set_name"))), + ("Architecture", text(policy["data"].get("architecture"))), + ("Policy evidence", source_note(policy, now)))) + return ('A GitHub App owner must confirm the App’s visibility. The snapshot has no durable " + "confirmation record. Credential presence, scale-set authentication and listener readiness " + "are separate observations.
" + runbooks) + "Showing {history["offset"] + 1:,} to ' + f'{history["offset"] + len(history["records"]):,} of {matching:,} matching records
' + '| Job and repository | ' + 'Activity | ' + 'Elapsed | Result | ' + 'Last observed |
|---|
No matching retained job records.
" + first = escape("/jobs" + ("?" + urlencode(filters) if filters else "")) + next_cursor = history["next_cursor"] + if history["offset"] or next_cursor: + content += '" + return section("Running and recent jobs", content) + section("Job history evidence", definitions(details), note=note) + + +VIEWS = {"/": overview, "/health": health, "/configuration": configuration, "/enrollment": enrollment} +NO_SOURCE = {"availability": "unknown", "freshness": "unknown", "observed_at": None, + "last_success_at": None, "error": None, "data": {}} + + +def page(path, snapshot, now, filters, *, unavailable=None): + title = PAGES[path] + nav = "".join(f'{label}' + for route, label in PAGES.items()) + if unavailable == "cursor_expired": + first = escape("/jobs" + ("?" + urlencode(filters) if filters else "")) + body = section("Job page expired", f'Job history changed or the record expired. Start again.
') + elif unavailable: + label = "Job history unavailable" if path == "/jobs" else "Worker snapshot unavailable" + body = section(label, f'{words(unavailable)}. Measurements and current activity are unknown.
') + if path == "/jobs": + body += section("Running and recent jobs", job_filters(filters)) + else: + body += VIEWS[path]({"sources": dict.fromkeys(SOURCE_NAMES, NO_SOURCE), + "publisher_freshness": "unknown", "clock_state": "unknown"}, None) + else: + if path == "/jobs": + body = jobs(snapshot, now, filters) + else: + body = VIEWS[path](snapshot, None if snapshot["clock_state"] == "uncertain" else now) + if path != "/jobs" and snapshot: + context = f'{text(snapshot["controller"])} · {snapshot_note(snapshot)}
' + elif snapshot: + context = f'{text(snapshot["controller"])} · Scale set {text(snapshot["scale_set"])}
' + else: + context = "" + available = "false" if unavailable else "true" + return f""" + + + + +CI Fleet Worker observation
+ +