Documentation
¶
Overview ¶
Package dockerx wraps the Docker Engine client.
It exposes the narrow set of read and lifecycle operations the agent's HTTP API needs, projected onto an explicit allowlist of DTOs (D1) so nothing forwards an Engine struct verbatim. Every mutating call is enforced through one chokepoint, resolveTarget, which refuses the agent's own container and any container matching the operator's DEVMON_PROTECTED_CONTAINERS list.
Index ¶
- Variables
- func ValidateRef(ref string) error
- type Client
- func (c *Client) Close() error
- func (c *Client) ContainerLogs(ctx context.Context, ref string, opts LogOptions) (ListResult[LogLine], error)
- func (c *Client) ContainerStates(ctx context.Context) ([]ContainerStateSummary, error)
- func (c *Client) Containerized() bool
- func (c *Client) InspectContainer(ctx context.Context, ref string) (ContainerDetail, error)
- func (c *Client) InspectImage(ctx context.Context, ref string) (ImageDetail, error)
- func (c *Client) InspectNetwork(ctx context.Context, ref string) (NetworkDetail, error)
- func (c *Client) InspectVolume(ctx context.Context, ref string) (VolumeSummary, error)
- func (c *Client) KillContainer(ctx context.Context, ref string) error
- func (c *Client) ListContainers(ctx context.Context, all bool) (ListResult[ContainerSummary], error)
- func (c *Client) ListImages(ctx context.Context) (ListResult[ImageSummary], error)
- func (c *Client) ListNetworks(ctx context.Context) (ListResult[NetworkSummary], error)
- func (c *Client) ListVolumes(ctx context.Context) (ListResult[VolumeSummary], error)
- func (c *Client) RemoveContainer(ctx context.Context, ref string) error
- func (c *Client) RestartContainer(ctx context.Context, ref string) error
- func (c *Client) SelfID() string
- func (c *Client) SelfKnown() bool
- func (c *Client) StartContainer(ctx context.Context, ref string) error
- func (c *Client) StopContainer(ctx context.Context, ref string) error
- func (c *Client) StreamContainerEvents(ctx context.Context, onReady func(), emit func(ContainerEvent) error) error
- func (c *Client) StreamContainerLogs(ctx context.Context, ref string, opts LogOptions, emit func(LogLine) error) error
- type ContainerDetail
- type ContainerEvent
- type ContainerStateSummary
- type ContainerSummary
- type EndpointSummary
- type ImageDetail
- type ImageSummary
- type ListResult
- type LogLine
- type LogOptions
- type Mount
- type NetworkDetail
- type NetworkEndpoint
- type NetworkSummary
- type Options
- type Port
- type VolumeSummary
Constants ¶
This section is empty.
Variables ¶
var ErrConflict = errors.New("docker object is in a conflicting state")
ErrConflict is returned when the Engine refuses an operation because of the object's current state — in practice, deleting a running container (D10).
var ErrEventFeedClosed = errors.New("docker event feed closed")
ErrEventFeedClosed is returned when the Engine's event feed ends rather than fails — an io.EOF on the error channel, or a closed channel. It is distinct from a transport failure because the caller's response is the same either way (tear the subscribers down so they reconnect and re-snapshot) while the log level is not: an ended feed is ordinary on a daemon restart, a transport failure is not.
var ErrInvalidRef = errors.New("invalid docker object reference")
ErrInvalidRef is returned by ValidateRef. It never reaches the Engine.
var ErrInvalidSince = errors.New("invalid since timestamp")
ErrInvalidSince is returned when a caller-supplied resume cursor does not parse as a timestamp. Like ErrInvalidRef it never reaches the Engine: the value is interpolated into the Engine's request URL, so it is validated at the agent's boundary rather than trusted to an upstream parser.
var ErrNotFound = errors.New("docker object not found")
ErrNotFound is returned when the Engine reports no such object. It is the only Engine failure the API distinguishes: the caller is an authenticated device, so telling it "that container is gone" is information it is entitled to, while every other Engine fault is an upstream problem the client can only retry.
var ErrNotModified = errors.New("docker object already in the requested state")
ErrNotModified is returned when the Engine reports the object was already in the requested state. Callers treat it as success (D9); it exists as a distinct sentinel so the audit detail can record that nothing changed.
var ErrProtectedContainer = errors.New("container is protected by host configuration")
ErrProtectedContainer is returned when a lifecycle operation targets a container matching an entry of the operator's DEVMON_PROTECTED_CONTAINERS list. Like self-exclusion it is enforced in every policy mode, but unlike self-exclusion it is operator configuration rather than a fixed rule; when a target matches both, the self rule takes precedence.
var ErrSelfProtected = errors.New("the agent cannot act on its own container")
ErrSelfProtected is returned when a lifecycle operation targets the agent's own container. This is a fixed rule, not a policy tier: stopping or deleting the agent from the app would destroy the operator's only remote access, and no configuration may opt into that (D1).
var ErrSelfUnknown = errors.New("agent cannot identify its own container")
ErrSelfUnknown is returned when the agent is running in a container but could not determine which one. Lifecycle operations fail closed rather than proceed with the self-exclusion rule unenforceable (D3).
Functions ¶
func ValidateRef ¶
ValidateRef reports whether ref is safe to interpolate into an Engine request path. It returns ErrInvalidRef, wrapped with ref for context, when ref does not match refPattern.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the agent's handle on the Docker Engine.
func New ¶
New dials the Docker Engine at opts.Host and verifies it responds.
A host whose Engine is unreachable cannot serve any agent operation, so this is a fatal startup error rather than a degraded mode: an agent that starts and then fails every request is harder to diagnose than one that refuses to start.
func (*Client) ContainerLogs ¶
func (c *Client) ContainerLogs(ctx context.Context, ref string, opts LogOptions) (ListResult[LogLine], error)
ContainerLogs returns a bounded slice of recent lines.
func (*Client) ContainerStates ¶ added in v0.4.0
func (c *Client) ContainerStates(ctx context.Context) ([]ContainerStateSummary, error)
ContainerStates returns the current state and health of every container on the host, including stopped ones — the payload of the event stream's opening snapshot.
One ContainerList call, never a per-container inspect. container.Summary carries Health directly, and N+1 inspects taken at N different instants would produce a "snapshot" that was never simultaneously true.
Health arrived on the list response in Docker API v1.52 (Engine 29). On an older Engine Summary.Health is nil for every container and they all report "none"; the events themselves are unaffected.
func (*Client) Containerized ¶
Containerized reports whether the agent is running inside a Docker container at all (D4). A non-containerized agent has no container to protect, so self-exclusion is inapplicable rather than failing closed.
func (*Client) InspectContainer ¶
InspectContainer returns the full projection of a single container. ref is validated before any Engine call reaches out over the network.
func (*Client) InspectImage ¶
InspectImage returns the full projection of a single image. ref is validated before any Engine call reaches out over the network.
func (*Client) InspectNetwork ¶
InspectNetwork returns the full projection of a single network, including its attached containers. ref is validated before any Engine call reaches out over the network.
func (*Client) InspectVolume ¶
InspectVolume returns the full projection of a single volume. ref is validated before any Engine call reaches out over the network.
func (*Client) KillContainer ¶
KillContainer sends SIGKILL to a running container. The signal is fixed, not caller-selectable: the kill button means "stop this now", not a config-reload idiom (D11).
func (*Client) ListContainers ¶
func (c *Client) ListContainers(ctx context.Context, all bool) (ListResult[ContainerSummary], error)
ListContainers returns every container on the host, or only running ones when all is false, capped at maxListItems.
func (*Client) ListImages ¶
func (c *Client) ListImages(ctx context.Context) (ListResult[ImageSummary], error)
ListImages returns every image on the host, capped at maxListItems.
func (*Client) ListNetworks ¶
func (c *Client) ListNetworks(ctx context.Context) (ListResult[NetworkSummary], error)
ListNetworks returns every network on the host, capped at maxListItems.
func (*Client) ListVolumes ¶
func (c *Client) ListVolumes(ctx context.Context) (ListResult[VolumeSummary], error)
ListVolumes returns every volume on the host, capped at maxListItems.
func (*Client) RemoveContainer ¶
RemoveContainer deletes a stopped container. A running container yields ErrConflict rather than being force-stopped and removed in one step: stop, then delete, is two operations, two audit rows, two deliberate taps (D10).
func (*Client) RestartContainer ¶
RestartContainer stops and starts a container, waiting up to stopGraceSeconds for it to exit on its own before SIGKILL.
func (*Client) SelfKnown ¶
SelfKnown reports whether the agent successfully identified its own container.
func (*Client) StartContainer ¶
StartContainer starts a stopped container. Starting an already-running container answers 304 from the Engine, which this SDK version treats as a successful status and returns with a nil error — so D9's "already in the requested state is success" holds here with no special case. If a future SDK version surfaces the 304 as an error instead, classify maps it to ErrNotModified and httpapi.writeDockerError answers 204 for it too, so the caller-visible behavior does not change either way.
func (*Client) StopContainer ¶
StopContainer stops a running container, waiting up to stopGraceSeconds for it to exit on its own before SIGKILL. Stopping an already-stopped container answers 304, which returns nil for the same reason described on StartContainer (D9), with the same ErrNotModified/204 fallback if that SDK behavior ever changes.
func (*Client) StreamContainerEvents ¶ added in v0.4.0
func (c *Client) StreamContainerEvents(ctx context.Context, onReady func(), emit func(ContainerEvent) error) error
StreamContainerEvents follows the Engine's container event feed, calling emit once per allowlisted event until ctx is cancelled, the feed ends, or emit returns an error.
onReady is invoked exactly once, after the Engine subscription is established and before the first event can be delivered. Callers depend on this: the event stream's opening snapshot must be taken AFTER the subscription exists, or an event firing in between is in neither the snapshot nor the stream, and this feature has no replay to recover it. client.Client.Events blocks internally until GET /events has been issued and its response received, so the moment it returns is exactly that point.
emit MUST NOT BLOCK. The SDK's message channel is unbuffered, so a slow emit stalls the Engine decoder goroutine and backs the feed up for every consumer.
No callTimeout here, deliberately, for the reason StreamContainerLogs gives: the subscription's lifetime is ctx and nothing else.
func (*Client) StreamContainerLogs ¶
func (c *Client) StreamContainerLogs(ctx context.Context, ref string, opts LogOptions, emit func(LogLine) error) error
StreamContainerLogs follows ref's output, calling emit once per line until the container stops, ctx is cancelled, or emit returns an error.
emit is a callback rather than a returned channel deliberately: the caller needs to flush after every line and to abort the stream the instant a client write fails. A channel would need a producer goroutine, a second error channel, and close semantics careful enough to survive a client that vanishes mid-line — three places to leak a goroutine instead of none.
type ContainerDetail ¶
type ContainerDetail struct {
ID string `json:"id"`
Name string `json:"name"`
Image string `json:"image"`
ImageID string `json:"image_id"`
CreatedAt string `json:"created_at"` // RFC3339 UTC
State string `json:"state"`
Running bool `json:"running"`
Paused bool `json:"paused"`
Restarting bool `json:"restarting"`
ExitCode int `json:"exit_code"`
StartedAt string `json:"started_at,omitempty"`
FinishedAt string `json:"finished_at,omitempty"`
Health string `json:"health,omitempty"`
RestartCount int `json:"restart_count"`
RestartPolicy string `json:"restart_policy,omitempty"`
Platform string `json:"platform"`
Labels map[string]string `json:"labels"`
Command string `json:"command"` // InspectResponse.Path
Args []string `json:"args"`
Entrypoint []string `json:"entrypoint,omitempty"`
WorkingDir string `json:"working_dir,omitempty"`
User string `json:"user,omitempty"`
Mounts []Mount `json:"mounts"`
Networks []EndpointSummary `json:"networks"`
Ports []Port `json:"ports"`
// Protected reports whether this is the agent's own container or one
// listed in DEVMON_PROTECTED_CONTAINERS (D18); every mutating route
// refuses it. See ContainerSummary.Protected for why it has no
// omitempty.
Protected bool `json:"protected"`
}
ContainerDetail is the full projection of a single container. 26 fields. NO env. NO raw Engine payload.
type ContainerEvent ¶ added in v0.4.0
type ContainerEvent struct {
ID string `json:"id"`
Name string `json:"name"` // leading "/" stripped (D18)
Event string `json:"event"` // "health_status" | "die" | "start" | "stop" | "oom"
Health string `json:"health,omitempty"` // set only for health_status; "healthy" | "unhealthy"
Time string `json:"time"` // RFC3339 UTC
}
ContainerEvent is one allowlisted Docker container event.
Event is a NORMALISED literal from a fixed allowlist, never string(msg.Action): a free-form health_status action carries the healthcheck's own output, which this agent must not publish or log. Actor.Attributes is never mapped at all — it is the container's label set (Phase 3 D2 applies verbatim); only the "name" key is read.
type ContainerStateSummary ¶ added in v0.4.0
type ContainerStateSummary struct {
ID string `json:"id"`
Name string `json:"name"` // leading "/" stripped (D18); join on ID, not this
State string `json:"state"`
Health string `json:"health"`
}
ContainerStateSummary is one entry of the event stream's opening snapshot: the minimum a client needs to reconcile its own view before live events start arriving. 4 fields.
It is deliberately not ContainerSummary. The snapshot is sent on every reconnect, including on a flaky mobile connection, so it carries the four fields the stream can change and nothing else — ports, labels, and image identifiers do not belong in a frame whose job is "here is what moved".
Health is one of container.NoHealthcheck, Starting, Healthy, Unhealthy — "none", "starting", "healthy", "unhealthy". No omitempty: a client must be able to tell "no healthcheck" from "this agent version does not report health", exactly as ContainerSummary.Protected argues.
type ContainerSummary ¶
type ContainerSummary struct {
ID string `json:"id"`
Names []string `json:"names"`
Image string `json:"image"`
ImageID string `json:"image_id"`
Command string `json:"command"`
CreatedAt string `json:"created_at"` // RFC3339 UTC
State string `json:"state"`
Status string `json:"status"`
Health string `json:"health,omitempty"` // "" when Health is nil
Labels map[string]string `json:"labels"`
Ports []Port `json:"ports"`
// Protected reports whether this is the agent's own container or one
// listed in DEVMON_PROTECTED_CONTAINERS (D18); every mutating route
// refuses it. No omitempty: a false value must appear in the JSON, or an
// app that cannot distinguish "not protected" from "this agent version
// does not report protection" would quietly offer a delete button on a
// container it should not.
Protected bool `json:"protected"`
}
ContainerSummary is one entry of a container list. 12 fields.
type EndpointSummary ¶
type EndpointSummary struct {
NetworkName string `json:"network_name"`
NetworkID string `json:"network_id"`
IPAddress string `json:"ip_address,omitempty"`
Gateway string `json:"gateway,omitempty"`
MACAddress string `json:"mac_address,omitempty"`
Aliases []string `json:"aliases,omitempty"`
}
EndpointSummary is a container's attachment to a single network.
type ImageDetail ¶
type ImageDetail struct {
ID string `json:"id"`
RepoTags []string `json:"repo_tags"`
RepoDigests []string `json:"repo_digests"`
CreatedAt string `json:"created_at,omitempty"`
Size int64 `json:"size"`
Architecture string `json:"architecture"`
OS string `json:"os"`
Author string `json:"author,omitempty"`
Comment string `json:"comment,omitempty"`
}
ImageDetail is the full projection of a single image. 9 fields.
image.InspectResponse.Config carries the image's baked-in Env. It is NOT mapped. D2 applies to images too.
type ImageSummary ¶
type ImageSummary struct {
ID string `json:"id"`
ParentID string `json:"parent_id,omitempty"`
RepoTags []string `json:"repo_tags"`
RepoDigests []string `json:"repo_digests"`
CreatedAt string `json:"created_at"` // RFC3339 UTC from int64
Size int64 `json:"size"`
Containers int64 `json:"containers"` // -1 means "not calculated"
Labels map[string]string `json:"labels"`
}
ImageSummary is one entry of an image list. 8 fields.
type ListResult ¶
ListResult is the envelope every list route returns. A bare top-level JSON array cannot gain a field later without breaking every client, and Truncated needs somewhere to live from day one (D9).
type LogLine ¶
type LogLine struct {
Timestamp string `json:"ts"` // RFC3339Nano; "" if the Engine emitted no parsable prefix
Stream string `json:"stream"` // "stdout" or "stderr"
Line string `json:"line"`
Truncated bool `json:"truncated,omitempty"` // set when the line exceeded maxLogLineBytes
}
LogLine is one demultiplexed line of container output. Unlike every other DTO in this package, its payload is not a projection of Engine metadata — Line is whatever the container printed, which is precisely what the operator asked for. That makes it the one field in the codebase that may legitimately carry a secret, and the reason D16 forbids writing it to the agent's own log.
type LogOptions ¶
type LogOptions struct {
Tail int // lines to seed with; <= 0 means "all"
Since string // RFC3339Nano cursor; "" means from the beginning
}
LogOptions is the validated, agent-side view of a log request. Both fields are bounded by the caller in httpapi before they arrive here; this struct re-validates Since because it is what reaches the Engine's request URL.
type Mount ¶
type Mount struct {
Type string `json:"type"`
Name string `json:"name,omitempty"`
Source string `json:"source"`
Destination string `json:"destination"`
ReadWrite bool `json:"read_write"`
}
Mount is a single filesystem mount attached to a container.
type NetworkDetail ¶
type NetworkDetail struct {
NetworkSummary
Containers []NetworkEndpoint `json:"containers"`
}
NetworkDetail is a NetworkSummary plus the containers attached to it.
type NetworkEndpoint ¶
type NetworkEndpoint struct {
ContainerID string `json:"container_id"`
Name string `json:"name"`
IPv4Address string `json:"ipv4_address,omitempty"`
IPv6Address string `json:"ipv6_address,omitempty"`
}
NetworkEndpoint is a single container's attachment to an inspected network.
type NetworkSummary ¶
type NetworkSummary struct {
ID string `json:"id"`
Name string `json:"name"`
Driver string `json:"driver"`
Scope string `json:"scope"`
CreatedAt string `json:"created_at"`
Internal bool `json:"internal"`
EnableIPv6 bool `json:"enable_ipv6"`
Labels map[string]string `json:"labels"`
}
NetworkSummary is one entry of a network list. 8 fields.
type Options ¶ added in v0.7.0
type Options struct {
// Host is DEVMON_DOCKER_HOST, the Engine endpoint to dial.
Host string
// SelfContainer is the operator's DEVMON_SELF_CONTAINER override, or ""
// when unset. It is the escape hatch for the rare host where every
// filesystem-derived candidate is wrong (D2).
SelfContainer string
// ProtectedContainers is the operator's DEVMON_PROTECTED_CONTAINERS
// entries (names or IDs), or nil when unset. A container matching any
// entry is refused by every lifecycle route and reported as protected in
// list and inspect responses, exactly like the agent's own container.
ProtectedContainers []string
}
Options configures New. Every field is startup configuration, read once and never changed afterward (D5): a client can never widen what the operator granted at process start.
type Port ¶
type Port struct {
IP string `json:"ip,omitempty"` // from netip.Addr; "" when !IsValid()
PrivatePort uint16 `json:"private_port"`
PublicPort uint16 `json:"public_port,omitempty"`
Protocol string `json:"protocol"` // from PortSummary.Type
}
Port is a single published or exposed container port.
type VolumeSummary ¶
type VolumeSummary struct {
Name string `json:"name"`
Driver string `json:"driver"`
Mountpoint string `json:"mountpoint"`
CreatedAt string `json:"created_at,omitempty"`
Scope string `json:"scope"`
Labels map[string]string `json:"labels"`
SizeBytes *int64 `json:"size_bytes,omitempty"` // from UsageData.Size when non-nil
}
VolumeSummary is both a volume list entry and a volume inspect response (VolumeDetail is VolumeSummary; there is no separate detail shape). 7 fields.
volume.Volume.Options is NOT mapped: for tmpfs and CIFS/NFS volumes it routinely contains credentials (o=username=...,password=...). D2's reasoning applies verbatim.