Documentation
¶
Overview ¶
`pstack api …` — every HTTP route as a command, generated from `packages/pstack/api/openapi.yaml`.
── WHY THIS IS THE ONE COBRA SUBTREE IN A HAND-ROLLED CLI ───────────────────────────────────────
The rest of `pstack` is parsed by the positional walker in args.go, deliberately: flags may appear anywhere, `--ui` peeks ahead, and `cli-goldens.test.ts` pins the usage text byte for byte. Cobra cannot reproduce any of that, so it never owns the root. It owns exactly the `api` subtree, which has none of those constraints because nobody has typed it before.
The split is enforced by INTERCEPTION, not by cooperation: `run` hands the whole tail to this function before `ParseArgs` sees a single token. Otherwise `pstack api deployments up --id pr-1` would be parsed as the verb `api` with three unknown arguments, and the walker would refuse it with a message about a spec file.
── THE COMMANDS ARE NOT WRITTEN HERE, AND THAT IS THE POINT ─────────────────────────────────────
`zz_generated.go` is produced by oascmd-gen from the OpenAPI document and carries a lock file, so a route that changes shape either regenerates cleanly or is reported as a BREAKING change to a command somebody may have scripted. Hand-writing sixty-nine subcommands would reproduce every path, method, parameter and enum a second time and let them drift — which is the same argument docs/README.md makes about route tables in prose.
── ADDRESSING AND CREDENTIALS ARE THE ONES THAT ALREADY EXISTED ─────────────────────────────────
`PSTACK_API_URL` and `PSTACK_TOKEN`, resolved by the same `apiBase` that `pull config` and `push config` use — including its refusals: no default URL (a guess talks to the wrong host) and no plain http off a private address. Viper would be a third configuration mechanism beside the `Tuning` env reader and that pair, for values that are already one lookup each.
The token is checked HERE rather than inside apiBase's config-specific sentence, because most of these routes are not root-only — a personal token at the right role is the normal credential, and telling somebody they need the root token to list deployments would be false.
Package cli is argv, dispatch and exit codes. Logic belongs in the modules, not here.
The parser is hand-rolled and positional: flags may appear ANYWHERE, including after the command word, `--ui` peeks ahead (a switch for build-image, a value for init), and unrecognised positional words accumulate into `cmd` and `sub`. Go's `flag` stops at the first non-flag argument and cobra would own the usage text — both would change observable behaviour that the CLI goldens pin.
PER-COMMAND HELP AND SHELL COMPLETION, from one table.
`pstack --help` prints the whole manual — every command, so a reader who does not yet know the vocabulary can find it. That text is a golden and stays exactly as it was. What was missing is the other direction: someone who knows they want `init` and needs only its flags, and a shell that can finish a word.
Both come from `commandHelp` below, and that is the point of the file: a command's flags are spelled ONCE. A completion script listing a flag the help does not describe — or the reverse — is the drift this repo refuses everywhere else, and it is the failure nobody notices, because a missing completion looks like a shell that has not been reloaded.
`commands_test.go` walks `Commands` and fails when an entry is missing, so a new command cannot ship with no help of its own.
SHELL COMPLETION — `pstack completion bash|zsh|fish`.
Generated from the same table `pstack <cmd> --help` reads (commands.go), so a flag the shell offers is a flag the help describes. A hand-written completion script is the classic thing that rots: nobody notices a MISSING completion (it reads as "my shell needs reloading"), so it drifts silently until it is wrong about everything.
STATIC ONLY, deliberately. A shell could complete deployment ids by calling the API, but that would mean every TAB press making an authenticated HTTP request to a host that may be down, slow, or not configured in this terminal — a shell that hangs on TAB is worse than one that completes nothing. Commands, subcommands and flags are what a shell can know for free.
THE SILENT-REVERT GUARD on `pstack init`.
`init` renders the control stack from its ARGUMENTS ALONE — it reads nothing back — so every flag left off takes that flag's DEFAULT, host-wide, without saying so. That is not a hypothetical: it is the single largest source of upgrade incidents this project has had.
· a run without PSTACK_TOKEN MINTS A NEW ONE, and every CI job holding the old one starts getting 401s. `pstack upgrade` exists because of this. · a run without `--ui advanced` reverts an advanced host to the basic UI, deleting the SPA container. · a run without PSTACK_DNS_TOKEN on a dns01 host rewrites `dns.env` BLANK, and the wildcard's renewal then fails weeks later, silently. · a run without `--challenge dns01` flips a wildcard host to per-hostname issuance, which burns the weekly rate limit and cannot be undone by re-running. · a run without `--logging loki` on a Loki host removes Loki; one without PSTACK_LOKI_PASSWORD mints a new push password, and every running container's pushes are refused until redeployed. · a run without `--scaler on` on a scaler host removes the scaler, stranding the workers it owns.
Every one of those is an OMISSION, never a wrong value: the operator did not ask for the change and is not told about it. So that is exactly what this refuses, and nothing else.
── WHAT IT DOES NOT DO ──────────────────────────────────────────────────────────────────────────
A flag you SPELLED is a decision, and passes through untouched — `--challenge dns01` on an http01 host is the documented way to switch modes. A first `init` has nothing to compare against. And `pstack upgrade` re-runs `init` with every value read back from the host, so it never trips this.
The guard is here rather than in initctl because reading the host's current state lives in `upgrade`, which already imports initctl — the other direction would be a cycle.
Index ¶
- Constants
- Variables
- func CommandHelp(cmd string) string
- func IsCommand(name string) bool
- func IsSpecCommand(name string) bool
- func ParseArgs(argv []string, env func(string) (string, bool)) (*Parsed, *Exit)
- func Run(argv []string, io IO) int
- func Usage(version string) string
- type Exit
- type IO
- type Parsed
- type ServeOptions
Constants ¶
const ( ExitOK = 0 ExitFailed = 1 ExitLeaked = 2 ExitUsage = 3 )
Exit codes. The distinct code for leaks lets CI treat "torn down but leaked" differently from "teardown errored", which are different problems with different owners.
Variables ¶
var Commands = append(append([]string{}, SpecCommands...), "init", "serve", "build-image", "cloud-init", "dockerfile", "upgrade", "ui", "logging", "swarm", "pull", "push", "route", "forward", "migrate", "scaler", "healthcheck", "api", "completion")
Commands in usage order.
var Shells = []string{"bash", "zsh", "fish"}
Shells is what `completion` accepts, in the order the usage lists them.
var SpecCommands = []string{"up", "down", "verify", "status", "validate"}
SpecCommands read a spec; Commands is every command that exists. An unknown command must fail as unknown, never by hunting for a spec file — that bug shipped once.
Functions ¶
func CommandHelp ¶ added in v0.38.0
CommandHelp is the page for one command, or "" when it has none.
func IsSpecCommand ¶
IsSpecCommand reports whether name reads a spec.
Types ¶
type Exit ¶
type Exit struct {
Code int
// Msg is printed to stderr prefixed with `pstack: ` when non-empty.
Msg string
}
Exit is how a command ends: a code and an optional stderr line (`pstack: <msg>`).
func Completion ¶ added in v0.38.0
Completion is the script for one shell, or a usage error naming the ones that exist.
func Healthcheck ¶
Healthcheck is the container's HEALTHCHECK: one GET against this process's own /api/health, exit 0 or 1. `init` blocks on this verdict, so it must be boring.
func Serve ¶
func Serve(o ServeOptions) *Exit
Serve is `pstack serve`. Blocks until SIGINT/SIGTERM, then stops the server.
func UnknownCommand ¶
UnknownCommand is the refusal for a command this build does not have.
type IO ¶
type IO struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
Env func(string) (string, bool)
// Environ is the whole environment as a map (what hooks inherit); nil means os.Environ().
Environ map[string]string
// UIHTML and ShareHTML are the embedded pages `serve` hosts.
UIHTML string
// OpenAPISpec is the embedded OpenAPI document `serve` publishes.
OpenAPISpec []byte
}
IO is the process's streams and environment, so a test can drive Run without a process.
type Parsed ¶
type Parsed struct {
Cmd string
Sub string
File string
DryRun bool
Level exec.Level
Overrides map[string]string
OverrideKeys []string
NoVerify bool
Force bool
Domain string
AcmeEmail string
DNSProvider string
Challenge string // http01 | dns01
Orchestrator string // swarm | compose
Logging string // none | loki
Scaler string // on | off
// IngressSubnet / SharedSubnet are the two networks' address ranges under swarm. "" = nobody
// asked: init keeps an existing network and gives a new one the default. Normalised CIDR.
IngressSubnet string
// PreviewsOn is where previews may run under swarm: workers | any. "" = nobody asked, and the
// manager's availability is left as it is.
PreviewsOn string
// Arg is the third word: `pstack swarm previews <workers|any>`.
Arg string
// Extra is every positional word after Arg: `pstack route assign <name> <deployment>`.
Extra []string
Distro string
Format string
Tag string
UI string // basic | advanced | hearth
UIImage bool
UIDist string
SSHKey string
Password string
// AdminUser / AdminPassword / APIToken are cloud-init's credential flags. Deliberately WITHOUT
// environment defaults, unlike --password (PSTACK_DASHBOARD_PASSWORD) beside them: an operator's
// shell has PSTACK_TOKEN set precisely because it is talking to a host that already exists, and a
// default would silently clone that host's bearer token into a new host's user-data. The pair
// follows the token because they are the same decision — the credentials of one specific host.
AdminUser string
AdminPassword string
APIToken string
ConfigRepo string
// Config / ConfigURL are cloud-init's two ways to carry a `pull config` export onto a new host:
// the sealed file itself, or a URL the host fetches at boot. Mutually exclusive, and both need
// PSTACK_CONFIG_KEY — see cloudInit().
//
// The PASSPHRASE is deliberately not here and has no flag anywhere: argv is world-readable
// through `ps`, so it comes from PSTACK_CONFIG_KEY or a no-echo prompt. Keeping it out of this
// struct also keeps it out of the `t.Errorf("got %+v", p)` that every parser test does.
Config string
ConfigURL string
// ExtraDomains is `--extra-domain` (repeatable): additional hostnames this host answers on, in
// place from the first boot rather than added afterwards.
//
// The case it exists for: the domain you actually want is still pointing at the OLD host, so you
// stand up the new one with that domain as the primary — its routers exist immediately and start
// working the moment DNS moves — and a temporary domain here to use meanwhile.
//
// It only ever ADDS. `init` merges these into whatever /api/domains already holds, because
// removing a domain the operator added through the UI on a re-run would be exactly the silent
// revert the guard exists to refuse.
ExtraDomains []string
// DNSTokenFile is `--dns-token-file`: the PATH to the DNS-01 credential, never the credential.
// Same reasoning as the passphrase above — a secret in argv is readable by every user on the
// box through `ps` for as long as the process lives. A path is not a secret, so it may travel
// here; what it points at never enters this struct.
DNSTokenFile string
Out string
// In is `-i` — the file `push config` reads. The counterpart of Out.
In string
Yes bool
To string
Resume bool
// From / Via / SleepSource are migrate's and forward's addressing: per-invocation, so no env
// default (route's flags and upgrade --to are the precedent). Their tokens are env-only.
From string
Via string
SleepSource bool
// JSON is `--json`: print the API's body instead of the terse lines (`route`).
JSON bool
// Typed records which value flags were spelled on the command line, for the commands that
// must only act on an EXPLICIT --ui / --orchestrator (upgrade, ui).
Typed map[string]bool
// Help and Version short-circuit dispatch.
Help bool
Version bool
}
Parsed is argv, resolved against the environment defaults.
type ServeOptions ¶
type ServeOptions struct {
UIHTML string
// OpenAPISpec is the embedded OpenAPI document, served at /api/openapi.{yaml,json}.
OpenAPISpec []byte
Stdout io.Writer
Stderr io.Writer
// Env is the process environment (os.LookupEnv-shaped); nil means the real one.
Env func(string) (string, bool)
}
ServeOptions are what the binary hands `serve`: the two embedded pages and the streams.