engine

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package engine is the only place that talks to the Docker daemon. It produces a Snapshot, a plain, JSON-serialisable copy of everything dockdu needs, so that collectors and renderers never depend on the SDK and can be tested from recorded fixtures.

The engine is strictly read-only: it calls Info, DiskUsage and ContainerInspect and nothing else.

Index

Constants

This section is empty.

Variables

View Source
var ErrDaemonUnreachable = errors.New("docker daemon unreachable")

ErrDaemonUnreachable wraps connection failures so main can map them to exit code 1.

View Source
var ErrFixtureExists = errors.New("fixture exists; pass overwrite to replace it")

ErrFixtureExists is returned by WriteFixture when the target exists and overwrite is false. Recording never silently replaces test data.

View Source
var ErrNotReadOnly = errors.New("dockdu read-only guard: request refused")

ErrNotReadOnly is returned for any request the read-only guard refuses. Seeing it means a code path tried to reach a Docker endpoint outside the allowlist; that is a bug, never a condition to work around.

Functions

func Record

func Record(ctx context.Context, e Engine, path string, overwrite bool) error

Record takes a snapshot from e, sanitises it and writes it to path.

func Sanitize

func Sanitize(s *Snapshot)

Sanitize removes data a fixture does not need: labels outside the compose namespace, the daemon host and name, registry hosts in image references, and build-cache descriptions, which can contain local paths and secrets from Dockerfile instructions.

func WriteFixture

func WriteFixture(path string, s *Snapshot, overwrite bool) error

WriteFixture stores a sanitised snapshot as indented JSON. Without overwrite the file is created with O_EXCL, so an existing file or a symlink planted at path is never replaced (no stat-then-write race).

Types

type Aggregate

type Aggregate struct {
	ActiveCount int64 `json:"active_count"`
	TotalCount  int64 `json:"total_count"`
	// Reclaimable is the daemon's own estimate of what a prune of this type
	// would free. For build cache it excludes shared records.
	Reclaimable int64 `json:"reclaimable"`
	TotalSize   int64 `json:"total_size"`
}

Aggregate mirrors the daemon's per-type disk usage summary.

type CacheRecord

type CacheRecord struct {
	ID          string     `json:"id"`
	Parents     []string   `json:"parents,omitempty"`
	Type        string     `json:"type"`
	Description string     `json:"description"`
	InUse       bool       `json:"in_use"`
	Shared      bool       `json:"shared"`
	Size        int64      `json:"size"`
	CreatedAt   time.Time  `json:"created_at"`
	LastUsedAt  *time.Time `json:"last_used_at,omitempty"`
	UsageCount  int        `json:"usage_count"`
}

CacheRecord is one BuildKit cache record as returned by the daemon.

type Container

type Container struct {
	ID         string            `json:"id"`
	Name       string            `json:"name"`
	Image      string            `json:"image"`
	ImageID    string            `json:"image_id"`
	Created    int64             `json:"created"`
	State      string            `json:"state"`
	Status     string            `json:"status"`
	SizeRw     int64             `json:"size_rw"`
	SizeRootFs int64             `json:"size_root_fs"`
	Labels     map[string]string `json:"labels,omitempty"`
	LogDriver  string            `json:"log_driver"`
	LogOpts    map[string]string `json:"log_opts,omitempty"`
	LogPath    string            `json:"log_path"`
	// InspectError is set when ContainerInspect failed; logging facts are
	// then unknown rather than empty.
	InspectError string `json:"inspect_error,omitempty"`
}

Container is one entry of the container list plus the logging facts from inspect. LogPath is empty for drivers that do not report one (local).

type Daemon

type Daemon struct {
	Host            string `json:"host"`
	ServerVersion   string `json:"server_version"`
	APIVersion      string `json:"api_version"`
	OperatingSystem string `json:"operating_system"`
	StorageDriver   string `json:"storage_driver"`
	LoggingDriver   string `json:"logging_driver"`
	DataRoot        string `json:"data_root"`
	// ContainerdSnapshotter is true when the daemon keeps images in the
	// containerd image store (DriverStatus driver-type
	// io.containerd.snapshotter.v1) instead of a graph driver.
	ContainerdSnapshotter bool `json:"containerd_snapshotter,omitempty"`
	// Rootless is true when Info.SecurityOptions contains name=rootless.
	Rootless bool `json:"rootless,omitempty"`
}

Daemon describes the daemon the snapshot was taken from.

type Engine

type Engine interface {
	Snapshot(ctx context.Context) (*Snapshot, error)
}

Engine returns a point-in-time Snapshot of the daemon's disk usage.

type Image

type Image struct {
	ID         string            `json:"id"`
	RepoTags   []string          `json:"repo_tags"`
	Created    int64             `json:"created"`
	Size       int64             `json:"size"`
	SharedSize int64             `json:"shared_size"`
	Containers int64             `json:"containers"`
	Labels     map[string]string `json:"labels,omitempty"`
}

Image is one entry of the image list. SharedSize and Containers are -1 when the daemon did not compute them.

type Moby

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

Moby is the Engine backed by the official Docker client.

func NewMoby

func NewMoby(opts ...client.Opt) (*Moby, error)

NewMoby connects using the standard DOCKER_* environment variables; opts (for example from ResolveTarget) are applied after them. API version negotiation is the client's default. Every request passes readOnlyGuard, which refuses anything but GET/HEAD on the four endpoints dockdu reads. Connecting is lazy; the first call reports ErrDaemonUnreachable when the socket is not there.

func (*Moby) Close

func (m *Moby) Close() error

Close releases the underlying HTTP client.

func (*Moby) Host

func (m *Moby) Host() string

Host is the daemon address the client will use.

func (*Moby) Snapshot

func (m *Moby) Snapshot(ctx context.Context) (*Snapshot, error)

Snapshot performs Info, DiskUsage and one ContainerInspect per container. A failed inspect does not fail the snapshot; it is recorded on the container and in Warnings.

type Snapshot

type Snapshot struct {
	TakenAt    time.Time     `json:"taken_at"`
	Daemon     Daemon        `json:"daemon"`
	Totals     Totals        `json:"totals"`
	Images     []Image       `json:"images"`
	Containers []Container   `json:"containers"`
	Volumes    []Volume      `json:"volumes"`
	BuildCache []CacheRecord `json:"build_cache"`
	// Warnings are non-fatal problems met while taking the snapshot, for
	// example a container that could not be inspected.
	Warnings []string `json:"warnings,omitempty"`
}

Snapshot is everything dockdu reads from the daemon.

func LoadFixture

func LoadFixture(path string) (*Snapshot, error)

LoadFixture reads a Snapshot written by WriteFixture.

type Static

type Static struct{ S *Snapshot }

Static is an Engine that returns a fixed Snapshot. It backs unit tests.

func (Static) Snapshot

func (st Static) Snapshot(context.Context) (*Snapshot, error)

Snapshot returns a deep copy so collectors cannot mutate the fixture.

type Target added in v0.2.0

type Target struct {
	// Source is "DOCKER_HOST", `context "name"` or "default".
	Source string
	// Opts are passed to NewMoby; they are applied after client.FromEnv.
	Opts []client.Opt
}

Target is the daemon endpoint dockdu connects to and where that choice came from, so an unreachable daemon can be explained precisely.

func ResolveTarget added in v0.2.0

func ResolveTarget(getenv func(string) string, home string) (Target, error)

ResolveTarget picks the daemon the docker CLI would use, without running it: DOCKER_HOST wins, then DOCKER_CONTEXT, then currentContext from the CLI config file. Contexts are how Colima, OrbStack, rootless Docker and Docker Desktop on Linux point the CLI at a socket other than /var/run/docker.sock. Only unix://, npipe:// and tcp:// endpoints are supported; ssh:// needs the docker CLI as a connection helper, which dockdu does not run.

getenv is os.Getenv in production; home is the user's home directory.

type Totals

type Totals struct {
	Images     Aggregate `json:"images"`
	Containers Aggregate `json:"containers"`
	Volumes    Aggregate `json:"volumes"`
	BuildCache Aggregate `json:"build_cache"`
}

Totals are the per-type aggregates the daemon computes for `docker system df`. They are reported, never recomputed.

type Volume

type Volume struct {
	Name         string            `json:"name"`
	Driver       string            `json:"driver"`
	Mountpoint   string            `json:"mountpoint"`
	CreatedAt    string            `json:"created_at"`
	Labels       map[string]string `json:"labels,omitempty"`
	HasUsageData bool              `json:"has_usage_data"`
	Size         int64             `json:"size"`
	RefCount     int64             `json:"ref_count"`
}

Volume is one entry of the volume list. Size and RefCount are -1 when unknown; HasUsageData is false when the daemon sent no usage block at all.

Jump to

Keyboard shortcuts

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