docker

package module
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: BSD-3-Clause Imports: 29 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Docker

Helpers for working with the Docker Engine API: container names, Compose labels, mounts, networks, exec, logs, progress rendering, and volume usage

Go Reference License

Documentation

Overview

Package docker provides helpers for working with the Docker Engine API: container names and Compose labels, mount translation and preservation, network selection, exec and log streaming, progress rendering, and cached volume usage.

Index

Constants

View Source
const (
	ComposeProjectLabelKey = "com.docker.compose.project"
	ComposeServiceLabelKey = "com.docker.compose.service"
)

Docker Compose attaches these labels to every container it manages. They identify the owning project and the service within that project.

Variables

View Source
var ErrArchiveDirectory = errors.New("path is a directory")

Functions

func BuildNetworkUsageMaps

func BuildNetworkUsageMaps(containers []container.Summary) (map[string]bool, map[string]bool)

BuildNetworkUsageMaps indexes container network attachments by ID and name.

func ComposeProjectLabel

func ComposeProjectLabel(labels map[string]string) string

ComposeProjectLabel returns the trimmed Docker Compose project name from a container's labels, or "" when unset.

func ComposeServiceLabel

func ComposeServiceLabel(labels map[string]string) string

ComposeServiceLabel returns the trimmed Docker Compose service name from a container's labels, or "" when unset.

func ContainerAnswersToHostname

func ContainerAnswersToHostname(c *container.Summary, host string) bool

ContainerAnswersToHostname reports whether the container is addressable as host on some network: by container name, compose service name, or an endpoint DNS name/alias.

func ContainerNameExcluded

func ContainerNameExcluded(names []string, excluded map[string]bool) bool

ContainerNameExcluded reports whether any of Docker's container names, stripped of the leading slash, appears in the exclusion lookup.

func ContainerNameFromNames

func ContainerNameFromNames(names []string) string

ContainerNameFromNames returns Docker's first container name without the leading slash Docker stores in container summaries.

func CopyFromContainer added in v0.3.0

func CopyFromContainer(ctx context.Context, dockerClient *client.Client, containerID, sourcePath string) (io.ReadCloser, int64, error)

func CopyToContainer added in v0.3.0

func CopyToContainer(ctx context.Context, dockerClient *client.Client, containerID, destDir string, files map[string][]byte) error

func ExcludedContainerNameSet

func ExcludedContainerNameSet(raw string) map[string]bool

ExcludedContainerNameSet parses a comma-separated exclusion setting into a name lookup. Returns nil when the setting names no containers.

func ExecInContainer

func ExecInContainer(ctx context.Context, dockerClient *client.Client, req ExecRequest) (int, error)

ExecInContainer runs req in its container, demultiplexing output into req.Stdout and req.Stderr, and returns the exec's exit code. A non-zero exit code is not an error — callers decide how to report it.

func FetchVolumeUsageData

func FetchVolumeUsageData(ctx context.Context, dockerClient *client.Client) ([]volume.Volume, error)

FetchVolumeUsageData queries the daemon for volume usage, bypassing the cache.

func FilterContainersUsingVolume

func FilterContainersUsingVolume(containers []container.Summary, volumeName string) []string

FilterContainersUsingVolume returns the IDs of containers in the provided slice that mount the named volume. Use this when checking many volumes in a row — list containers once and reuse the slice.

func GetContainersUsingVolume

func GetContainersUsingVolume(ctx context.Context, dockerClient *client.Client, volumeName string) ([]string, error)

GetContainersUsingVolume lists all containers and returns IDs that mount the named volume. For batch checks (multiple volumes), prefer listing containers once via dockerClient.ContainerList and calling FilterContainersUsingVolume per volume.

func IsDefaultNetwork

func IsDefaultNetwork(name string) bool

IsDefaultNetwork reports whether name is one of Docker's built-in networks.

func IsExpectedStreamEndError

func IsExpectedStreamEndError(err error) bool

IsExpectedStreamEndError reports whether err is the ordinary way a Docker attach/log stream ends rather than a real failure.

func MountForDestination

func MountForDestination(mounts []container.MountPoint, destination, target string) *mount.Mount

MountForDestination returns a Mount suitable for container creation that mirrors an existing container mount at the given destination.

It currently supports bind and named volume mounts. If target is empty, destination is used as the target.

func MountForEnclosingPath

func MountForEnclosingPath(mounts []container.MountPoint, containerPath, target string) (*mount.Mount, string)

MountForEnclosingPath returns the most-specific mount covering containerPath mounted whole at target, plus containerPath's path relative to that mount. Unlike MountForSubpath the subpath need not exist yet, so restores can create it. Returns nil when no bind or volume mount covers containerPath.

func MountForSubpath

func MountForSubpath(mounts []container.MountPoint, containerPath, target string) *mount.Mount

MountForSubpath returns a Mount that exposes a subpath of one of the current container's existing mounts at the requested target. It's a generalisation of MountForDestination for the case where the caller wants a sub-tree below an existing mount destination (e.g. "/app/data/projects/X" when "/app/data" is what the container has mounted).

The function picks the most-specific mount whose Destination is a prefix of containerPath, then constructs the Mount based on the backing type:

  • TypeBind: Source = mount.Source joined with the relative subpath. Works because bind sources are real host paths the daemon can address directly.
  • TypeVolume: Source = mount.Name (the volume name), and the relative subpath is set on VolumeOptions.Subpath. This lets the daemon mount the named volume directly without needing a host-side path translation — important for setups where the underlying volume storage is opaque (Docker Desktop on WSL2, Docker-in-Docker, etc.).

Returns nil if no mount destination is a prefix of containerPath or if the matching mount is of an unsupported type.

func NestedMounts

func NestedMounts(mounts []container.MountPoint, containerPath, target string) []mount.Mount

NestedMounts mirrors every bind or volume mount whose destination lies strictly below containerPath, re-targeted beneath target, so a helper container sees the same tree the current container does. Parents precede their children; unsupported mount types are skipped.

func NewLogLineWriter

func NewLogLineWriter(dst io.Writer) io.WriteCloser

NewLogLineWriter returns a writer that splits everything written to it on newlines and emits each line as a {"log":"<line>"} NDJSON frame to dst, flushing after each frame when dst supports it. Close flushes any trailing partial line as a final frame. Writers such as compose's plain progress renderer and jsonmessage.DisplayJSONMessagesStream write raw CLI text into this to put docker-CLI-parity output on the wire.

func PreserveVolumeMounts

func PreserveVolumeMounts(ctx context.Context, binds []string, mounts []mount.Mount, mountPoints []container.MountPoint) ([]string, []mount.Mount, error)

PreserveVolumeMounts returns cloned binds and mounts with every inspected volume pinned to its name, so a recreate reuses it instead of a new anonymous one.

func ReadLogLines

func ReadLogLines(ctx context.Context, reader io.Reader, logsChan chan<- string, prefix string) error

ReadLogLines sends each non-empty line from reader to logsChan, prepending prefix, until EOF or ctx is done. Lines longer than 1 MiB are split.

func RenderJSONMessageStream

func RenderJSONMessageStream(reader io.Reader, out io.Writer) error

RenderJSONMessageStream renders a Docker JSON message stream (image pull, push, build, load) as the raw text the docker CLI prints in non-TTY mode, writing it to out. Any daemon-reported error is returned verbatim.

func SelectAutoNetworkMode

func SelectAutoNetworkMode(inspect *container.InspectResponse) string

SelectAutoNetworkMode picks the network mode a helper container should share with the inspected container, preferring user-defined networks over defaults.

func SelectDockerHostReachableNetworkMode

func SelectDockerHostReachableNetworkMode(ctx context.Context, dockerClient *client.Client, inspect *container.InspectResponse, dockerHost string) string

SelectDockerHostReachableNetworkMode picks the network for a helper container that must reach a tcp DOCKER_HOST (e.g. a docker-socket-proxy). When the DOCKER_HOST hostname matches a running container — by name, compose service, or DNS alias — that shares a network with the current container, that shared network wins. SelectAutoNetworkMode's alphabetical heuristic routinely lands on an unrelated external network on multi-network setups, leaving the helper unable to reach the daemon.

func StartStdCopy

func StartStdCopy(stream io.Reader, stdout, stderr io.Writer) <-chan error

StartStdCopy demultiplexes a Docker stream into stdout/stderr on a goroutine and reports the copy result on the returned channel. A nil stdout or stderr discards that stream. Pair with WaitStdCopy.

func StreamContainerLogs

func StreamContainerLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string, opts LogOptions) error

StreamContainerLogs streams Docker container logs, handling TTY raw streams and non-TTY multiplexed stdout/stderr streams.

func StreamMultiplexedLogs

func StreamMultiplexedLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string) error

StreamMultiplexedLogs demultiplexes a Docker stdout/stderr log stream and sends non-empty lines to logsChan. logs is closed when ctx is done so a blocked read unblocks.

func WaitStdCopy

func WaitStdCopy(done <-chan error) error

WaitStdCopy waits for a StartStdCopy goroutine, treating an ordinary stream end as success.

Types

type ExecRequest

type ExecRequest struct {
	// Stdout receives the exec's demultiplexed standard output; nil discards it.
	Stdout io.Writer
	// Stderr receives the exec's demultiplexed standard error; nil discards it.
	Stderr io.Writer
	// ContainerID is the container the exec runs in.
	ContainerID string
	// Options configures the exec, e.g. its command and environment.
	Options client.ExecCreateOptions
}

ExecRequest describes one exec run by ExecInContainer.

type LogOptions

type LogOptions struct {
	// TTY marks a raw TTY stream; otherwise the stream is stdout/stderr multiplexed.
	TTY bool
}

LogOptions describes the log stream StreamContainerLogs reads.

type VolumeUsageCache added in v0.3.4

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

VolumeUsageCache caches Docker daemon volume usage snapshots per daemon host, sharing in-flight refreshes across concurrent callers.

func NewVolumeUsageCache added in v0.3.4

func NewVolumeUsageCache(cfg VolumeUsageCacheConfig) *VolumeUsageCache

NewVolumeUsageCache constructs a VolumeUsageCache with the given configuration.

func (*VolumeUsageCache) Get added in v0.3.4

func (c *VolumeUsageCache) Get(ctx context.Context, dockerClient *client.Client) ([]volume.Volume, error)

Get returns current volume usage data, sharing an in-flight refresh with concurrent callers while allowing each caller to honor its own context.

func (*VolumeUsageCache) GetStaleWhileRevalidate added in v0.3.4

func (c *VolumeUsageCache) GetStaleWhileRevalidate(ctx context.Context, dockerClient *client.Client) mo.Option[[]volume.Volume]

GetStaleWhileRevalidate returns immediately with any cached snapshot and starts a bounded refresh when the snapshot is stale or missing.

func (*VolumeUsageCache) Invalidate added in v0.3.4

func (c *VolumeUsageCache) Invalidate(dockerClient *client.Client)

Invalidate removes cached usage data for the Docker daemon used by dockerClient.

type VolumeUsageCacheConfig added in v0.3.4

type VolumeUsageCacheConfig struct {
	Logger         *slog.Logger
	Capacity       int
	TTL            time.Duration
	RefreshTimeout time.Duration
}

VolumeUsageCacheConfig configures a VolumeUsageCache. Zero fields use defaults.

Directories

Path Synopsis
Package compat gates newer Docker daemon features behind the API version a daemon actually speaks, so container creation works against older daemons.
Package compat gates newer Docker daemon features behind the API version a daemon actually speaks, so container creation works against older daemons.
convert module
streams
agg
Package agg provides JSON-lines fan-in helpers for aggregated streams.
Package agg provides JSON-lines fan-in helpers for aggregated streams.
bus
Package bus provides typed in-process pub/sub fan-out primitives.
Package bus provides typed in-process pub/sub fan-out primitives.
internal/buffer
Package buffer resolves optional channel buffer sizes for streams configs.
Package buffer resolves optional channel buffer sizes for streams configs.
logs
Package logs captures slog output into a bounded in-memory ring buffer and fans it out to live subscribers.
Package logs captures slog output into a bounded in-memory ring buffer and fans it out to live subscribers.
stats
Package stats stores compact container stats history samples.
Package stats stores compact container stats history samples.
Package types holds contracts shared between producers and consumers of the docker package.
Package types holds contracts shared between producers and consumers of the docker package.

Jump to

Keyboard shortcuts

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