dockerx

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package dockerx wraps the Docker Engine client.

Phase 1 exposes only New and Close. No container, image, network, or volume operation belongs here yet — reads are Phase 3 and lifecycle control is Phase 5. Keeping the surface this narrow is what makes the policy tier enforceable later: every capability arrives with the phase that audits it.

Index

Constants

This section is empty.

Variables

View Source
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).

View Source
var ErrInvalidRef = errors.New("invalid docker object reference")

ErrInvalidRef is returned by ValidateRef. It never reaches the Engine.

View Source
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.

View Source
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.

View Source
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.

View Source
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).

View Source
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

func ValidateRef(ref string) error

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

func New(ctx context.Context, host string, selfOverride string, log *slog.Logger) (*Client, error)

New dials the Docker Engine at 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.

selfOverride is the operator's DEVMON_SELF_CONTAINER, or "" when unset. It is the escape hatch for the rare host where every filesystem-derived candidate is wrong (D2).

func (*Client) Close

func (c *Client) Close() error

Close releases the Engine connection.

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) Containerized

func (c *Client) Containerized() bool

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

func (c *Client) InspectContainer(ctx context.Context, ref string) (ContainerDetail, error)

InspectContainer returns the full projection of a single container. ref is validated before any Engine call reaches out over the network.

func (*Client) InspectImage

func (c *Client) InspectImage(ctx context.Context, ref string) (ImageDetail, error)

InspectImage returns the full projection of a single image. ref is validated before any Engine call reaches out over the network.

func (*Client) InspectNetwork

func (c *Client) InspectNetwork(ctx context.Context, ref string) (NetworkDetail, error)

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

func (c *Client) InspectVolume(ctx context.Context, ref string) (VolumeSummary, error)

InspectVolume returns the full projection of a single volume. ref is validated before any Engine call reaches out over the network.

func (*Client) KillContainer

func (c *Client) KillContainer(ctx context.Context, ref string) error

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

func (c *Client) RemoveContainer(ctx context.Context, ref string) error

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

func (c *Client) RestartContainer(ctx context.Context, ref string) error

RestartContainer stops and starts a container, waiting up to stopGraceSeconds for it to exit on its own before SIGKILL.

func (*Client) SelfID

func (c *Client) SelfID() string

SelfID returns the agent's own resolved container ID, or "" if unresolved.

func (*Client) SelfKnown

func (c *Client) SelfKnown() bool

SelfKnown reports whether the agent successfully identified its own container.

func (*Client) StartContainer

func (c *Client) StartContainer(ctx context.Context, ref string) error

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

func (c *Client) StopContainer(ctx context.Context, ref string) error

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) 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"`
	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 (D18). See
	// ContainerSummary.Protected for why it has no omitempty.
	Protected bool `json:"protected"`
}

ContainerDetail is the full projection of a single container. 25 fields. NO env. NO raw Engine payload.

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 (D18). 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 the agent
	// itself.
	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

type ListResult[T any] struct {
	Items     []T  `json:"items"`
	Truncated bool `json:"truncated"`
}

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 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.

Jump to

Keyboard shortcuts

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