Documentation
¶
Overview ¶
Package initctl is `pstack init` — stand up the CONTROL stack on a host.
── WHY THIS LIVES IN THE CLI AND NOT IN THE API ──────────────────────────────────────────────
host (systemd / CLI)
└─ pstack init ──▶ CONTROL stack: traefik + pstack (API + UI)
│ manages
▼
shared + isolated deployments
The running API manages every OTHER deployment. It must never manage the stack it is running in, because `up` on that project recreates the pstack container — killing the process halfway through the operation it was performing. The request never returns, the job transcript is lost with the process (job history is in-memory, invariant 10), and if the new image is broken the host is left with no control plane and no remote way to fix it: the only thing that could have repaired it was the thing that just died. So self-management is not a feature with a caveat, it is a way to brick a host from a browser tab.
The host keeps that power. `init` runs over SSH, from systemd, or from CI-with-a-key — always from OUTSIDE the containers it is recreating, which is the only place a failed upgrade is recoverable.
Everything here is idempotent: re-running `init` is the supported way to change the domain, rotate the token, or move to a new image.
Init also replaces pstack-agent, the node reporter (step 5b, internal/nodestats), and is its only creator (invariant 12): never the API, since the agent's service and containers are host state like the control stack.
Index ¶
- Constants
- Variables
- func AcmeChallengeArgs(challenge Challenge, provider string) string
- func AcmeRouterLabels(challenge Challenge) string
- func AdvancedUIService(ui UI) string
- func ControlUIService(ui UI) string
- func GrafanaService(logging Logging, challenge Challenge) string
- func Init(opts Options) error
- func LokiService(logging Logging, challenge Challenge, password string) string
- func LokiWiring(template string, logging Logging) (string, error)
- func ScalerService(on bool) string
- func ScalerWiring(template string, on bool) (string, error)
- func SwarmProviderArgs(orchestrator spec.Orchestrator) string
- func WakeRouterLabels(domain string) string
- type Challenge
- type Logging
- type Options
- type UI
Constants ¶
const ( DefaultIngressSubnet = "10.250.0.0/16" )
The two networks' address ranges under swarm, when nobody chose one.
Docker's default for a swarm overlay network is a /24 — about 250 addresses — and every routed service in every preview takes at least one there, plus one per machine in the swarm. A busy host fills that honestly, and swarm also hands out addresses it never takes back: on one 0.39.0 host the /24 filled in nine days, and every routed service after that sat in `New` forever with the reason only in docker's own log (docs/preview-ingress-address-leak.md). A /16 is 65,534.
Both sit inside swarm's default address pool (10.0.0.0/8) on purpose: a range docker manages is one it will not hand to another network later, where a range outside it could collide with the host's own LAN or docker's local bridges.
const ( HTTP01 Challenge = "http01" DNS01 Challenge = "dns01" Basic UI = "basic" Advanced UI = "advanced" Hearth UI = "hearth" LoggingNone Logging = "none" Loki Logging = "loki" )
const ControlProject = "pstack-control"
ControlProject is the control stack's compose project name. Exported because the API reads it to SHOW the control stack's status — never to act on it. Keep it stable: it is how an operator finds the stack with `docker compose -p pstack-control …`.
const DaemonOOMScoreAdjust = -900
DaemonOOMScoreAdjust is dockerd's oom_score_adj: well below every container's 0, so the kernel takes a preview's process first. Not -1000, which would exempt it from the killer entirely.
const GrafanaVersion = "13.2.1"
GrafanaVersion is the Grafana image tag. Here, not beside swarm.LokiVersion: swarm needs Loki's tag for the plugin install line, and nothing in swarm uses Grafana.
const PushURLLabel = "pstack.logging.push-url"
PushURLLabel is the label on the control stack's loki container that carries the push URL. Deploys read it off the RUNNING container, the way DetectChallenge reads Traefik's flags, so `pstack up` on the host and the API always agree and there is no setting to keep in step. The one spelling of the key.
const UILabel = "pstack.ui"
UILabel is the label on a hearth `advanced-ui` container that names it. Both container UIs share the service name, so the API reads this to tell them apart; advanced carries none.
Variables ¶
var DNSTokenVar = map[string]string{
"cloudflare": "CF_DNS_API_TOKEN",
"hetzner": "HETZNER_API_TOKEN",
"route53": "",
"gcloud": "",
}
DNSTokenVar is lego's DNS-01 credential variable, per provider — the name Traefik expects the token under.
ONLY the providers verified in `docs/bootstrap.md` §3 are listed. A wrong variable name fails as "propagation timeout", which sends you debugging DNS instead of a typo, so an unknown provider gets a CHANGEME line pointing at lego's list rather than a guess.
"" (the TS's `null`) means the provider is *tokenless*: AWS satisfies the credential chain from an instance profile and GCP from the VM's attached service account, so there is nothing to write, nothing on disk, and nothing to rotate. Prefer those where you have the choice. Presence in the map is the "known" test; a lookup table, never ranged into output.
Functions ¶
func AcmeChallengeArgs ¶
AcmeChallengeArgs is Traefik's ACME challenge flags for the chosen mode, at the template's indentation.
HTTP-01 needs no credential: Traefik answers on the `web` entrypoint over port 80. The web→websecure redirect does NOT break it — Traefik installs an internal ACME router at maximum priority that bypasses the redirect for `/.well-known/acme-challenge/`. Port 80 must be reachable from the internet, which is the one hard requirement.
func AcmeRouterLabels ¶
AcmeRouterLabels is the TLS labels on the control router.
dns01 requests ONE wildcard from a single always-on router; every other router (including every per-PR one) sets `tls=true` alone and inherits it by SNI. Adding `certresolver` to another router makes Traefik order a SEPARATE certificate for it — the rate-limit trap.
http01 cannot do wildcards at all, so each router resolves its own certificate on first request.
func AdvancedUIService ¶
AdvancedUIService is the optional advanced-UI container. Omitted entirely in basic mode — not merely disabled.
The service is named `advanced-ui` in both container modes: routing, the domains API and upgrade detection all target that name, and only the image differs.
func ControlUIService ¶
ControlUIService is which Traefik service `control.<domain>` routes to.
The ROUTER stays on the pstack container in both modes so the TLS labels render identically; only its target changes. Traefik happily lets a router declared on one container reference a loadbalancer service declared on another, which keeps this a one-line swap.
func GrafanaService ¶ added in v0.40.0
GrafanaService is the Grafana container, appended after LokiService at the same marker and, like it, omitted entirely unless logging is loki: Loki's query API is on the logs network only, so Grafana is how its logs are read. Sign-in is pstack's. Traefik's forwardAuth asks pstack about every request and Grafana trusts the two headers pstack answers with, so the network, the stripped headers and the router priority below are the whole of its auth. The block's comments say why each one holds.
func LokiService ¶ added in v0.40.0
LokiService is the opt-in Loki container, appended after the advanced UI at the same marker. Omitted entirely unless logging is loki: the template gains no line of its own, so every host without it renders byte-identical.
Pushes arrive through Traefik's websecure entrypoint, and Traefik is the only other member of the `logs` network. The password is hashed HERE because compose cannot hash: `{SHA}`, not bcrypt, because Traefik checks it on every push — about one per container per second — and a 128-bit random secret needs no slow hash. The discovery label keeps `${LOKI_PUSH_PASSWORD}` for compose to fill from .env, so the password itself is never in this file.
func LokiWiring ¶ added in v0.40.0
LokiWiring is the rest of Loki's plumbing: Traefik joins the `logs` network, and the file declares the `loki` and `grafana` volumes and that network. Literal edits of lines the template already has, not new markers — every marker leaves a line behind when it renders "off", so a new one would change the compose file of every existing host.
Each anchor is checked before it is replaced (strings.Replace with n=1, rule 8), so a template edit that moves one fails init by name instead of rendering a Loki that Traefik cannot reach. The networks anchor is checked inside `haystack`, scoped to Traefik's own block: the advanced UI's identical networks line would otherwise stand in for a Traefik line a template edit actually removed, passing the check and then getting edited in Traefik's place. Ordered, never a map (rule 5): the first missing anchor is the one named.
func ScalerService ¶ added in v0.46.0
ScalerService is the opt-in worker scaler, appended after Grafana at the same marker. Omitted entirely when off, so every host without it renders byte-identical.
func ScalerWiring ¶ added in v0.46.0
ScalerWiring is LokiWiring for the scaler: pstack joins the `scaler` network and the file declares it. Run after LokiWiring, so `scaler: {}` lands between `preview-shared` and `logs`. The networks anchor is checked inside pstack's own block, for traefikBlock's reason.
func SwarmProviderArgs ¶
func SwarmProviderArgs(orchestrator spec.Orchestrator) string
SwarmProviderArgs is Traefik's swarm provider, in swarm mode only. Both providers run: docker for the control stack's own containers (and any compose-mode preview), swarm for the stacks. `exposedbydefault=false` on both for the same reason — routing is opt-in.
func WakeRouterLabels ¶
WakeRouterLabels is the catch-all router for wake-on-call. A Go regexp over any depth under the domain, so a sleeping stack's subdomain subtree (`a.web-pr-1.<d>`) wakes it too; the exact control routers still win on priority; `$$` is how a literal `$` survives compose's interpolation of this file, and the dots are escaped here (the template cannot, it only knows `${DOMAIN}`).
Types ¶
type Logging ¶ added in v0.40.0
type Logging string
Logging is where preview containers' logs go. "" counts as LoggingNone.
type Options ¶
type Options struct {
// DataDir is where the control plane keeps its state — the same path the API reads as PSTACK_DATA.
DataDir string
// Domain is the apex of the preview domain, e.g. `preview.example.com`. The UI lands on `control.<domain>`.
Domain string
// AcmeEmail is the ACME registration address. Let's Encrypt mails expiry warnings here.
AcmeEmail string
// Challenge is how Let's Encrypt verifies the domain.
//
// http01 DEFAULT. Zero credentials — Traefik answers a challenge on port 80. Works the
// moment DNS points at the box. CANNOT issue wildcards, so every hostname gets its
// own certificate, and Let's Encrypt allows only ~50 new certificates per registered
// domain per week. At 3 surfaces per PR that is ~16 PRs/week. It also cannot cover a
// hostname before its container exists, so a not-yet-deployed preview URL has no cert.
// dns01 One wildcard covers every present and future `*.<domain>` host: no per-PR issuance,
// no rate-limit ceiling, and a URL is valid before the stack is deployed. Costs a DNS
// API credential to obtain, store and rotate.
//
// Start on http01; move to dns01 when PR volume or pre-deploy URLs demand it.
Challenge Challenge
// UI is which web UI `control.<domain>` serves.
//
// basic DEFAULT. The UI embedded in the API bundle — no extra container, nothing else to
// build or pull. Enough to submit a deployment and watch a job.
// advanced The standalone SPA (@samyx/preview-stacks-ui) as its OWN container, which the
// control stack gains a service for. Richer, but one more image to build and keep
// current, so it is opt-in rather than the default.
// hearth The same, built on Hearth UI (@samyx/preview-stacks-ui-hearth). Same service name
// and routing as advanced; only the image differs (PSTACK_UI_HEARTH_IMAGE).
//
// Whichever is chosen, the API keeps serving the basic UI on `api.<domain>`, so a broken advanced image
// never leaves the host with no usable interface.
UI UI
// Orchestrator is how previews are deployed on this host.
//
// swarm DEFAULT for a new host. This daemon becomes a one-node swarm manager; previews deploy
// as swarm stacks; workers can join later from the swarm panel. The control stack
// itself stays a plain compose project on the manager (it must never depend on the
// orchestrator it manages), and the two external networks become attachable overlays
// so its containers reach tasks on any node.
// compose What every host before 0.26.0 ran. `pstack upgrade` keeps it: switching an existing
// host means recreating its networks, which needs every preview torn down first.
Orchestrator spec.Orchestrator
// Logging is where this host's previews' logs go.
//
// none DEFAULT ("" counts as none). The control stack and every deploy stay exactly what they
// were. .env still keeps LOKI_PUSH_PASSWORD if PSTACK_LOKI_PASSWORD is set, so a value
// survives `pstack logging off` for `pstack logging loki` to reuse.
// loki A Loki service in the control stack, reachable only at loki.<domain>'s push path; its log
// plugin on this node; a push password in .env. Deploys give every service without its
// own `logging:` the loki driver.
Logging Logging
// Scaler adds the worker scaler service, its `scaler` network and <data>/scaler (0700). Swarm only.
Scaler bool
// DNSProvider is the lego DNS-01 provider code, e.g. `cloudflare`. Required for, and only used by, `dns01`.
DNSProvider string
// Token is the DNS-01 API token, and ONLY that — it is written to `dns.env` for Traefik and
// never reused as the API's bearer token. Two different secrets, two different blast radii:
// this one can edit a DNS zone, PSTACK_TOKEN can start privileged containers. Omit it for the
// tokenless providers (route53, gcloud), which authenticate from the instance's own identity.
Token string
// DryRun: change nothing — print what would happen. Must match the flag the runner was built with.
DryRun bool
// Runner is from exec.New, so `--dry-run` behaves exactly as it does everywhere else.
Runner exec.Runner
// Out is where init's own lines go (stdout when nil). Pass the runner's Out so a dry-run
// transcript interleaves in order.
Out io.Writer
// IngressSubnet and SharedSubnet are the networks' address ranges under swarm. "" means "nobody
// asked": a new network gets the default above and an existing one is KEPT as it is, so
// `pstack upgrade` never recreates a network on its own. A value is a request: a network whose
// range differs is recreated, which needs every preview off it first.
IngressSubnet string
// PreviewsOn is `workers` (label this manager off: control stack only), `any` (undo that) or ""
// (nobody asked: availability is left alone, so `pstack upgrade` never changes it). Swarm only.
PreviewsOn string
// NoOOMProtect skips the dockerd oom_score_adj step (PSTACK_NO_OOM_PROTECT). For a host that
// manages docker.service itself, and for every test that runs init as root.
NoOOMProtect bool
// AgentImage is the image pstack-agent runs in; "" is nodestats.AgentImage. From PSTACK_AGENT_IMAGE
// only: no flag, no .env line, and `pstack upgrade` does not read it back, so an override must be
// re-exported on every init and upgrade. Cloud-init does not pass it (NP-R6).
AgentImage string
}
Options are init's inputs.