dockerx

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package dockerx is the agent's only gateway to the Docker Engine API.

Index

Constants

View Source
const MaxLogLine = 16 << 10

MaxLogLine caps the text of one line of the live view (F6): the size of the parts Docker cuts a long line into. The download keeps more.

Variables

View Source
var (
	ErrNotFound    = errors.New("not found in Docker")
	ErrRefused     = errors.New("refused by Docker")
	ErrPutInvalid  = errors.New("extraction refused by Docker")
	ErrUnavailable = errors.New("Docker unavailable")
)

ErrNotFound: no such container (or no such path, for an archive). ErrRefused: Docker refused a write because its target is read-only (measured on Docker 29.7: "container rootfs is marked read-only", "mounted volume is marked read-only"). ErrPutInvalid: any other InvalidArgument of PutArchive, e.g. "extraction point is not a directory": the path changed after the agent's checks. ErrUnavailable: any other failure of the daemon or of the connection to it.

View Source
var ErrNoLogs = errors.New("the logging driver of this container cannot be read back")

ErrNoLogs: the container's logging driver cannot be read (--log-driver none, syslog…): Docker answers 501 "configured logging driver does not support reading".

Functions

func Date

func Date(s string) string

Date is a date of Docker's State, "" for its zero date ("0001-01-01T00:00:00Z": never started, or not finished yet).

func ReadLogs

func ReadLogs(r io.Reader, tty bool, max int, emit func(LogLine) error) error

ReadLogs reads a logs stream asked with timestamps and calls emit for each line, in order. Without a TTY the stream is Docker's multiplexed format (8-byte header: stream type, 3 zero bytes, big-endian size); with a TTY it is raw, one stream. A line Docker cut into parts is joined back (per stream), its text capped at max bytes (Truncated beyond). A frame is never read whole into memory, whatever size its header announces. It stops at the first error of r or of emit, and returns nil at the end of the stream.

Types

type Change

type Change struct {
	Path string `json:"path"`
	Kind string `json:"kind"` // "added" | "modified" | "deleted"
}

Change is one entry of GET /containers/{id}/changes (F5).

type Client

type Client interface {
	ListContainers(ctx context.Context) ([]Container, error)
	Ping(ctx context.Context) error
	// Inspect accepts a full ID, a short ID or a name.
	Inspect(ctx context.Context, id string) (ContainerInfo, error)
	// GetArchive streams the tar of path (GET /containers/{id}/archive).
	// The caller closes it.
	GetArchive(ctx context.Context, id, path string) (io.ReadCloser, error)
	// VolumeOptions returns the driver options of a named volume
	// (GET /volumes/{name}, field Options), e.g. o=bind, device=/proc.
	VolumeOptions(ctx context.Context, name string) (map[string]string, error)
	// SizeRootFs is Inspect with size=true: the size of the container's
	// root filesystem, for the progress of an index (spec §5.2 step 3). Costly
	// for Docker: called once per index build. 0 when Docker gives none.
	SizeRootFs(ctx context.Context, id string) (int64, error)
	// Changes is GET /containers/{id}/changes (F5): never nil.
	Changes(ctx context.Context, id string) ([]Change, error)
	// PutArchive extracts the tar read from content into directory dir of the
	// container (PUT /containers/{id}/archive). dir is sent as is: package
	// files gives the parent of the path it checked (spec §5.3 step 5).
	// Docker never replaces a directory by a file (noOverwriteDirNonDir) and
	// keeps the UID/GID of the tar headers (no copyUIDGID).
	PutArchive(ctx context.Context, id, dir string, content io.Reader) error
	// Logs is GET /containers/{id}/logs with stdout, stderr and timestamps
	// (F6): the raw stream, multiplexed unless the container has a TTY; read
	// it with ReadLogs. The caller closes it; it also ends with ctx.
	// ErrNoLogs when the logging driver cannot be read.
	Logs(ctx context.Context, id string, opt LogsOptions) (io.ReadCloser, error)
	// Info says how the daemon is reached (spec v0.2 §5.10): a Ping of 2 s
	// at most, then GET /version. Host is always set; on an error, Connected
	// is false and the versions may be empty.
	Info(ctx context.Context) (DaemonInfo, error)
	// ContainerSize is Inspect with size=true (spec v0.2 §5.3): SizeRw (the
	// writable layer) and SizeRootFs (the whole root filesystem), nil when
	// Docker gives none. dockerd walks the writable layer: never for a list.
	ContainerSize(ctx context.Context, id string) (rw, rootfs *int64, err error)
	// ImageInspect is GET /images/{id}/json.
	ImageInspect(ctx context.Context, id string) (ImageInfo, error)
	// ImageList is GET /images/json without the intermediate images; the
	// untagged ones are kept (spec v0.2 §5.4).
	ImageList(ctx context.Context) ([]ImageSummary, error)
	// ImageHistory is GET /images/{id}/history: never nil.
	ImageHistory(ctx context.Context, id string) ([]ImageLayer, error)
	// ImageSave streams the export of `docker save` of the image id, given
	// by its full ID (GET /images/get?names=<id>): a read, never a container
	// created (spec v0.2 §5.5). The caller closes it; it also ends with ctx.
	ImageSave(ctx context.Context, id string) (io.ReadCloser, error)
}

func New

func New() (Client, error)

New connects lazily: no request is sent until the first call. The API version is negotiated on the first request.

type Container

type Container struct {
	ID      string    `json:"id"`
	Name    string    `json:"name"`
	Image   string    `json:"image"`
	State   string    `json:"state"`
	Status  string    `json:"status"`
	Created time.Time `json:"created"`
	Ports   []Port    `json:"ports"`
	// Project and Service: the Compose labels com.docker.compose.project and
	// .service (spec v0.2 §5.1), the only labels the list exposes, "" outside
	// Compose or when the label rule masks them (secrets.SafeLabel).
	Project string `json:"project,omitempty"`
	Service string `json:"service,omitempty"`
	// ImageID: "sha256:…", the image the container runs, for the Images
	// page (spec v0.2 §5.4). Not in the container list of the API.
	ImageID string `json:"-"`
}

type ContainerInfo

type ContainerInfo struct {
	ID      string // full 64-character ID
	Name    string // without the leading "/"
	Running bool
	Pid     int // 0 when the container does not run
	// FinishedAt is State.FinishedAt as Docker gives it: part of the index
	// cache key (spec §5.2 step 1). "0001-01-01T00:00:00Z" if never started.
	FinishedAt string
	Mounts     []Mount
	// Tmpfs: destinations of --tmpfs (HostConfig.Tmpfs), sorted. Absent from
	// Mounts; Docker never writes into them (plan Explorateur 3, Q21).
	Tmpfs []string
	// Tty: the logs come as one raw stream, not multiplexed (F6).
	Tty bool
	// LogDriver: HostConfig.LogConfig.Type ("json-file", "local", "none"…).
	LogDriver string
	// Details: the rest of the radiography (F7).
	Details Details
}

ContainerInfo is the part of `docker inspect` the agent uses.

type DaemonInfo added in v0.2.0

type DaemonInfo struct {
	Host          string // DOCKER_HOST, or unix:///var/run/docker.sock
	ServerVersion string // version of the daemon ("29.8.2")
	APIVersion    string // API version negotiated by the client ("1.44")
	Connected     bool
}

DaemonInfo is the Docker part of /api/meta. Host is raw: the API masks it.

type Details

type Details struct {
	Image        string // as asked (Config.Image: "nginx:1.27")
	ImageID      string // "sha256:…"
	Created      string
	Status       string // State.Status: created, running, paused, restarting, exited, dead
	ExitCode     int
	Error        string
	StartedAt    string
	OOMKilled    bool
	Health       string // healthy, unhealthy, starting; "" without a health check
	RestartCount int
	// RestartPolicy: no, always, on-failure, unless-stopped; MaxRetry for on-failure.
	RestartPolicy string
	MaxRetry      int
	Entrypoint    []string
	Cmd           []string
	WorkingDir    string
	User          string
	Env           []string // "NAME=value", raw
	// Ports: the real bindings of a running container, else the configured
	// ones; none on the host network or another container's (Docker ignores
	// -p there). An exposed port without binding has no IP and no Public; a
	// configured -p 90 (host port chosen at start) has an IP, no Public.
	// Sorted.
	Ports       []Port
	NetworkMode string
	Networks    []Network // sorted by name
	// Labels: Config.Labels, raw. They leave the agent through
	// secrets.Labels only (spec v0.2 §5.2).
	Labels map[string]string
}

Details is what the radiography (F7) shows of `docker inspect`, beyond ContainerInfo. Env, Cmd and Entrypoint are raw: package secrets masks them before they leave the agent (spec §7).

type Fake

type Fake struct {
	Containers []Container
	// Infos answers Inspect, by full ID or by name (tests add both keys).
	Infos map[string]ContainerInfo
	// Archives answers GetArchive, keyed by id + ":" + path.
	Archives map[string][]byte
	// ArchiveGate, when not nil, holds every GetArchive call (after it is
	// recorded) until the channel is closed or the context ends: a test
	// keeps an index build in flight as long as it needs.
	ArchiveGate chan struct{}
	// ArchiveCalls records every GetArchive call as id + ":" + path.
	ArchiveCalls []string
	// Sizes answers SizeRootFs, by full ID (absent: 0).
	Sizes map[string]int64
	// Diffs answers Changes, by id as given (absent: ErrNotFound).
	Diffs map[string][]Change
	// ArchiveCloses counts the Close calls of the readers GetArchive returned.
	ArchiveCloses atomic.Int32
	// Volumes answers VolumeOptions, by volume name.
	Volumes map[string]map[string]string
	// PutErr answers PutArchive (nil: success); every call is recorded,
	// failed ones included (read them with PutCalls).
	PutErr error

	// LogStreams answers Logs with these raw bytes, by id as given (absent:
	// ErrNotFound). LogsErr, when set, is returned instead.
	LogStreams map[string][]byte
	LogsErr    error
	// LogsGate, when not nil, holds every logs stream after its bytes (a
	// container that keeps running) until it is closed (end of stream) or
	// the context ends (ctx.Err()).
	LogsGate   chan struct{}
	LogsCloses atomic.Int32

	// Daemon answers Info, with DaemonErr (a Ping that works and a /version
	// that fails, for instance); with Err set, Connected is false.
	Daemon    DaemonInfo
	DaemonErr error
	// ContainerSizes answers ContainerSize, by id as given (absent: both
	// nil, as Docker without a size); SizeGate, when not nil, holds every
	// call until it is closed or the context ends (dockerd's container lock).
	ContainerSizes map[string]SizePair
	SizeGate       chan struct{}
	SizeCalls      atomic.Int32
	// Images answers ImageInspect, by id as given (absent: ErrNotFound);
	// ImageCalls counts the calls of ImageInspect and ImageHistory.
	Images     map[string]ImageInfo
	ImageCalls atomic.Int32
	// ImageSummaries answers ImageList; Histories answers ImageHistory, by
	// id as given (absent: ErrNotFound).
	ImageSummaries []ImageSummary
	Histories      map[string][]ImageLayer
	// ImageSaves answers ImageSave, by id as given (absent: ErrNotFound);
	// ImageSaveCalls counts the calls.
	ImageSaves     map[string][]byte
	ImageSaveCalls atomic.Int32
	// NoWrites makes PutArchive, the one write of the Client, panic: a test
	// of a read-only feature fails if anything writes to Docker.
	NoWrites bool
	Err      error
	// contains filtered or unexported fields
}

Fake is an in-memory Client for tests of other packages. Concurrent calls are safe: an index is built in a goroutine, so GetArchive may run while the test reads Calls().

func (*Fake) Calls

func (f *Fake) Calls() []string

Calls returns a copy of ArchiveCalls, read under the lock.

func (*Fake) Changes

func (f *Fake) Changes(_ context.Context, id string) ([]Change, error)

func (*Fake) ContainerSize added in v0.2.0

func (f *Fake) ContainerSize(ctx context.Context, id string) (rw, rootfs *int64, err error)

func (*Fake) GetArchive

func (f *Fake) GetArchive(ctx context.Context, id, path string) (io.ReadCloser, error)

func (*Fake) ImageHistory added in v0.2.0

func (f *Fake) ImageHistory(_ context.Context, id string) ([]ImageLayer, error)

func (*Fake) ImageInspect added in v0.2.0

func (f *Fake) ImageInspect(_ context.Context, id string) (ImageInfo, error)

func (*Fake) ImageList added in v0.2.0

func (f *Fake) ImageList(context.Context) ([]ImageSummary, error)

func (*Fake) ImageSave added in v0.2.0

func (f *Fake) ImageSave(_ context.Context, id string) (io.ReadCloser, error)

func (*Fake) Info added in v0.2.0

func (f *Fake) Info(context.Context) (DaemonInfo, error)

func (*Fake) Inspect

func (f *Fake) Inspect(_ context.Context, id string) (ContainerInfo, error)

func (*Fake) ListContainers

func (f *Fake) ListContainers(context.Context) ([]Container, error)

func (*Fake) Logs

func (f *Fake) Logs(ctx context.Context, id string, opt LogsOptions) (io.ReadCloser, error)

func (*Fake) LogsCalls

func (f *Fake) LogsCalls() []LogsOptions

LogsCalls returns a copy of the options of every Logs call.

func (*Fake) Ping

func (f *Fake) Ping(context.Context) error

func (*Fake) PutArchive

func (f *Fake) PutArchive(_ context.Context, id, dir string, content io.Reader) error

func (*Fake) PutCalls

func (f *Fake) PutCalls() []Put

PutCalls returns a copy of the PutArchive calls, read under the lock.

func (*Fake) SizeRootFs

func (f *Fake) SizeRootFs(_ context.Context, id string) (int64, error)

func (*Fake) VolumeOptions

func (f *Fake) VolumeOptions(_ context.Context, name string) (map[string]string, error)

type ImageInfo added in v0.2.0

type ImageInfo struct {
	ID           string   // "sha256:…"
	Tags         []string // RepoTags, without "<none>:<none>"
	Size         int64    // bytes, every layer
	Created      string
	OS           string
	Architecture string
	Variant      string
	Env          []string // "NAME=value", raw
	Cmd          []string
	Entrypoint   []string
	WorkingDir   string
	User         string
	ExposedPorts []string // "80/tcp", sorted
	Labels       map[string]string
}

ImageInfo is the part of GET /images/{id}/json the agent uses. Env, Cmd, Entrypoint and Labels are raw: package secrets masks them before they leave the agent (spec v0.2 §5.4).

type ImageLayer added in v0.2.0

type ImageLayer struct {
	CreatedBy string
	Created   time.Time // zero when Docker gives none
	Size      int64
	// Empty: no file changed (ENV, CMD, LABEL…). The history of the API
	// does not say it; an entry of size 0 is counted as empty.
	Empty bool
}

ImageLayer is one entry of GET /images/{id}/history, newest first, as Docker gives them. CreatedBy is raw: secrets.History masks it.

type ImageSummary added in v0.2.0

type ImageSummary struct {
	ID      string   // "sha256:…"
	Tags    []string // RepoTags, without "<none>:<none>": empty for an untagged image
	Size    int64
	Created time.Time
}

ImageSummary is one image of GET /images/json (spec v0.2 §5.4).

type LogLine

type LogLine struct {
	TS        time.Time // zero when Docker gave none
	Stream    string    // "stdout" | "stderr" (a TTY merges both into stdout)
	Text      string
	Truncated bool // longer than MaxLogLine: the rest was dropped
}

LogLine is one line of a container's logs, without its line end.

type LogsOptions

type LogsOptions struct {
	Tail   string
	Since  string
	Follow bool
}

LogsOptions of GET /containers/{id}/logs: stdout, stderr and timestamps are always asked for. Tail is a number of lines or "all"; Since, when set, an RFC 3339 timestamp, inclusive; Follow keeps the stream open while the container runs (a stopped container's stream ends by itself).

type Mount

type Mount struct {
	Type        string // "bind", "volume", "tmpfs"…
	Name        string // volume name
	Source      string // host path of a bind
	Destination string // path in the container
	Driver      string // volume driver ("local"…)
	Mode        string // options given by the user ("ro", "z"…)
	RW          bool
}

Mount is one entry of Inspect.Mounts (binds and volumes).

type Network

type Network struct {
	Name    string   `json:"name"`
	IP      string   `json:"ip,omitempty"`
	Gateway string   `json:"gateway,omitempty"`
	MAC     string   `json:"mac,omitempty"`
	Aliases []string `json:"aliases,omitempty"`
}

Network is one network the container is attached to.

type Port

type Port struct {
	Private uint16 `json:"private"`
	Public  uint16 `json:"public,omitempty"`
	Type    string `json:"type"`
	IP      string `json:"ip,omitempty"`
}

type Put

type Put struct {
	ID, Dir string
	Tar     []byte
}

Put is one PutArchive call: the tar is read whole.

type SizePair added in v0.2.0

type SizePair struct{ RW, RootFs *int64 }

SizePair is what ContainerSize answers.

Jump to

Keyboard shortcuts

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