docker

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package docker wraps the Docker SDK client. client.go provides a singleton Docker client and basic connectivity check.

containers.go fetches container list, live stats, and exposes control actions.

demo.go provides fake Docker data for running dockviz without a live Docker daemon. Used with the --demo flag for portfolio demonstrations and CI previews.

diskusage.go computes a `docker system df`-style disk usage breakdown and exposes one prune action per resource category (images, containers, volumes, build cache, container logs). Each category's reported ReclaimMB always matches exactly what its Prune* method will free, so the TUI never shows a number the prune action can't deliver.

events.go streams Docker container lifecycle events from the daemon.

images.go fetches the list of local Docker images.

interface.go defines the DockerClient interface. Both the real Client and DemoClient implement this, allowing the TUI to work identically in live and demo modes.

logs.go provides real-time log streaming for a container. It wraps the Docker ContainerLogs API with a simple channel-based interface so the TUI can receive log lines asynchronously via Bubble Tea commands.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatSize

func FormatSize(mb float64) string

FormatSize returns a human-readable size string.

Types

type Client

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

Client wraps the Docker SDK client with a shared context.

func NewClient

func NewClient(host string) (*Client, error)

NewClient creates and validates a connection to the Docker daemon. host overrides the DOCKER_HOST environment variable when non-empty (e.g. "tcp://192.168.1.100:2375"). Pass "" to use the env var or default socket.

func (*Client) Close

func (c *Client) Close()

Close releases the underlying HTTP connection.

func (*Client) DiskUsage added in v0.4.6

func (c *Client) DiskUsage() (DiskUsageInfo, error)

DiskUsage fetches and summarizes Docker's disk usage, mirroring `docker system df` plus a Logs category that `docker system df` doesn't account for at all.

func (*Client) FetchStats

func (c *Client) FetchStats(id string) (cpu float64, memMB float64, err error)

FetchStats fetches a single-shot stats snapshot for a container.

func (*Client) ListContainers

func (c *Client) ListContainers() ([]ContainerInfo, error)

ListContainers returns all containers (running + stopped).

func (*Client) ListImages

func (c *Client) ListImages() ([]ImageInfo, error)

ListImages returns all locally available Docker images, one row per tag.

func (*Client) PruneBuildCache added in v0.4.6

func (c *Client) PruneBuildCache() (float64, error)

PruneBuildCache removes build cache layers not in use by a running build.

func (*Client) PruneContainers added in v0.4.6

func (c *Client) PruneContainers() (float64, error)

PruneContainers removes stopped ("created"/"exited"/"dead") containers.

func (*Client) PruneImages added in v0.4.6

func (c *Client) PruneImages() (float64, error)

PruneImages removes dangling (untagged) images — the leftovers of repeated rebuilds. Tagged images still referenced by a name are never touched.

func (*Client) PruneLogs added in v0.5.0

func (c *Client) PruneLogs() (float64, error)

PruneLogs truncates every container's active log file to zero bytes and removes any rotated siblings (<path>.1, <path>.2, ...). The active file is truncated in place rather than removed: the daemon holds it open for the life of the container, and unlinking it would leave the space allocated until the daemon next reopens it. This never touches the container itself — a running container keeps writing to the same (now-empty) file.

func (*Client) PruneVolumes added in v0.4.6

func (c *Client) PruneVolumes() (float64, error)

PruneVolumes removes local volumes not attached to any container. The "all" filter is required because on API >=1.42 the daemon otherwise restricts pruning to anonymous volumes only, which would silently leave named-but-unattached volumes on disk despite DiskUsage reporting them as reclaimable.

func (*Client) RemoveContainer

func (c *Client) RemoveContainer(id string) error

RemoveContainer force-removes a container regardless of its running state. Equivalent to `docker rm -f <id>`.

func (*Client) RemoveImage added in v0.2.2

func (c *Client) RemoveImage(id string) error

RemoveImage removes a local image by tag name (safe default: only removes that tag).

func (*Client) StreamEvents added in v0.3.0

func (c *Client) StreamEvents(ctx context.Context) <-chan EventInfo

StreamEvents streams container lifecycle events from the Docker daemon. It includes events from the past hour so the initial view is populated. The returned channel is closed when ctx is cancelled.

func (*Client) StreamLogs

func (c *Client) StreamLogs(ctx context.Context, id string) <-chan LogLine

StreamLogs streams the last 50 lines of existing logs followed by live output for the given container ID. Log lines are sent on the returned channel. Cancel the provided context to stop the goroutine and close the channel.

Docker log streams use an 8-byte multiplexed framing (stdcopy format) for non-TTY containers. stdcopy.StdCopy demultiplexes the stream correctly, avoiding the data corruption that naive byte-slicing causes.

type ContainerInfo

type ContainerInfo struct {
	ID             string
	Name           string
	Image          string
	Status         string  // "running", "stopped", "paused", etc.
	CPUPerc        float64 // percentage 0-100
	MemMB          float64 // megabytes
	CPULimit       float64
	MemoryLimitMB  float64
	LimitsKnown    bool
	ComposeProject string
	ComposeService string
	Ports          string   // human-readable port bindings
	Volumes        []string // mount points, e.g. ["/host/path → /ctr/path", "vol → /data:ro"]
}

ContainerInfo holds the data shown in the TUI list.

type DemoClient

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

DemoClient mimics Client but returns static/animated fake data.

func NewDemoClient

func NewDemoClient() *DemoClient

NewDemoClient returns a demo client that needs no Docker daemon.

func (*DemoClient) Close

func (d *DemoClient) Close()

Close is a no-op for demo mode.

func (*DemoClient) DiskUsage added in v0.4.6

func (d *DemoClient) DiskUsage() (DiskUsageInfo, error)

DiskUsage returns a static fake breakdown, shrunk per-category after the matching PruneX method has been called so the demo prune flow looks real.

func (*DemoClient) FetchStats

func (d *DemoClient) FetchStats(id string) (float64, float64, error)

FetchStats returns animated fake stats (not used — stats are inlined in ListContainers for demo).

func (*DemoClient) ListContainers

func (d *DemoClient) ListContainers() ([]ContainerInfo, error)

ListContainers returns a realistic set of fake containers.

func (*DemoClient) ListImages

func (d *DemoClient) ListImages() ([]ImageInfo, error)

ListImages returns fake image data.

func (*DemoClient) Ping

func (d *DemoClient) Ping() error

Ping always succeeds in demo mode.

func (*DemoClient) PruneBuildCache added in v0.4.6

func (d *DemoClient) PruneBuildCache() (float64, error)

PruneBuildCache simulates removing unused build cache.

func (*DemoClient) PruneContainers added in v0.4.6

func (d *DemoClient) PruneContainers() (float64, error)

PruneContainers simulates removing stopped containers.

func (*DemoClient) PruneImages added in v0.4.6

func (d *DemoClient) PruneImages() (float64, error)

PruneImages simulates removing dangling images.

func (*DemoClient) PruneLogs added in v0.5.0

func (d *DemoClient) PruneLogs() (float64, error)

PruneLogs simulates truncating container log files.

func (*DemoClient) PruneVolumes added in v0.4.6

func (d *DemoClient) PruneVolumes() (float64, error)

PruneVolumes simulates removing unattached volumes.

func (*DemoClient) RemoveContainer

func (d *DemoClient) RemoveContainer(id string) error

RemoveContainer simulates a container removal with a short delay.

func (*DemoClient) RemoveImage added in v0.2.2

func (d *DemoClient) RemoveImage(id string) error

RemoveImage simulates an image removal.

func (*DemoClient) StreamEvents added in v0.3.0

func (d *DemoClient) StreamEvents(ctx context.Context) <-chan EventInfo

StreamEvents emits a sequence of realistic fake Docker events for demo mode. It first sends a batch of historical events, then generates new events every few seconds.

func (*DemoClient) StreamLogs

func (d *DemoClient) StreamLogs(ctx context.Context, id string) <-chan LogLine

StreamLogs simulates a live log stream with pre-canned demo lines. Each line is emitted with a 500ms delay to mimic a real service.

type DiskUsageCategory added in v0.4.6

type DiskUsageCategory struct {
	Label     string  // display name, e.g. "Images"
	Total     int     // total object count
	Active    int     // objects currently in use
	SizeMB    float64 // total size on disk
	ReclaimMB float64 // size Prune would free for this category
	// Unknown is the number of objects whose size or reclaimability could not
	// be measured. It is deliberately separate from zero: zero means the
	// daemon measured no bytes, while Unknown means the answer is unavailable.
	Unknown int
	// OutsidePruneMB is known unused space that the selected safe prune action
	// intentionally does not remove. It is currently used for tagged images.
	OutsidePruneMB float64
	// Unavailable, when non-empty, explains why this category couldn't be
	// fully measured (e.g. filesystem permission denied) so the TUI can
	// show that instead of a misleadingly clean 0.
	Unavailable string
}

DiskUsageCategory holds the disk usage breakdown for one resource type.

type DiskUsageInfo added in v0.4.6

type DiskUsageInfo struct {
	Images     DiskUsageCategory
	Containers DiskUsageCategory
	Volumes    DiskUsageCategory
	BuildCache DiskUsageCategory
	// Logs is container stdout/stderr log files on disk. `docker system df`
	// never counts these — its container size only covers the RW layer —
	// so an unrotated json-file log is a common source of disk usage that
	// stays invisible until the disk fills up.
	Logs DiskUsageCategory
	// HostStorage describes Docker Desktop's host-side virtual disk when it
	// can be measured locally. It is informational only; docker prune actions
	// do not shrink this file.
	HostStorage HostStorageInfo
}

DiskUsageInfo is the full disk usage breakdown, one category per resource type.

type DockerClient

type DockerClient interface {
	ListContainers() ([]ContainerInfo, error)
	ListImages() ([]ImageInfo, error)
	FetchStats(id string) (cpu float64, memMB float64, err error)
	// RemoveContainer force-removes a container (running or stopped).
	RemoveContainer(id string) error
	// RemoveImage removes a local image by ID or tag.
	RemoveImage(id string) error
	// DiskUsage returns a docker-system-df-style breakdown of images,
	// containers, volumes, and build cache, plus a Logs category that
	// `docker system df` itself doesn't account for.
	DiskUsage() (DiskUsageInfo, error)
	// PruneImages removes dangling (untagged) images.
	PruneImages() (freedMB float64, err error)
	// PruneContainers removes stopped containers.
	PruneContainers() (freedMB float64, err error)
	// PruneVolumes removes volumes not attached to any container.
	PruneVolumes() (freedMB float64, err error)
	// PruneBuildCache removes unused build cache layers.
	PruneBuildCache() (freedMB float64, err error)
	// PruneLogs truncates container log files. Never removes a container.
	PruneLogs() (freedMB float64, err error)
	// StreamLogs streams the last 50 lines + live log output for a container.
	// Cancel the provided context to stop the stream.
	StreamLogs(ctx context.Context, id string) <-chan LogLine
	// StreamEvents streams container lifecycle events (start, stop, die, etc.).
	// Includes the past hour of events on first call, then live from there.
	// Cancel the provided context to stop the stream.
	StreamEvents(ctx context.Context) <-chan EventInfo
	Close()
}

DockerClient is the interface the TUI depends on. The real Client and DemoClient both satisfy it.

type EventInfo added in v0.3.0

type EventInfo struct {
	Time          time.Time
	Action        string // start, stop, die, create, destroy, kill, restart, pause, unpause
	ContainerName string
	ContainerID   string // short 12-char ID
	ExitCode      int    // populated on container/die (0=clean, 137=SIGKILL, 1=error)
	OOMKilled     bool   // populated on container/die when oomKilled attribute is "true"
	Disconnected  bool   // sentinel: stream was interrupted by an error
}

EventInfo represents a single Docker container lifecycle event. When Disconnected is true, the event stream has been interrupted (daemon restart, network drop, etc.) and no further events will arrive until the stream is restarted. All other fields are zero in this case.

type HostStorageInfo added in v0.5.0

type HostStorageInfo struct {
	Label       string
	Kind        string
	Path        string
	AllocatedMB float64
	HostFreeMB  float64
	Available   bool
	Unavailable string
}

HostStorageInfo describes storage owned by the local Docker runtime outside Docker's daemon-level system/df accounting. On Windows Docker Desktop WSL2 this is the docker_data.vhdx file that can stay expanded after docker prune.

type ImageInfo

type ImageInfo struct {
	ID      string
	Tag     string   // 이 행의 단일 태그, 또는 "<none>"
	AllTags []string // 이 image ID의 모든 태그 (삭제 경고 표시용)
	SizeMB  float64
}

ImageInfo holds display data for one Docker image row (one tag per row).

type LogLine

type LogLine struct {
	Text string
}

LogLine carries a single line of log output from a container.

Jump to

Keyboard shortcuts

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