docker

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package docker materializes and drives the embedded reverse-proxy stack (Traefik + DNS server + network watcher) via `docker compose`, and hosts the network-attach watcher used inside the stack.

Index

Constants

View Source
const (
	// DefaultIncidentsPerService is how many Incidents one service keeps.
	DefaultIncidentsPerService = 20
	// DefaultIncidentMaxAge is how far back the store remembers. Past it an
	// Incident is answering a question nobody is still asking, and the container
	// output it would anchor has rotated away regardless.
	DefaultIncidentMaxAge = 24 * time.Hour
)

Retention defaults. The cap is per service rather than a global byte budget: an Incident is tens of bytes, so memory is never the risk — a worker restarting every three seconds evicting another service's only Incident is.

View Source
const (
	// RoleLabel marks the proximo stack's own containers.
	// RoleLabel names a stack service, and is exported because the host-side CLI
	// recognises proximo's own containers by it too.
	RoleLabel = "proximo.role"

	// ComposeServiceLabel is exported for the same reason RoleLabel is: a
	// host-side reader recognises a stack service by its compose name too.
	ComposeServiceLabel = "com.docker.compose.service"

	// TranscriptLabel opts a container in to being observed without being
	// routed: "you can be quoted", where proximo.hosts says "this is how you are
	// reached". A worker or a queue consumer has no host, so nothing else in the
	// label set can make it known to proximo. It routes nothing, and on an
	// already-routed container (which is observed anyway) it is redundant and
	// accepted in silence. See docs/observability.md.
	// TranscriptLabel is exported because the CLI names it when it says how a
	// container with no route becomes one proximo knows about.
	TranscriptLabel = "proximo.transcript"
)
View Source
const NoteStarting = "starting (waiting for healthy)"
View Source
const NoteUnhealthy = "unhealthy (route withdrawn until healthy)"

NoteUnhealthy is the note carried by a container whose healthcheck failed, so its route was withdrawn. Unlike NoteStarting it is a fault: the container is up and cannot serve.

Variables

This section is empty.

Functions

func CanonicalImage added in v0.11.0

func CanonicalImage() string

CanonicalImage is the stack image this CLI pins itself to. An --image override replaces it wholesale; `status` compares against this to tell the developer an override is in effect.

func Converge added in v0.3.0

func Converge(tld, certDir string, opts ConvergeOpts) error

Converge materializes the embedded stack to disk and brings it up with ref-aware pull freshness. It is the single bring-up path shared by `proximo up`, `install`, and `proximo update`, so "update now" and "update on next start" cannot drift.

func ConvergeObservability added in v0.3.0

func ConvergeObservability(tld, certDir string, opts ConvergeOpts, bootstrap func(stackDir string) error) error

ConvergeObservability brings the stack up with the opt-in observability profile active. It runs the normal core converge, brings up the log viewer and metrics hub, runs the supplied bootstrap (which must write the agent env file once the hub is reachable), then brings up the metrics agent. Sequencing the agent after the bootstrap guarantees it never starts without its hub credentials (design D4). bootstrap may be nil (e.g. in tests).

func DisplayVersion added in v0.5.0

func DisplayVersion(ver string) string

DisplayVersion names a stack version for human output. A running stack without a version label predates version stamping (the proximo.version label was introduced in 0.4.0), so an empty version is shown as "pre-0.4.0".

func Down

func Down() error

Down stops and removes the whole stack — core services plus the opt-in observability dashboards — without touching host configuration. A plain `docker compose down` leaves profile-gated services running, so the observability profile must be enabled (and --remove-orphans added) for the dashboards to be torn down together with the core stack.

func DownObservability added in v0.3.2

func DownObservability() error

DownObservability stops and removes only the opt-in observability services, leaving the core stack running. It is the scoped counterpart to Down behind `proximo down --observability`.

func EnvImage added in v0.11.0

func EnvImage() (string, error)

EnvImage returns the stack image ref recorded in the materialized .env, or "" when nothing has been materialized yet. It is how `up` and `update` see the sticky --image override they are about to keep or clear.

func MatchService added in v0.15.0

func MatchService(want string, known []Service) (match Service, candidates []Service)

MatchService resolves what a developer typed into --service against the services proximo can see. A qualified name is matched exactly; a bare one is accepted when nothing contests it, and when something does its candidates are returned rather than one of them chosen — the position proximo already holds on a Collision and on an Overlap. Neither a match nor candidates means nothing answers to that name at all.

func Materialize

func Materialize(tld, certDir, image string) (string, error)

Materialize writes the embedded stack assets to disk, substituting the TLD and the host data-dir path, creates the bind-mounted data subdirectories, copies the TLS material from certDir into the stack, writes the compose environment file pinning the stack image, and returns the stack directory.

func PortKey added in v0.13.0

func PortKey(port int, proto string) string

PortKey is the map key PublishedPorts uses, e.g. "443/tcp".

func PublishedPorts added in v0.13.0

func PublishedPorts(ctx context.Context) (map[string]PortOwner, error)

PublishedPorts maps each published host port, keyed by PortKey, to the container publishing it. A Check asks who holds a port rather than whether it is free: a healthy machine has :443 bound, by proximo.

Docker is asked rather than inferred from a failed bind, because a bind is not a reliable answer everywhere: on BSD (macOS) SO_REUSEADDR lets a loopback-specific bind succeed while another process holds the wildcard address, which is exactly how Docker publishes :80 and :443.

func Purge added in v0.11.0

func Purge() error

Purge is Down plus proximo's own stack images — the pinned version in use and every superseded one `update` deliberately left cached. `uninstall` reverses everything proximo put on the host, and those images are one of those things; a plain `down` keeps them, because stopping the stack must not make the next `up` re-download it.

Third-party images (Traefik, the observability dashboards) are left alone: proximo did not author them, and a developer may well be sharing them with another project. That is why this is not `compose down --rmi all`.

func SortIncidents added in v0.15.0

func SortIncidents(all []Incident)

SortIncidents orders a listing most recent first — the order a listing of Exchanges is already read in, since the two share one.

func StackDir

func StackDir() (string, error)

StackDir returns the directory the embedded stack is materialized into.

func StackRecordsAccessLog added in v0.15.0

func StackRecordsAccessLog(ctx context.Context) (bool, error)

StackRecordsAccessLog reports whether the running Traefik writes an access log. Without one there is no Access record for any route, and `proximo errors` would be silent for a reason that has nothing to do with a developer's code.

It reads the config the running container has mounted rather than the copy this CLI would materialize: Traefik reads its static configuration once, at startup, so a stack brought up before the access log existed keeps running without it however new the file on disk is. That skew is the whole point of the question.

func StackRecordsIncidents added in v0.15.0

func StackRecordsIncidents(ctx context.Context) (bool, error)

StackRecordsIncidents reports whether the running watcher publishes the Incident API at all. A stack older than this CLI does not, and then `proximo errors` is silent about a restart-looping worker for a reason that has nothing to do with a developer's code — which is exactly the kind of silence a Check exists to name.

A refused connection is a "no" rather than an error: the port is published by the stack itself, so nothing else can be holding it, and a stack that is not running at all is already a failed Check of its own. Every other failure — a timeout, an HTTP status, an unreadable body — stays an error: not knowing is not the same as knowing there are no Incidents, and a Check that confuses the two prescribes `proximo update` for a watcher that is merely slow.

Types

type Composer added in v0.3.0

type Composer interface {
	Compose(stackDir string, args ...string) error
}

Composer runs a docker compose subcommand in a materialized stack directory. The production adapter (execComposer) shells out via compose(); tests pass a fake that records the commands so Converge's sequencing is verifiable without Docker. Only execution is bound — composeConvergeCmds stays the pure, tested source of the command sequence.

type ConvergeOpts added in v0.3.0

type ConvergeOpts struct {
	// Force re-pulls the stack image even when its tag is already cached. A
	// benign no-op on an immutable vX.Y.Z, and the only way to advance a mobile
	// ref that has not changed name.
	Force bool
	// Image overrides the stack image ref verbatim — a tag, a digest, or a
	// locally built image. Empty means CanonicalImage(). It replaces the whole
	// stack, never one component, and is written into the materialized .env so
	// containers restarting at boot keep it.
	Image string
}

ConvergeOpts tunes how Converge brings the stack up.

func (ConvergeOpts) EffectiveImage added in v0.11.0

func (o ConvergeOpts) EffectiveImage() string

EffectiveImage resolves the ref a converge with these options runs. An explicit --image wins; then a PROXIMO_SRC checkout, which is built rather than pulled; otherwise the version-pinned published ref. Whatever it returns is what the .env records and the services stamp as proximo.image, so the stack can never run one image and declare another — and the CLI must resolve what it reports through here, not re-derive it, for the same reason.

type Incident added in v0.15.0

type Incident struct {
	// ID is derived — service, instant and kind — rather than minted, so the
	// same Incident has the same id across two invocations, and the id stays
	// computable from what is on screen after proximo has forgotten it.
	ID string    `json:"id"`
	At time.Time `json:"at"`

	// Service is the qualified service the container belongs to (`shop/worker`),
	// which is what a developer asks about: "what did the worker say" is a
	// question about the service, and "what did worker-2 say" one you can only
	// ask after seeing all three.
	Service   Service `json:"service"`
	Container string  `json:"container"`

	Kind     IncidentKind `json:"kind"`
	ExitCode int          `json:"exit_code,omitempty"`
	// OOM says the kernel chose this exit. It is only ever set from the runtime's
	// own oom event: exit 137 is equally what a plain `docker kill` produces, and
	// claiming the kernel did it would be interpreting.
	OOM bool `json:"oom,omitempty"`
}

An Incident is a fact the runtime declares about a container: it exited non-zero, it was restarted, the kernel killed it, its passing healthcheck stopped passing. Never a line that was read — proximo may remember what the runtime declares, never what the project wrote. See docs/adr/0007-proximo-remembers-what-the-runtime-declares.md.

func PreviousIncident added in v0.15.0

func PreviousIncident(inc Incident, all []Incident) (Incident, bool)

PreviousIncident is the Incident of the same service that came before inc. It is the left edge of the window a Transcript anchored to inc quotes: for a restart loop that is exactly one container lifetime, which no fixed duration can be — a fixed one truncates the worker that wrote the useful line five minutes before dying and drowns the one that restarts every three seconds.

func SelectIncidents added in v0.15.0

func SelectIncidents(all []Incident, q IncidentQuery) []Incident

SelectIncidents narrows a listing of Incidents, most recent first — the way inspect.Select narrows Exchanges, and to the same flags.

func (Incident) Describe added in v0.15.0

func (i Incident) Describe() string

Describe is the Incident in the words the runtime used.

type IncidentAPI added in v0.15.0

type IncidentAPI struct{ Store *IncidentStore }

IncidentAPI is the read side of the watcher's Incident store, published on loopback only — the same shape the hop's read API has, and for the same reason: nothing a browser can reach may read back what proximo observed.

func (IncidentAPI) ServeHTTP added in v0.15.0

func (a IncidentAPI) ServeHTTP(w http.ResponseWriter, r *http.Request)

type IncidentKind added in v0.15.0

type IncidentKind string

IncidentKind is what the runtime declared. The set is closed on purpose: every member is a statement Docker makes, and the first text matcher added here would turn an Incident into a reading of the project's own output.

const (
	IncidentExited    IncidentKind = "exited"
	IncidentRestarted IncidentKind = "restarted"
	// IncidentUnhealthy is a healthcheck that was *passing and stopped*, never one
	// that merely reports unhealthy: a container waiting on postgres at boot goes
	// starting → unhealthy and was never healthy, and a stall is healthy →
	// unhealthy by construction. That distinction is the whole of the noise
	// filtering, which is why it is made when the Incident is recorded rather than
	// when a listing is rendered. See
	// docs/adr/0008-proximo-measures-the-project-concludes.md.
	IncidentUnhealthy IncidentKind = "unhealthy"
)

type IncidentListing added in v0.15.0

type IncidentListing struct {
	Started   time.Time  `json:"started"`
	Incidents []Incident `json:"incidents"`
}

IncidentListing is what the watcher hands back, and what the CLI decodes. Started travels with the Incidents rather than on a second endpoint: an empty listing means either that nothing happened or that a restart threw everything away, and those are very different answers to give a developer.

func IncidentsFromStack added in v0.15.0

func IncidentsFromStack(ctx context.Context, since time.Duration) (IncidentListing, error)

IncidentsFromStack asks the running watcher what the runtime declared about the containers proximo knows, within since of now (zero for everything it holds).

It is the second source `proximo errors` reads, beside the hop: the Incident store lives in the watcher because that is the only stack service with both the Docker socket and the event subscription. That is also a second way for the command to fail, which is why the error is worded for a reader rather than swallowed.

type IncidentQuery added in v0.15.0

type IncidentQuery struct {
	// Service is an exact match on a resolved Service; empty matches any.
	Service Service
	// Services is the set a --host narrowed to. An Incident carries no host, so
	// the only honest way to keep it under a --host is by the Service that served
	// the requests on that host. A nil set means no host was asked for; an empty
	// non-nil one means a host was asked for and nothing could be attributed to it.
	Services map[Service]bool
	// Since bounds the window; the zero instant means no bound.
	Since time.Time
	// Limit keeps the most recent N; zero or less means no bound.
	Limit int
}

IncidentQuery narrows a listing of Incidents. The zero value holds nothing back, and so does every query: an Incident is a fact the runtime declared, and there is no longer a kind with nothing to say (see docs/adr/0008-proximo-measures-the-project-concludes.md). What it shares with inspect.Query is the window and the limit, because the two halves of one listing must be narrowed by the same flags or `--since` means two different things depending on which source a row came from.

type IncidentStore added in v0.15.0

type IncidentStore struct {
	// contains filtered or unexported fields
}

IncidentStore holds the Incidents the watcher observed, in memory. It lives in the watcher because that is the one stack service with both the Docker socket and the event subscription — the hop deliberately has neither, since it sits in the request path.

func NewIncidentStore added in v0.15.0

func NewIncidentStore(perService int, maxAge time.Duration) *IncidentStore

NewIncidentStore returns a store keeping perService Incidents per service for maxAge. Zero or less for either uses the default.

func (*IncidentStore) List added in v0.15.0

func (s *IncidentStore) List(since time.Time) []Incident

List returns every Incident newer than since, most recent first. A zero instant means no bound.

func (*IncidentStore) Observe added in v0.15.0

func (s *IncidentStore) Observe(msg events.Message) (Incident, bool)

Observe turns one Docker event into an Incident and records it, reporting whether it recorded one. Everything the runtime does not declare an Incident about — a start, a clean exit, a container proximo knows nothing about — is dropped here.

func (*IncidentStore) SawHealthy added in v0.15.0

func (s *IncidentStore) SawHealthy(id string)

SawHealthy records that a container's healthcheck is currently passing, so a later fall out of healthy is the Incident it is. The event stream cannot supply this on its own: a watcher that restarted has seen no health_status event for a container that was already healthy, and would read its next stall as a check that never passed. The reconcile's container listing closes that hole.

func (*IncidentStore) Started added in v0.15.0

func (s *IncidentStore) Started() time.Time

Started reports when the store came up, so an empty listing can say whether a restart is the reason.

type PortOwner added in v0.13.0

type PortOwner struct {
	Container string
	Stack     bool
}

PortOwner is the container publishing a host port, and whether it is one of proximo's own — which is the difference between a healthy machine and a contested port.

type Reading added in v0.15.0

type Reading struct {
	// Container is the one measured. There is no "running" alongside it: a Reading
	// is the present tense of something alive, so being alive is what qualified
	// the container for one rather than something the Reading reports.
	Container string `json:"container"`
	// Since is when the container last started (not when it was created): for a
	// worker that has been restarted, the second would overstate its uptime.
	Since       time.Time `json:"since,omitzero"`
	Healthcheck string    `json:"healthcheck,omitempty"`
	Restarts    int       `json:"restarts,omitempty"`

	// LastWrote is when the container last wrote a line — the instant, never the
	// line. WroteNothing is set instead when the stream was read and had nothing
	// in it, which is a fact about the project rather than about the read. With
	// neither set the stream could not be read at all, and Unread says so: a
	// reading nobody could take is not a reading of zero.
	LastWrote    time.Time `json:"last_wrote,omitzero"`
	WroteNothing bool      `json:"wrote_nothing,omitempty"`

	// Unread names what could not be read, and is empty when everything was. Every
	// absence in proximo says which absence it is; a missing reading presented as
	// a measurement is the one that sends a developer after the wrong thing.
	Unread []string `json:"unread,omitempty"`
}

A Reading is what the runtime says about a container *right now*, where an Incident is dated history: whether it is running and since when, what its healthcheck says, how many times it has been restarted, and the instant its output last moved. Measured, never interpreted — when a stream moved is the runtime's to declare, what the line said is the project's.

It is what proximo has to offer about a container that is alive and may not be progressing, and it stops short of the conclusion on purpose: an idle consumer and one blocked on a slow query read identically from out here.

It is a fact about *one* container, so a Service produces one per running replica: with three workers up and one of them wedged, a single reading is a coin toss that comes up "healthy, wrote 3s ago" twice out of three.

func (Reading) Describe added in v0.15.0

func (rd Reading) Describe() string

Describe renders the Reading as one clause per fact, in the order a developer checks them. What could not be read is named rather than left as a gap.

type Route

type Route struct {
	Container   string
	Host        string
	Qualified   string // the qualified host the route also answers on ("" when it has none)
	Path        string // proximo.path prefix scoping the route ("" = all paths)
	URL         string
	Note        string
	Middlewares []string // active proximo middlewares (auth/cors/headers), in chain order
	TCPPorts    []int    // backend ports for a TCP-over-TLS (SNI) route; empty means an HTTP route
	TLSMode     string   // TCP TLS mode (terminate/passthrough); set only for TCP routes
	Backends    int      // number of backend containers serving this route; >1 means round-robin balanced
	Inspect     bool     // proximo.inspect asked for, and honoured: the route is served through the hop
	InspectNote string   // set when proximo.inspect was asked for but could not be honoured
	// Observed marks a container proximo knows about but does not route: it
	// carries proximo.transcript and no host. It is inventory, not a warning —
	// the only other way to learn the label took effect would be to wait for
	// something to go wrong, and a label that cannot be verified is one that
	// gets written wrong unnoticed.
	Observed bool
	// Collision marks the row as a host another container claimed. It is said
	// structurally rather than read back out of Note, so a Check can route a
	// collision to its own explanation without pattern-matching prose that is
	// written for a human.
	Collision bool
}

Route is a routed container and a URL it is reachable at. When Note is set the container opted in but is not effectively served (e.g. an unresolved backend port the watcher skips); URL is then empty and Note explains why.

func Routes

func Routes(ctx context.Context, tld string) ([]Route, error)

Routes lists the effective routing state `proximo status` reports. It uses the same classifier (classify) the watcher uses to generate routers and certificates, so the two cannot disagree about which hosts are served. A proximo container whose backend port is ambiguous/unresolved (the watcher skips it) is flagged with a Note rather than listed as a working route. The classifyInfo diagnostics are ignored here so status stays quiet — no watcher warnings. tld names the Traefik dashboard self-route host (traefik.<tld>), which the watcher injects outside container classification and is therefore surfaced here the same way: present whenever the stack's Traefik is running.

func (Route) Display added in v0.9.0

func (r Route) Display() string

Display renders the route's target for `proximo status`: the HTTPS URL for an HTTP route, or a `tcp://host:ports (mode)` summary for a TCP-over-TLS route, suffixed with a balanced marker when more than one backend serves it.

type Service added in v0.15.0

type Service string

A Service is one named part of a Project — a Compose service — qualified by its Namespace: `shop/worker`. It is a type rather than a string because the bare-vs-qualified rule travels with it, and because a resolved Service and whatever a developer typed into --service are not the same thing: the second is a question, and only MatchService turns it into an answer.

func ServiceKey added in v0.15.0

func ServiceKey(c container.Summary) Service

ServiceKey is ServiceOf for a container listing, so the watcher (which sees only an event's attributes) and every host-side reader name one service the same way.

func ServiceOf added in v0.15.0

func ServiceOf(labels map[string]string, containerName string) Service

ServiceOf names the Compose service a container belongs to, qualified by its Namespace — the same qualifier a qualified host carries, because a qualified service and a Namespace are one concept, not two. A container outside a Compose project has neither, so it names itself.

func (Service) Bare added in v0.15.0

func (s Service) Bare() string

Bare is the service name without its Namespace — the short name a developer writes when nothing contests it, and the one MatchService accepts when nothing contests it. The Namespace half needs no accessor: it is only ever printed as part of the qualified name.

func (Service) String added in v0.15.0

func (s Service) String() string

type StackInfo added in v0.11.0

type StackInfo struct {
	Running bool
	Version string
	Image   string
	// Roles are the proximo.role values of the running stack containers, so a
	// degraded stack (traefik up, watcher gone) is distinguishable from a
	// healthy one — which "is anything running?" alone cannot tell.
	Roles []string
}

StackInfo is what the host can read back off a running stack: whether one is running at all, the CLI version that materialized it, and the image ref its Go services were started from.

Running distinguishes "no stack" from "stack predating version stamping" (running, empty Version — a pre-0.4.0 stack carries no version label).

func StackStatus added in v0.11.0

func StackStatus(ctx context.Context) (StackInfo, error)

StackStatus reads the proximo.version and proximo.image labels off the running stack. Docker errors are returned so callers can tell "stack down" from "Docker broken".

func (StackInfo) MissingRoles added in v0.13.0

func (s StackInfo) MissingRoles() []string

MissingRoles returns the core stack services that are not running, in the order they are named above. Empty means the stack is whole.

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher keeps Traefik attached to the Docker networks of routed containers and issues a CA-signed certificate per container, written to Traefik's file-provider directory.

func NewWatcher

func NewWatcher() (*Watcher, error)

NewWatcher creates a Watcher from the Docker environment and loads the CA (for issuing per-host certificates) from the mounted paths.

func (*Watcher) Incidents added in v0.15.0

func (w *Watcher) Incidents() *IncidentStore

Incidents is the store the watcher records into, for the loopback read API the CLI asks for Incidents on.

func (*Watcher) Run

func (w *Watcher) Run(ctx context.Context) error

Run reconciles once, then reacts to Docker events with a periodic resync.

Jump to

Keyboard shortcuts

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