routing

package
v0.45.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: MIT, MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

CUSTOM ROUTES: a stable alias for a stack. Route `checkout` on stack `myapp-pr-123` makes `web-myapp-pr-123.<domain>` also answer on `web-checkout.<domain>`, with no redeploy.

The routers live in one derived, reserved dynamic file, re-rendered from the custom_routes table. Each mirrors one autolabel router: same rule shape, entrypoint and priority, and it points at the stack's own Traefik service, provider-qualified (`<svc>-<stack>@docker|@swarm`), because an unqualified name resolves to `@file`, which does not exist.

The input is pure data. The caller derives it from the same autolabel computation the deploy used, since routing cannot import autolabel (autolabel imports routing).

ADDITIONAL DOMAINS: the hostnames this host answers on besides the one `init` rendered.

── WHY A DYNAMIC FILE AND NOT A RE-INIT ─────────────────────────────────────────────────────────

The primary domain's `control.` and `api.` routers are docker LABELS on the pstack container, and they must stay there: routing.go's header states the property they buy — no file written here can lock an operator out of the UI and the API that would let them undo it. Adding a SECOND domain does not touch that. The primary keeps answering from its labels whatever happens to this file, so the recovery path survives, and the addition costs no re-render, no restart and no downtime — Traefik picks the file up in about two seconds.

A sidecar proxy was considered and rejected: Traefik owns :443, so nothing reaches a sidecar until a router has already matched the hostname — the router is the whole job, and the sidecar would be a second hop behind it, living in the init-owned control stack that adding a domain would then have to recreate.

── WHAT ONE DOMAIN NEEDS ────────────────────────────────────────────────────────────────────────

control.<d>  and  api.<d>   → the console and the API, so the new name is usable end to end
a wake catch-all             → so a SLEEPING preview on that domain can be woken at all

The wake router is the one people forget. The sleep index is already domain-agnostic (it stores the hostnames a deployment's own routers carry), so a preview on a second domain is indexed correctly the day it is deployed — but with nothing routing `*.<d>` to this container while its own routers are gone, the request never arrives and the stack stays asleep forever.

── SERVICE REFERENCES ARE PROVIDER-QUALIFIED ────────────────────────────────────────────────────

`service: pstack@docker`, and the suffix is LOAD-BEARING: an unqualified name resolves against the REFERENCING object's provider, so a bare `pstack` here means `pstack@file`, which does not exist, and Traefik drops the router with an error rather than falling back.

`@docker` is right on a swarm host too, and that is not an oversight to fix later: `pstack init` brings the control stack up with `docker compose -p pstack-control` in both orchestrator modes and leaves `--providers.docker=true` on, so this container is always the docker provider's. Only the per-PR stacks move to `@swarm`.

Package routing is Traefik dynamic configuration files — list, read, write, delete.

WHAT THIS IS FOR. Traefik takes configuration from two providers: the **docker** provider (labels on containers — how every per-PR router is declared) and the **file** provider, which watches a directory and reloads on change. The file provider is where everything that is not a container lives: middleware (basicAuth, rate limits, IP allow-lists), TLS options, the catch-all fallback router, and routes to something running outside compose. Splitting it across several files is supported and is the point of a watched *directory* rather than one file — one file per concern, each independently editable.

Until now that directory was created by `init` and then never touched again, so the only way to add a middleware was to SSH in. This module is the API behind doing it from the UI.

── WHY THIS NEEDS MORE CARE THAN IT LOOKS ───────────────────────────────────────────────────────

Traefik's own documented behaviour: an unparseable file in the watched directory produces a parse error **for the directory**, and the rest of it can be discarded with it. The visible symptom is not "my new middleware is broken", it is *routes elsewhere disappearing*. So a careless write here does not break the thing you were editing — it breaks other people's previews.

Three consequences, all load-bearing:

  1. **Validate before touching disk.** Parse it, and require the top-level keys to be Traefik's. A typo'd `htttp:` is valid YAML that configures nothing, and Traefik will not tell you.
  2. **Write atomically.** A plain write truncates then fills, and the watcher can fire on the truncated file. Write a temp file in the same directory and `rename` it — rename is atomic within a filesystem, so the watcher only ever sees a whole file.
  3. **Never put anything in that directory that is not dynamic config.** No `.bak`, no temp file left behind, no dotfile — Traefik would try to parse it. This is why there is no on-disk version history: the obvious place to keep it is the one place it must not go. `Write()` returns the previous content instead, so a caller can offer an immediate revert.

── WHAT IT CANNOT BREAK ─────────────────────────────────────────────────────────────────────────

`control.<domain>` and `api.<domain>` are declared as **docker labels on the pstack container**, not in this directory (see initctl). So no file written here can lock you out of the UI or the API that would let you fix it. That is not luck; keep it that way.

The BRING-YOUR-OWN WILDCARD: one certificate pair, stored where Traefik reads and served to every preview by SNI — the `dns-persist-01` mode, minus (for now) the sidecar that would renew it.

── WHERE THE FILES LIVE, AND WHY THE ORDER OF WRITES IS LOAD-BEARING ────────────────────────────

The PEMs go in `certs/` UNDER the watched directory: Traefik's file provider loads directories recursively but parses only .yml/.yaml/.toml, so a PEM there is readable by path yet can never be mistaken for configuration. The pointer to them is a top-level `tls-wildcard.yml` — and it is written LAST, every time, because the fsnotify watch is NOT recursive: an event in `certs/` wakes nobody, while the YAML landing at the top level triggers the rebuild that also RE-INLINES the certificate bytes (Traefik flattens certFile contents into the config at build time, and its unchanged-config check compares those bytes — so a byte-identical YAML still applies a rotated certificate). Removal inverts the order: the YAML goes first, so Traefik never holds a pointer to files that are already gone.

── WHAT WINS THE HANDSHAKE ───────────────────────────────────────────────────────────────────────

File-provider certificates and ACME's share one store, and an exact-SAN certificate sorts before a wildcard — so previews that already own a per-hostname certificate keep serving it, and everything else inherits the wildcard. Nothing has to be revoked to adopt this mode.

── THE KEY HAS NO READ PATH ──────────────────────────────────────────────────────────────────────

Invariant 15. The key goes in and never comes back out: WildcardInfo carries the certificate's public facts only, and no function returning key material exists in this package.

Index

Constants

View Source
const AdvancedUIService = "advanced-ui@docker"

AdvancedUIService is what `control.<d>` targets on a host running the advanced UI. On a basic host the console IS the API container, so it targets apiService instead.

View Source
const CustomRoutesYAML = "pstack-routes.yml"

CustomRoutesYAML is the dynamic file holding every assigned route's routers. Reserved: its routers ARE the assignments, so a hand edit would disagree with GET /api/custom-routes.

View Source
const DomainsYAML = "pstack-domains.yml"

DomainsYAML is the dynamic file holding every additional domain's routers. Reserved, like the wildcard pointer: it is derived state, and a hand edit would make the API's answer a lie.

View Source
const WildcardYAML = "tls-wildcard.yml"

WildcardYAML is the top-level dynamic file that points Traefik at the pair. Its presence IS the mode: `dns-persist-01` is detected by this file existing, never by a stored setting that could disagree with it.

Variables

This section is empty.

Functions

func AliasHosts added in v0.44.0

func AliasHosts(t AliasTarget) []string

AliasHosts is every host the route serves: the plain hosts in service order, then each mirrored wildcard as `*.<host>`.

func AliasRouters added in v0.44.0

func AliasRouters(t AliasTarget) []string

AliasRouters is every router name the route renders (`…-wild` included), for the assign-time check that two routes never render the same name.

func AliasWildcardRules added in v0.44.0

func AliasWildcardRules(t AliasTarget) []string

AliasWildcardRules is the HostRegexp rule of every `-wild` router the route renders, for the sleep index.

func AssertValidRoutingName

func AssertValidRoutingName(name string) error

AssertValidRoutingName rejects a filename Traefik would not read or that could leave the directory.

func DynamicDir added in v0.35.0

func DynamicDir(dataDir string) string

DynamicDir is where Traefik's dynamic configuration lives for THIS process — the resolution `pstack serve` has always performed, shared so the deploy path's mode probe agrees with the server: explicit override, then the in-container mount, then the host-side path under the data dir. (`??` semantics on the env: presence decides, not emptiness.)

func IsError

func IsError(err error) bool

IsError reports whether err is a *Error.

func IsReserved added in v0.35.0

func IsReserved(name string) bool

IsReserved is true for a dynamic file THIS package owns rather than the operator.

The gate exists because these files are DERIVED STATE, not operator configuration: the wildcard pointer's existence IS `dns-persist-01` (so writing that name through the generic routing API would enter a mode whose own routes are admin's, or leaving it would orphan the key pair in `certs/`), and the domains file's routers ARE the domain list `GET /api/domains` reports. Either hand edit makes the API's answer a lie about the host. Each belongs to the route that owns it, which validates what the generic routing API cannot. The custom-routes file is the same: its routers ARE the custom_routes table's assignments.

func RenderCustomRoutes added in v0.44.0

func RenderCustomRoutes(targets []AliasTarget, mode string) (string, error)

RenderCustomRoutes builds the file for every target; "" when there is no router to render, so the caller removes the file rather than leaving an empty one on every host.

Total: a router whose name is already taken (alias `a-b` + service `c` and alias `a` + service `b-c` both give `pstack-route-a-b-c`) or whose provider is unknown is left out with a comment naming it, and the rest of the file still renders. Targets and services are sorted first, so which one wins never depends on the caller's order. The server settles collisions before this (the earlier claim wins, deployments first), so the name drop is a safety net that never fires there.

TLS is never the dns01 wildcard pin: the stack's own certificate story covers the alias host the same way it covers the stack host, and a pin per alias would order a wildcard certificate each.

func ValidateRoutingContent

func ValidateRoutingContent(content string) (*omap.Map, error)

ValidateRoutingContent rejects a file that would break the directory, or silently do nothing.

Returns the parsed mapping on success, so a caller does not parse twice.

The "silently does nothing" half matters as much as the parse half: `htttp:` and `middlewares:` at the top level are both perfectly good YAML that Traefik ignores, and an ignored file is a support ticket that starts "I added the middleware and nothing happened".

Types

type AliasService added in v0.44.0

type AliasService struct {
	// Name is the routing service name (pstack.routing.service_name aware): the Traefik service is
	// `<Name>-<Stack>` and the alias host `<Name>-<Alias>.<Domain>`.
	Name   string
	Domain string
	// Depth is the wildcard subdomain depth when the stack has a derived `-wild` router for this
	// service; "" means none. Autolabel renders at most one per service.
	Depth spec.Depth
	// NoHost leaves the plain router out while the `-wild` one still renders: the server blocked
	// that host because something else serves it. The zero value serves it.
	NoHost bool
}

AliasService is one routed service of the stack whose host autolabel generated.

type AliasTarget added in v0.44.0

type AliasTarget struct {
	Alias    string
	Stack    string
	Provider string // "docker" | "swarm"
	Services []AliasService
}

AliasTarget is one assigned route: the alias, the stack it follows, and the services it mirrors.

func (AliasTarget) Host added in v0.44.0

func (t AliasTarget) Host(s AliasService) string

Host is the alias host of service s: `<Name>-<Alias>.<Domain>`.

func (AliasTarget) Router added in v0.44.0

func (t AliasTarget) Router(s AliasService) string

Router is the name of service s's plain router; its wildcard twin adds `-wild`.

type DomainOptions added in v0.36.0

type DomainOptions struct {
	// Primary is the domain `init` rendered onto the container's labels. Refused as an addition:
	// it already has routers, and a second set would be a name collision — Traefik drops BOTH
	// routers when one name is defined twice with different configurations.
	Primary string
	// Mode is the host's certificate mode (http01 | dns01 | dns-persist-01 | unknown). It decides
	// only the TLS block; see tlsFor.
	Mode string
	// ConsoleService is the Traefik service `control.<d>` targets. Empty means the API container,
	// which is what a BASIC host serves the console from.
	//
	// It exists because the primary domain's own router already makes this choice — `init` renders
	// `pstack-ui.service=advanced-ui` on an advanced host — and an added domain that ignored it
	// served the embedded basic UI on `control.<new-domain>` while `control.<primary>` served the
	// SPA. Same console, two different answers depending on which hostname you typed.
	ConsoleService string
	// Grafana adds a `grafana.<d>` router per added domain, behind the same forwardAuth middleware
	// the primary's Grafana router uses. Off when the host runs no Grafana: a route to nothing is a 502.
	Grafana bool
}

DomainOptions is what the rendering needs to know about the host.

type Error

type Error struct{ Msg string }

Error is a refused name, refused content, an unwritable directory or a missing file. The API maps it to 400 with its own sentence.

func (*Error) Error

func (e *Error) Error() string

type RoutingFile

type RoutingFile struct {
	Name string `json:"name"`
	// Size in bytes. Enough for a list view to show something is there without reading every file.
	Size int64 `json:"size"`
	// UpdatedAt is epoch milliseconds — mtime.
	UpdatedAt int64 `json:"updatedAt"`
}

RoutingFile is one entry of the list view.

type RoutingStore

type RoutingStore struct {
	Dir string
	// contains filtered or unexported fields
}

RoutingStore is the watched directory, and whether this process can write to it.

Writable is probed rather than assumed because the pstack container only gained this mount in 0.4.0: on a host whose control stack predates it the directory is simply absent from the container, and the API must say "re-run `pstack init`" rather than fail with ENOENT.

Stateless apart from Dir; safe to share. No lock: two writers race on the rename, and the last whole file wins — the reference had the same property.

func New

func New(dir string) *RoutingStore

New returns the store over dir.

func (*RoutingStore) Domains added in v0.36.0

func (s *RoutingStore) Domains() []string

Domains is every additional domain, sorted. Derived from the file; empty when there is none.

Total on a nil receiver: a host with no dynamic directory has no additional domains, and this is read on the REQUEST PATH (the wake exclusion), where a panic would be a 500 on every hostname.

func (*RoutingStore) IsControlHostname added in v0.36.0

func (s *RoutingStore) IsControlHostname(hostname, primary string) bool

IsControlHostname reports whether a hostname is one of the control plane's own — the primary's or any additional domain's. Those are never a preview's to wake, and never a preview's to claim: autolabel refuses a `pstack.routing.host` that names one.

The PRIMARY is checked even on a nil store, because it is the one that must never be answered with a waking page whatever else is missing.

`loki.` and `grafana.` count ALWAYS, not only on a host running `--logging loki`: a host that turned logging off must still never answer either with a waking page, and no preview can take the name meanwhile. `grafana.` exists only on the primary; on an added domain it is reserved so that the wake catch-all never hands it to a preview.

func (*RoutingStore) List

func (s *RoutingStore) List() []RoutingFile

List is every file Traefik would read, by name.

func (*RoutingStore) Read

func (s *RoutingStore) Read(name string) (string, error)

Read returns a file's content.

func (*RoutingStore) Remove

func (s *RoutingStore) Remove(name string) (string, error)

Remove deletes a file and returns the removed content, so a caller can offer an undo.

func (*RoutingStore) RemoveWildcard added in v0.35.0

func (s *RoutingStore) RemoveWildcard() (bool, error)

RemoveWildcard leaves the mode: pointer first, then the pair. Returns false when there was nothing to remove — neither pointer NOR pair.

It does not short-circuit on the pointer alone. A crash between the two steps (or an operator who ignored the unlink error below) leaves a key with no pointer, and an early return would answer "no wildcard is stored" forever while it sits there, with no route left that would ever delete it. Every call sweeps both halves.

func (*RoutingStore) SetCustomRoutes added in v0.44.0

func (s *RoutingStore) SetCustomRoutes(content string) error

SetCustomRoutes writes the rendered file atomically; "" removes it.

func (*RoutingStore) SetDomains added in v0.36.0

func (s *RoutingStore) SetDomains(domains []string, o DomainOptions) ([]string, error)

SetDomains rewrites the file so this host answers on exactly these additional domains. An empty list removes it. Returns the normalised list actually stored.

func (*RoutingStore) SetWildcard added in v0.35.0

func (s *RoutingStore) SetWildcard(certPEM, keyPEM string, domains []string) (*WildcardInfo, error)

SetWildcard validates and stores the pair, then points Traefik at it. `domain` is the host's preview domain when known — the certificate must actually cover `*.<domain>`, because a wildcard for the wrong zone fails only at the visitor's browser, weeks later.

Serialised: this is TWO renames plus the pointer, and interleaving them with another PUT would leave certA beside keyB — each half valid, the pair unloadable, and the failure visible only in Traefik's own log. That is precisely what the validation above exists to prevent.

func (*RoutingStore) WildcardActive added in v0.35.0

func (s *RoutingStore) WildcardActive() bool

WildcardActive is the mode probe: does the pointer file exist. Cheap enough for the deploy path.

func (*RoutingStore) WildcardInfo added in v0.35.0

func (s *RoutingStore) WildcardInfo() *WildcardInfo

WildcardInfo reads the stored certificate's public facts; nil when no wildcard is stored.

func (*RoutingStore) Writable

func (s *RoutingStore) Writable() bool

Writable is true when the directory exists and this process may write in it.

func (*RoutingStore) Write

func (s *RoutingStore) Write(name, content string) (*string, error)

Write validates, then replaces atomically. Returns the previous content, or nil if it is new.

The temp file goes in the SAME directory because `rename` is only atomic within a filesystem — across one it degrades to copy-then-delete, which is the partial-file window this exists to avoid. It is named so that Traefik will not read it (no `.yml` suffix) and is removed on failure, because a leftover file in this directory is exactly what must never happen.

type WildcardInfo added in v0.35.0

type WildcardInfo struct {
	Domains   []string `json:"domains"`
	NotBefore int64    `json:"notBefore"`
	NotAfter  int64    `json:"notAfter"`
	Issuer    string   `json:"issuer"`
	// SelfSigned is informational: fine for a lab, a browser warning in production.
	SelfSigned bool `json:"selfSigned"`
}

WildcardInfo is the certificate's public facts — never the key.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL