Documentation
¶
Overview ¶
Forwarding (docs/migrate-forward-design.md): this host (A) passes deploys and visitors it no longer serves to another pstack (B). This file is what every forwarding path shares: the stored row, the transport that reaches B, and the deploy-API proxy. routes_forward.go is the setting's API.
Package api is the HTTP control plane. This file is the request/response plumbing every route shares: the JSON envelope, query variables, cookies, the base URL, and the byte-level helpers the terminal and the tuning knobs need. Routes live in routes.go; the principal and the gate in principal.go.
The loki-apply job: Loki's saved settings, onto control/loki and the loki container.
ONE JOB ON THE CONTROL PROJECT'S KEY (inspect.ControlProject). Applies run one at a time, one waits, and each counts against PSTACK_MAX_JOBS. A save's job and a boot job are the same job.
PENDING PATCHES. A PUT stores its section's patch with a generation under lokiMu, then starts a job that holds only that number. The job takes every patch at or below it. jobs.Start keeps one waiting job per key and supersedes the rest, so a superseded save is carried by its successor, and a running job never takes a newer save.
THE STEPS. find → render → verify → commit → swap → restart → ready → finish → log, then logging.changed when the row changed. Nothing live changes before the swap: a failure up to the commit removes the .next files and leaves the row. The row is saved with previous_* BEFORE the swap and finished after ready, so a pstack that dies in between leaves its own undo record.
THE POST RUNNER. From the swap on, commands run on a runner with its own 2×lead deadline. It is not the job's runner, which refuses every command once cancelled (exec.go:110), and not s.host, which Stop cancels. A cancel after the swap still restarts and waits.
SCRUBBING. The secret, the previous secret and the key id are known only once the patches are merged. One scrub serves the sink and the record, and it reads them when it is called, on the job's goroutine.
THE PERMISSION TABLE: which role may reach which route, in ONE ordered table consulted in ONE place, and DEFAULT-DENY.
── WHY A TABLE AND NOT A CHECK IN EACH HANDLER ─────────────────────────────────────────────────
A check inside each handler is a rule you have to remember to write. Forgetting is silent, and it is not hypothetical: `POST /api/users` shipped reachable by ANY authenticated principal and — the route passing no role, so the insert fell through to `COALESCE(?, 'admin')` — always created an ADMIN. Any account on the host could mint itself a second, fully privileged one. Nothing in the code looked wrong, because the missing check was invisible.
So the rule lives here instead, and a route with NO ENTRY requires root. Forgetting to add an entry costs an operator a 403 and one commit; forgetting a handler check costs the host. The fallback and a deliberate root-only row are the SAME expression — `who.Allows("")`, an unrankable minimum nobody but root meets — so there is no third behaviour to get wrong.
── THE SAME REGEXES routes.go DISPATCHES ON ────────────────────────────────────────────────────
Every row points at the compiled pattern the chain itself matches (`deploymentRe`, `notifierRe`, …), never a second copy of it. Two patterns for one route is a drift bug with a fuse in it: the day someone widens the dispatch pattern, the gate keeps matching the old one and the new shape of the route is ungated. permissions_test.go walks the source of the chain and fails if a matcher or a literal path it dispatches on has no row here.
── THE FOUR ROLES, AND THE TWO PRINCIPALS THAT ARE NOT ROLES ───────────────────────────────────
viewer < developer < maintainer < admin (internal/auth). Above them, `root` — the PSTACK_TOKEN bearer — passes everything.
A SHARE PRINCIPAL SKIPS THIS TABLE ENTIRELY, and that is not a hole. `shareAllows` (principal.go) has already run, BEFORE any route: GET only, its own deployment only, only the routes its views name, everything else refused (invariant 16). Ranking a share here would be a second, weaker copy of that gate; denying it here would break every share link on every host. It is decided before it arrives, so this table lets it pass and `auth.Principal.Allows` refuses it at every rank in case anyone ever reaches for it directly.
── WHERE A ROW IS A DECISION, NOT A DEDUCTION ──────────────────────────────────────────────────
Four rows below are worth stating out loud, because each looks wrong at a glance:
- `WS /api/deployments/:id/terminal` is DEVELOPER, not admin. A developer can already run arbitrary compose through `up` — including a service that mounts the docker socket — so refusing them the shell is theatre while the larger door stays open. Close the larger door first and this row can follow it.
- `GET /api/swarm/join` is MAINTAINER, where it used to be admin. It is a host-configuration read, and it sits with the other ones. It is still a real credential (the token joins a machine to the cluster), so it stops at maintainer and goes no lower.
- `PUT/DELETE /api/sso/config*` is ADMIN even though every other host-configuration write is maintainer, because a provider's `defaultRole` MINTS ACCOUNTS at whatever role it names. A maintainer able to point SSO at an identity provider they control could sign in through it as an admin — that is a promotion path, so it belongs with people, not with configuration. The matching READ stays maintainer: it returns a mask, never the client secret.
- The custom-route writes are DEVELOPER, though they rewrite a Traefik dynamic file (`pstack-routes.yml`) and every hand-written one (`/api/routing/:file`) is maintainer. The file is rendered, never typed: a route can only point a twin host at a deployment's own generated services, which is what deploying that deployment already does.
Node pressure, held in memory: which kinds each node is in, and the `node.pressure` / `node.recovered` events on the edges. nodestats/pressure.go judges a reading; this file keeps the state between ticks and tells the world when it changes.
── EDGES ONLY ──────────────────────────────────────────────────────────────────────────────────
`node.pressure` fires when a node's kinds go from none to some, `node.recovered` from some to none. A change of kinds inside pressure fires nothing: `/api/stats` carries the current picture. The state is memory only (invariant 10), so a restart raises again whatever is still true; receivers dedupe on `id`, as they do for signals.
── UNKNOWN IS NEVER PRESSURE ───────────────────────────────────────────────────────────────────
Only a fresh, readable batch is judged (invariant 11). A stale node's entry is left as it was and nothing fires: it did not recover, it went quiet. inPressure says false for it, so no guard acts.
── NO ROOM, NO NEW WORK ────────────────────────────────────────────────────────────────────────
capacityRefusal is the guard startLifecycle runs before an up or a wake. On swarm it refuses when every active node is fresh and in pressure: which node a task lands on cannot be known. With no active node, or no data, it allows (NP-R18): unknown is never pressure. A compose deployment, on either host, is refused when the self node is in pressure.
── SLEEP THE LEAST RECENTLY USED ───────────────────────────────────────────────────────────────
pressureSleep is the memory and cpu answer. Each stats tick it sleeps ONE stack in total, across every node (NP-R21): of the stacks with a container on a node in memory or cpu pressure, the one whose scheduler.Recency is oldest (NP-R20), ties by stack name. Eligible means awake, not `kind: shared`, not busy, and unused for `pressure_sleep_idle_min`; 0 turns it off. It does nothing when the traffic meter cannot read Traefik: silence is not idle. `st.Sleep` is not required, since a wake runs `up` off the record. The reason is `<hostname> <Describe>` of the stack's first node in key order, as Describe words it (NP-R22): `worker-2 memory 6% free ≤ 10%`.
── THE id ──────────────────────────────────────────────────────────────────────────────────────
`pressure/<key>` (NP-R17): the swarm node id on swarm, as the spec spells it, and the hostname on a compose host, where the spec's `pressure/<node>` would read `pressure/`. `node` is null there (NP-R15).
Image prunes, decided on the stats tick: an emergency prune of a node whose disk is in pressure, and a scheduled prune of every node every 6 hours. nodestats/commands.go spells the commands and reads their output; this file decides when, runs them, and tells the world.
── WHEN ────────────────────────────────────────────────────────────────────────────────────────
- Emergency (`pressure`): a fresh node in disk pressure, at most once per node per 10 minutes, so a disk full of something other than images is not pruned in a loop. Unused images of any age; the build cache is left alone. lastEmergency is set when the prune starts, whether or not it works (NP-R2).
- Scheduled: every 6 hours from the first tick (NP-R3), when image_prune_after_h is above 0. Images and build cache older than that many hours. It does not wait for agent data (NP-R26).
- One prune at a time. An emergency wins a tick over the schedule.
── WHERE ───────────────────────────────────────────────────────────────────────────────────────
The control-plane node (selfKey) is always pruned by the host runner: with `--previews-on workers` it runs no swarm task, and it is the node whose disk filled (NP-R10). On swarm the scheduled prune adds one global-job excluding self, skipped when the self id is unknown (never unconstrained), and an emergency on another node is a replicated-job pinned to it. A job is create, `service logs --raw`, then `service rm` on every path, on a fresh 30 s ctx: the 10-minute one may be what expired (NP-R5). A job no ready, active node can run waits forever, so the global one needs such a node besides self and the pinned one needs its own; otherwise it is skipped.
── WHAT IS SAID ────────────────────────────────────────────────────────────────────────────────
`node.pruned` once per node that reported, `0` included; a failed prune reports nothing and sends nothing; the log gets docker's first stderr line. `node` is null on compose (NP-R15), where the script's `-` is selfKey. Memory only (invariant 10): /api/stats shows the newest per node, and a restart forgets them.
The two routes that carry a host's whole configuration — `GET /api/config` exports it, `POST /api/config` applies one. Everything else in this package is a route over ONE thing; these two are a route over EVERY secret the host holds, so the rules below are not the same rules.
── ROOT TOKEN ONLY. NOT AN ADMIN SESSION. THIS IS DELIBERATE ────────────────────────────────────
`mayMoveConfig` admits `auth.KindRoot` and nothing else. Every other admin-gated route in this package admits an admin browser session too — the admin rows in permissions.go, and mayApplySealedConfig below for the session-admitting shape. Copying that shape onto the export or the plaintext import would be the single worst change anyone could make to this file:
- GET returns argon2 password hashes, API-token hashes, every host secret, every notifier signing secret, the SSO client secret and every registry password, in plaintext. Reachable from a session cookie, one XSS in the UI — or one stolen laptop with a live session — is a complete credential exfiltration of the host, silently, from the victim's own browser.
- POST writes registry credentials, so the same cookie repoints where this host pulls images from.
The cost is real and was accepted: there is no button in the UI, and there never should be. A browser session is a human at a keyboard; `PSTACK_TOKEN` is the machine credential an operator deliberately put on a machine. Only the second one moves credentials. If you are here to "fix the inconsistency" with the other admin routes: the inconsistency is the security control.
── THE OTHER HALF OF THE GATE IS INVARIANT 9 ───────────────────────────────────────────────────
`principal()` returns `KindRoot` for EVERY request when `s.opts.Token == ""` — the loopback dev mode. On this route that means an unauthenticated GET returns the whole credential dump. What stops that being a hole is invariant 9 in `internal/cli`: with no `PSTACK_TOKEN` the listener is forced to 127.0.0.1, and an explicit non-loopback `PSTACK_HOST` is a hard exit 3 rather than a silent downgrade. This is the route where that interlock is the ONLY thing between an anonymous request and every secret on the host. Weaken it and you weaken this.
── WHAT REACHES A NOTIFIER, AND WHAT NEVER DOES ────────────────────────────────────────────────
Both routes emit, so a credential dump is visible rather than silent — that is the point of the events, and they are emitted BEFORE the response is written so a client that disconnects mid-body cannot suppress them (`Emit` is synchronous, in-order, and individually recovered).
The payloads carry COUNTS AND IDENTITIES ONLY. `Document.Trusts()` returns credentials — for a chat notifier the webhook URL *is* the secret — so it goes in the HTTP response body, which travels over TLS to a caller that already holds the plaintext, and NEVER into an event. An event body is POSTed to every subscribed notifier; putting a Slack URL in one is invariant 15's named failure (`docs/secret-exposure.md`), and `events.Event.Data`'s own comment says nothing secret goes in. Registry HOSTNAMES and notifier names/types are in the import event on purpose: they are what an operator needs to notice a hostile file, and neither is a credential.
`GET /api/control/runtime` and `POST /api/control/restart` — the control stack, visible.
Every other runtime page shows a deployment; this one shows the machinery that serves them: traefik, pstack itself, the optional advanced UI. The fields that earn the page are restart count and OOM-killed — a Traefik restart wipes its in-memory ACME challenge tokens, so certificates stop issuing while everything reports healthy, and until this page the only witness was a default certificate's notBefore timestamp.
The restart is scoped by a refusal, not a role: even root may not restart `pstack` through the API, because it is the container answering the request — inspect.RestartControlService owns the rule and the sentence. Everything else here is maintainer's, like the other host-configuration surfaces (permissions.go).
`/api/custom-routes` — a stable alias for a stack. Route `checkout` assigned to the deployment of stack `myapp-pr-123` makes `web-myapp-pr-123.<domain>` also answer on `web-checkout.<domain>`, with no redeploy (internal/routing/customroutes.go renders the routers).
The custom_routes table is the source of truth; pstack-routes.yml is derived from it. Every write that changes an assignment re-renders the file and rebuilds the sleep index.
THE WRITE SHAPE, the same as removeDeployment's: writeMu, then every check (they resolve specs, which reads host vars from the store — never inside store.Tx, rule 16), then the Tx holding store calls only, then the render, then unlock, then Emit. writeMu makes the check-then-act safe: every write to the table runs under it.
Developer, like the deployments they point at. Share principals never reach this (invariant 16).
`/api/domains` — the additional hostnames this host answers on, added and removed at runtime.
The motivation is a domain migration you can perform gradually: register the new domain, point a deployment at it by setting `PREVIEW_DOMAIN` in its vars, watch it, move the next one. Nothing is re-rendered and nothing restarts — the routers land in Traefik's watched directory and take effect in about two seconds (internal/routing/domains.go explains why that is safe).
WHAT THIS ROUTE DOES NOT DO, deliberately: it does not move any deployment. A preview's hostname comes from its own spec's PREVIEW_DOMAIN, which is already per-deployment and already editable — so the migration's unit is one deployment, and its rollback is that same deployment. Registering a domain only makes the host able to SERVE and WAKE names under it.
Maintainer, like the other host-configuration surfaces and like the routing files this writes.
`/api/forward` — the setting that sends this host's deploys and unserved visitors to another pstack (forward.go). Maintainer reads; admin writes, for blast radius: it decides where every deploy runs (permissions.go).
The token goes in and never comes back out (invariant 15): not in a read, an event, a log line or an error. PUT checks B before saving anything, and any failed check answers 400 naming it.
Grafana at G = https://grafana.<domain> (`pstack init --logging loki`), signed in with pstack accounts. Spec of record: docs/loki-logging-design.md, "Slice 3".
── IS IT ON ─────────────────────────────────────────────────────────────────────────────────────
Read from docker (inspect.GrafanaOn) and cached in s.grafana by Start and reindexLoop, via grafanaCheckIn, which keeps the last known value when docker does not answer. It is never a setting and never asked per request, so a `pstack logging` switch shows within 30 s (the next reindexLoop tick), with no pstack restart. Sign-in also needs PSTACK_DOMAIN (every URL here is built from config, never from a request header) and PSTACK_TOKEN (the cookie's MAC key). When off, /api/health has no `grafana` key.
Sign-in. Traefik's forwardAuth asks verify about EVERY request to grafana.<domain>, and verify answers from __Host-pstack_grafana alone: never pstack_session, never a bearer, never principal(). That cookie is `<id_hash>.<mac>`, the parent pstack session's stored hash signed with PSTACK_TOKEN under a "pstack-grafana\n" prefix: the share-link precedent, so there is no table, and the session row IS the Grafana session (a pstack sign-out ends Grafana access on the next request). Getting the cookie is a redirect sign-in: verify sets a state cookie and sends a top-level navigation to start on control.<domain>; start parks a 60 s single-use code; the callback is a branch of verify, because forwardAuth relays a 302 and its Set-Cookie. Roles: developer and maintainer are Editor, admin is Admin, and viewers are refused (owner, 2026-09-15): a Grafana Viewer still queries Loki's unredacted lines.
`/api/logging` — Loki's settings: retention and chunks, and where chunks are stored.
THE ROW IS WHAT AN OPERATOR SAVED, NOT WHAT LOKI RUNS (invariant 10). Loki runs control/loki/config.yaml and its container. Once a save exists the API owns that file's content, the way it owns pstack-domains.yml; init only creates it. A hand edit is reverted by the next apply or pstack start, except that no live schema period is ever dropped (loki.CheckPeriods).
A save is a `loki-apply` job on the pstack-control key (loki_apply.go): render, -verify-config, rename, restart Loki only, wait for ready, roll back when it does not come up. Nothing here renders compose or recreates a container (invariant 12); the mount and the env line are init's.
── A PUT, IN ORDER ─────────────────────────────────────────────────────────────────────────────
- Loki here? Docker silent → 503; no `loki` container → 409. BEFORE the body is read, so a bodiless PUT on a logging-off host is a 409.
- No writable config.yaml in LokiDir → 409: pstack's ./loki mount comes from init.
- Parse, then Merge over the stored row with any queued storage save on top. One-way and fixed-field → 409 (sentinels, mapped here); a malformed or out-of-range field → 400 (fail()).
- Storage with S3: pstack must be able to hand Loki's uid the 0600 credentials file → 409.
- Nothing running or queued on the key, nothing pending, nothing changed → 200 {changed: false}. Otherwise the job decides, against the row it reads.
- Storage with S3: the probe, before anything is recorded → 400 when S3 refuses.
- Record the patch (lokiPut) and start the job → 202 {job}.
Steps 3–4 are early refusals, not the authority: the job re-runs them against the row it reads.
── ROLES (permissions.go) ──────────────────────────────────────────────────────────────────────
Retention and chunks are host configuration: maintainer, who can already restart Loki. Storage is ADMIN for BLAST RADIUS, the TLS-wildcard argument: one save sends every node's logs to an outside bucket, and it cannot be undone. Not an access boundary — viewers read logs through the logs routes. Two paths rather than a role check inside a handler, per the settings precedent. The `loki-apply` transcript is viewer-readable and may name the endpoint and bucket in Loki's error lines; only the secret and key id are scrubbed.
The S3 secret has no read path (invariant 15). GET answers `secretSet`, never the mask; an empty, omitted or masked `secretAccessKey` keeps the stored one.
`GET /api/openapi.yaml` and `GET /api/openapi.json` — the API's own description, as served by the binary answering the requests.
── WHY IT IS THE EMBEDDED FILE AND NOT A GENERATED ONE ──────────────────────────────────────────
The same document oascmd-gen reads to generate `pstack api`, embedded verbatim. So the spec a client fetches, the commands the CLI ships, and the routes `routes.go` serves are one artifact checked three ways: `openapi_coverage_test.go` fails when a route has no path or a path has no route, and CI's `generated` job fails when the document moves without the generated code.
A spec assembled at runtime from the route table would be a fourth thing to keep true, and the first one to drift, because nothing would compare it to anything.
── TWO FORMATS, ONE SOURCE ──────────────────────────────────────────────────────────────────────
YAML is the file, byte for byte — no re-serialisation, so comments and key order survive and what you fetch is what the repo holds. JSON is that file parsed by `yamlx` (the same YAML-1.2 reader the specs go through) and re-emitted by `jsonx`, which preserves insertion order via `omap` — so `paths` reads in the order it was written rather than sorted, and a diff between two versions is legible.
Converted ONCE, on first request, not per request and not at init: `pstack up` on a laptop must not pay for a document it will never serve, and a control plane serving it a thousand times must not pay a thousand times.
── UNAUTHENTICATED, LIKE /api/health ────────────────────────────────────────────────────────────
A description of an API is not a secret — every route in it enforces its own auth, the repository is public, and a client generating against it has no token yet by definition. It sits in the pre-gate for the same reason health does.
`GET /api/probe/<id>` — "is this preview serving?", answered WITHOUT a token and WITHOUT depending on the preview's own certificate.
── WHY IT EXISTS ────────────────────────────────────────────────────────────────────────────────
Under HTTP-01 every preview hostname resolves its OWN certificate on its first HTTPS request, so a CI job that polls `https://app-pr-123.example.com` right after a deploy is waiting on ACME, not on the app — and the more stacks a host carries, the more of that waiting there is. This route rides a hostname whose certificate is already warm (the control plane's own, obtained when `init` ran and waited for the healthcheck) and asks the container directly, over `preview-ingress`. The answer is available the moment the container answers, whatever ACME is doing.
The real fix for slow issuance is a wildcard, which is what `--challenge dns01` already does: one router holds `${DOMAIN}` + `*.${DOMAIN}` and every per-PR router inherits it by SNI. This route is not a substitute for that; it is what CI polls in either mode.
── UNAUTHENTICATED, AND THEREFORE DELIBERATELY MUTE ─────────────────────────────────────────────
It sits in the pre-gate beside `/api/health`. `docs/secret-exposure.md` records what unauthenticated reads cost this project once — job outcomes carry captured credentials by design, and for a while anyone could read them — so the rule here is absolute and structural rather than careful:
- **No body. Ever.** Not the upstream's, not an error message, not a byte. `Content-Length: 0` on every path. An endpoint that cannot return content cannot become a data feed, which is the failure mode that finding was about.
- **No upstream headers.** They carry `Set-Cookie`, `Server`, framework banners.
- **No redirects followed.** Otherwise it is an open prober for whatever a preview redirects to.
- **The path is fixed at `/`.** Never taken from the query: a caller-chosen path would reach endpoints a preview's own Traefik middleware protects, from a route that has no auth at all.
What it does disclose, unavoidably and by design: whether a deployment id exists, and whether it is up. That is the question being asked. `PSTACK_PROBE=off` turns the route off for a host that does not want even that much (it then 404s like any unknown path).
── IT NEVER WAKES ANYTHING ──────────────────────────────────────────────────────────────────────
A sleeping stack answers `503 asleep` and stays asleep. `wakeFor` triggers on PREVIEW hostnames and this route is reached on the control plane's, so it is not in that path to begin with — but the sleep record is checked explicitly all the same, because an unauthenticated route that starts a `docker compose up` is an unauthenticated deploy, and relying on "the other mechanism happens not to fire here" is not a boundary.
── THE ANSWER IS THE STATUS CODE, THE REASON IS A HEADER ────────────────────────────────────────
`curl -o /dev/null -w '%{http_code}'` is the intended client, so the upstream's status is passed through unchanged — a 404 from the app means the app answered, which is what "is it serving" asks. `x-pstack-probe` says which kind of answer it is, because a 503 the app produced and a 503 meaning "asleep" are different facts:
upstream the container answered; the status is ITS status unknown no such deployment (404) asleep sleeping, and left that way (503) no-target nothing to dial: no router, no port, or not on preview-ingress (503) unresolved the spec would not resolve without request variables (503) unreachable the dial or the read failed, or took longer than the timeout (502) busy too many probes in flight (503)
`/api/scaler` — the worker scaler's settings, its Tofu presets, and the two root-only routes the scaler itself calls (internal/scaler talks to pstack over HTTP only). Maintainer reads; admin writes, for blast radius: a save decides what machines this host pays for (permissions.go).
Credentials go in and never come back out, except through GET /api/scaler/config: root only, gated twice like GET /api/config (routes_config.go's header), because the scaler needs them.
The scaler is the authority on what it owns (/state/scaler.json). Each report's ownership and lock record is mirrored in scaler_config.report so the 409s below hold across a pstack restart; the rest of a report (worker state, last error, orphans …) lives in memory only (W-R2).
The host settings an operator may change at RUNTIME: `GET /api/settings` and `PUT /api/settings/<key>`. internal/settings owns the keys, the validation and the precedence; this file is the HTTP surface and the two things that happen the moment a value changes.
── THE READ SAYS WHERE THE VALUE CAME FROM ─────────────────────────────────────────────────────
Every row carries `source`: "db" (someone set it here), "env" (PSTACK_MAX_JOBS) or "default" (what the binary ships with). Without it a box saying 4 is unexplainable — an operator who typed 8 into it and still sees 4 has no way to tell a rejected write from a stale page from a value their environment is overriding, and "why did my change not stick" is unanswerable.
The SOURCE is computed here, per key, from settings.Usable — the same predicate the readers use for "is this stored row usable", so the two cannot disagree. Comparing the resolved value with the stored text instead would lie about a hand-edited "008", which Atoi accepts and string equality does not. The pressure keys have no environment layer: `db` or `default`.
── A WRITE APPLIES NOW, AND LOWERING THE CAP CANCELS NOTHING ───────────────────────────────────
PUT max_jobs calls jobs.Registry.SetMaxRunning, so the new cap is in force for the next dispatch without restarting the container — the whole point of the feature. Jobs already RUNNING run to completion, so the response says so in words: an operator who types 1 while four jobs run must not read the 200 as "three were just cancelled".
── THE PERMISSION IS PER KEY, AND LIVES IN permissions.go ──────────────────────────────────────
max_jobs is operational (MAINTAINER, with host configuration); default_role is user management by another name (ADMIN, with the promotion paths); the five pressure keys are ADMIN. The rows are exact paths, so a key nobody listed is root's by the table's default-deny — and the chain 404s it, because routes.go dispatches on the seven literals only. `minRole` in the read is taken FROM that table rather than written down again here: a second copy is the drift permissions.go's header exists to prevent.
`GET /api/signals`: what the swarm looks like right now, for whatever adds and removes worker machines. internal/signals asks docker; this file is the HTTP surface and the one piece of memory the feature has.
── THE READ CHANGES NOTHING ────────────────────────────────────────────────────────────────────
It emits no event and starts no work (AGENTS.md's rule for a new route). The ticker below (signalsLoop, started in server.go) is the only thing that raises and clears. A consumer can poll this as often as it likes; the cost is four docker commands.
── emptySince IS THE ONLY STATE ────────────────────────────────────────────────────────────────
A node with no tasks gets a timestamp the first time it is seen that way, and loses it the moment it picks up work. It lives in memory (invariant 10): a restart forgets, so the clock starts again from boot. That errs the safe way — a machine looks busier for longer than it is, never emptier sooner. Whoever reads this decides how long "empty" has to last before acting; pstack has no opinion, because the policy belongs with the thing that pays for the machines.
`GET /api/stats`: what every node's pstack-agent last reported, and the stacks using it. internal/nodestats reads the agent's lines and keeps the samples; this file owns the loop that feeds it, the lock around it, and the HTTP surface. A sibling of routes_signals.go, which stays free of capacity arithmetic.
── THE LOOP ASKS DOCKER, THE ROUTE DOES NOT ────────────────────────────────────────────────────
statsTick runs `docker info` (and `node ls` on a manager) and the agent's logs commands, then records the newest complete batch per node under statsMu, then judges pressure (pressure.go), which emits its edges after the lock, then may start a prune (prune.go), then may sleep one stack (pressureSleep). The route reads only memory (invariant 10: none of this is a table, and a restart forgets it). Reads emit nothing.
── UNKNOWN IS null ─────────────────────────────────────────────────────────────────────────────
- A node with no batch in nodestats.StaleMs is stale: `at` and every reading are null, and `stale` is true. Its `history` is kept: the sparkline shows where it was (invariant 11).
- A docker that does not answer changes nothing: the last tick's node list, self key and orchestrator stay. An active manager whose `node ls` came back empty did not answer either; its own node is always on that list.
── WHICH ROWS ──────────────────────────────────────────────────────────────────────────────────
On swarm, every node `node ls` lists, by hostname, whether or not its agent reported. On a compose host, every node the store has seen (one). `node` is null on compose (NP-R15).
`stacks` sums fresh batches only, by the stack label the agent read. `pstack-control` is a stack like any other: it is real use of the node. A container in no stack is left out.
Wildcard subdomains turned on from the API instead of the spec: per deployment and service here, per custom route in routes_customroutes.go. A deployment's rows (store.DeploymentSubdomains) are merged into its resolved spec by resolveDep, so every consumer (deploy, sleep index, routes) sees one list; a spec entry for the same service wins. A change applies on the next deploy, since the stack's own `-wild` router is a container label.
`/api/tls` — the host's certificate mode, and the bring-your-own wildcard (`dns-persist-01`).
There is deliberately NO stored "desired mode" setting: the mode is DERIVED — a stored wildcard (routing.WildcardYAML present) is `dns-persist-01`, otherwise whatever Traefik's own argv says. A setting could disagree with the artifacts; the artifacts cannot disagree with themselves.
The wildcard PUT takes the pair in plaintext and the key never comes back out (invariant 15) — the GET returns the certificate's public facts only. The write is ADMIN's for BLAST RADIUS, not as a security boundary: it changes what every hostname on the host presents, and the redeploy that follows touches every stack. A maintainer can already reach equivalent power through /api/routing (see permissions.go). Reading the status and running the redeploy loop are maintainer's, like the other host surfaces.
`POST /api/tls/redeploy` is tls-challenge.md's migration loop, server-side: per-PR router labels are stamped at deploy time from the mode the host was in THEN, so entering or leaving a wildcard mode requires each stack to deploy once more. Asleep stacks are skipped — their labels regenerate on wake, and redeploying them here would BE a wake nobody asked for. So are stacks docker does not list (downed, record kept): their next `up` stamps the new labels anyway.
Server: the control plane's remote surface. The route inventory is openapi.yaml plus permissions.go's role table; the rules that matter are in AGENTS.md. While forwarding is on, a preview hostname this host does not serve goes to the other pstack (forward.go), before wake-on-call.
THIS API MUST NEVER MANAGE THE STACK IT RUNS IN (invariant 12). VARIABLES are merged from the request's `?query` (and a PUT's `env`) over the process env, once, at resolve time. SECURITY: every route but health/probe/openapi/login/logout/bootstrap/sso/grafana verify+start is behind the principal gate, and behind THAT a second one — permissions.go, a single ordered (path, method, minimum role) table consulted once at the top of routes(), default-deny, so a route nobody listed is root's. Responses are built field by field and never echo a resolved Stack.Env.
Index ¶
Constants ¶
const ( ReadinessTimeoutMinS = 5 ReadinessTimeoutMaxS = 3600 )
Bounds of the `?timeout=` watch deadline, shared by `POST …/up` and `GET …/readiness`. The max is the job cap: a watch that could outlive every job would report on a stack nothing is driving. The min is over two poll intervals (readiness.PollMs is 2s): the up route's watch runs with Emit:true, and a deadline shorter than the first poll times out a SUCCESSFUL deploy into every notifier.
const SignalsTickDefaultMs = 30_000
SignalsTickDefaultMs is what `serve` uses when PSTACK_SIGNALS_TICK_MS is unset.
const StatsTickDefaultMs = 30_000
StatsTickDefaultMs is what `serve` uses when PSTACK_STATS_TICK_MS is unset: the agent's batch interval.
const WakeRetryMs = 60_000
WakeRetryMs: after a failed wake, how long a request to the hostname waits before trying again.
Variables ¶
This section is empty.
Functions ¶
func CrToNl ¶
CrToNl is CR → NL for terminal input. With no pty there is no line discipline, so this is the only thing standing between "Enter" and a shell that never runs anything. CRLF collapses to ONE NL, or every Enter from a client that sends both would run the line and then an empty one. Same rule for text and binary frames.
Types ¶
type Options ¶
type Options struct {
// DataDir is the registry root; deployments live under <DataDir>/deployments.
DataDir string
Port int
Host string
Token string
// RoutingDir is Traefik's dynamic-config directory. Default: the in-container mount path
// /etc/traefik/dynamic; on a host-side run, <dataDir>/control/traefik-dynamic.
RoutingDir string
// RegistryDir is the DOCKER_CONFIG directory holding private-registry credentials. Default:
// $DOCKER_CONFIG, else /docker-config.
RegistryDir string
// TerminalArgv opens a container shell. Default: docker exec -i <id> <shell>. Injectable for
// the same reason Runner is: the machine this is developed on has no Docker.
TerminalArgv func(containerID, shell string) []string
// SignalsTickMs is how often to compare the swarm with the last comparison and emit the
// difference. ZERO IS OFF, and off is the zero value on purpose: `serve` is the only caller
// that turns it on.
SignalsTickMs int64
// StatsTickMs is how often statsLoop reads the agents' logs (routes_stats.go). Zero is off, like
// SignalsTickMs: only `serve` turns it on.
StatsTickMs int64
// Readiness tuning; zero means the defaults (2s / 180s / 3 restarts).
ReadinessPollMs int64
ReadinessTimeoutMs int64
// ReadinessRestartLoop is the crash-loop threshold. Raise it on a SWARM host: without
// `depends_on`, a dependent legitimately restarts while its database converges.
ReadinessRestartLoop int64
// LokiDir holds Loki's config.yaml and s3-credentials, which the Loki settings routes write.
// Default: <DataDir>/control/loki. serve passes loki.Dir (PSTACK_LOKI_DIR, then /etc/loki).
LokiDir string
// LokiReadyTimeoutMs is how long an apply waits for Loki's /ready. Zero means 300000.
LokiReadyTimeoutMs int64
// LokiUID owns s3-credentials, so Loki can read it. Zero means 10001, grafana/loki's uid.
LokiUID int
// MaxJobs is how many lifecycle jobs RUN AT ONCE across every stack (PSTACK_MAX_JOBS); zero
// means jobs.DefaultMaxRunning. Over the cap an accepted job WAITS for a slot — it is never
// refused. Not to be confused with jobs.MaxJobs, which bounds retained transcripts and is not
// tunable; the env name is the one the operator-facing contract fixed.
//
// It is now the DEFAULT rather than the authority: a `max_jobs` row in the settings table
// outranks it (internal/settings), so an operator who set the cap in the UI is not overridden
// by the container's environment on the next restart, and one who never opened the UI keeps
// exactly this value. PUT /api/settings/max_jobs applies without a restart.
MaxJobs int
// OpenAPISpec is the API's own OpenAPI document, served at `/api/openapi.yaml` and, converted,
// at `/api/openapi.json`. Passed in rather than imported so this package does not depend on the
// root one — the same reason UIHTML and ShareHTML are options. Empty means the two routes 404.
OpenAPISpec []byte
// ProbeOff turns OFF `GET /api/probe/<id>`, the unauthenticated "is this preview serving"
// route (routes_probe.go). Named for the off switch so the ZERO VALUE is the shipped
// behaviour — every caller that does not care, tests included, gets the route without saying
// so, and only `PSTACK_PROBE=off` has to be spelled out.
ProbeOff bool
// Domain is the preview domain (PSTACK_DOMAIN): share links and the SSO callback are built on
// control.<domain>; without it the request's own origin is used.
Domain string
// MetricsURL is Traefik's Prometheus endpoint (PSTACK_TRAEFIK_METRICS). What sleep.idle reads.
MetricsURL string
// Scheduler tuning — a minute on a host, milliseconds in a test.
SchedulerTickMs int64
SchedulerFetch scheduler.Fetcher
// SSO: how long a half-finished sign-in is remembered (default 300s) and how long a provider's
// discovery document is trusted (default 1h). Zero = default.
SSOStateTTLS int64
SSODiscoveryTTLS int64
// Bus defaults to events.Default.
Bus *events.Bus
// Env is the process environment the server hands to hooks and reads variables from; nil
// means os.Environ().
Env map[string]string
// Log receives the scheduler's and the SSO adoption lines (stderr on a host).
Log func(string)
// Version is what /api/health reports.
Version string
// UIHTML and ShareHTML are the two embedded pages.
UIHTML string
}
Options configure a server.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is one running control plane.
Owner of writeMu: the registry/spec mutations that were racy check-then-acts in the reference (PUT/DELETE deployment, DELETE spec, the sleep record). Everything else has its own owner.
type Tuning ¶
type Tuning struct {
ReadinessPollMs float64
ReadinessTimeoutMs float64
ReadinessRestartLoop float64
SSOStateTTLS float64
SSODiscoveryTTLS float64
// MaxJobs is PSTACK_MAX_JOBS: how many lifecycle jobs RUN AT ONCE across every stack, zero
// meaning jobs.DefaultMaxRunning. It is NOT jobs.MaxJobs — that one bounds how many finished
// transcripts are kept and is not tunable. One letter apart in name, nothing in common.
MaxJobs float64
// PSTACK_LOKI_READY_TIMEOUT_MS and PSTACK_LOKI_UID. 0 means the default (300000, 10001), so
// PSTACK_LOKI_UID=0 is 10001: a root pstack chowns s3-credentials to 10001 either way.
LokiReadyTimeoutMs float64
LokiUID float64
// SignalsTickMs is PSTACK_SIGNALS_TICK_MS: how often the swarm is compared with the last
// comparison so `signal.raised` / `signal.cleared` can be sent. It does NOT go through num(),
// which cannot tell an unset variable from an explicit "0" — and an explicit 0, meaning "never
// tick", is exactly what the conformance harness sets. SignalsTickSet says which it was.
SignalsTickMs float64
SignalsTickSet bool
// StatsTickMs is PSTACK_STATS_TICK_MS: how often the node agents' logs are read. Parsed exactly
// like the signals pair, explicit 0 included.
StatsTickMs float64
StatsTickSet bool
}
Tuning is what `serve` reads from the environment: the same knobs a test passes as options, so a black-box harness driving the real CLI can reach the expiry paths. `??` semantics — unset means the default, and a value that is not a positive number is ignored rather than turning a timeout into NaN.
Source Files
¶
- body.go
- customroutes_target.go
- forward.go
- http.go
- loki_apply.go
- permissions.go
- pressure.go
- principal.go
- prune.go
- routes.go
- routes_auth.go
- routes_config.go
- routes_control.go
- routes_customroutes.go
- routes_deploy.go
- routes_domains.go
- routes_forward.go
- routes_grafana.go
- routes_logging.go
- routes_openapi.go
- routes_probe.go
- routes_scaler.go
- routes_settings.go
- routes_signals.go
- routes_stats.go
- routes_subdomains.go
- routes_tls.go
- server.go
- sse.go
- ws.go