dockercli

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const HelperImage = "alpine:3.22"

HelperImage is the Docker image used for file operations on volumes

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client provides higher-level helpers around docker CLI.

func New

func New(contextName string) *Client

func (*Client) CheckDaemon

func (c *Client) CheckDaemon(ctx context.Context) error

CheckDaemon verifies the docker daemon for the configured context is reachable.

func (*Client) ClearVolume added in v0.3.0

func (c *Client) ClearVolume(ctx context.Context, volumeName string) error

ClearVolume removes all contents of the volume's root directory.

func (*Client) ComposeConfigFull

func (c *Client) ComposeConfigFull(ctx context.Context, workingDir string, files, profiles, envFiles []string, inlineEnv []string) (ComposeConfigDoc, error)

ComposeConfigFull renders the effective compose config and parses desired services info (image, etc.).

func (*Client) ComposeConfigHash

func (c *Client) ComposeConfigHash(ctx context.Context, workingDir string, files, profiles, envFiles []string, projectName string, service string, identifier string, inlineEnv []string) (string, error)

ComposeConfigHash returns the compose config hash for a single service. If identifier is non-empty, a temporary overlay compose file is used to add the label `io.dockform.identifier: <identifier>` to that service before hashing.

func (*Client) ComposeConfigRaw added in v0.3.0

func (c *Client) ComposeConfigRaw(ctx context.Context, workingDir string, files, profiles, envFiles []string, inlineEnv []string) (string, error)

ComposeConfigRaw returns the fully resolved compose configuration as YAML text. It is equivalent to running `docker compose config` with the provided files, profiles and env files, resolved relative to workingDir. Inline environment variables are provided via the process environment for the command.

func (*Client) ComposeConfigServices

func (c *Client) ComposeConfigServices(ctx context.Context, workingDir string, files, profiles, envFiles []string, inlineEnv []string) ([]string, error)

ComposeConfigServices returns the list of service names that would be part of the project.

func (*Client) ComposePs

func (c *Client) ComposePs(ctx context.Context, workingDir string, files, profiles, envFiles []string, projectName string, inlineEnv []string) ([]ComposePsItem, error)

ComposePs lists running (or created) compose services for the project.

func (*Client) ComposeUp

func (c *Client) ComposeUp(ctx context.Context, workingDir string, files, profiles, envFiles []string, projectName string, inlineEnv []string) (string, error)

ComposeUp runs docker compose up -d with the given parameters. workingDir is where compose files and relative paths are resolved.

func (*Client) CreateNetwork

func (c *Client) CreateNetwork(ctx context.Context, name string, labels map[string]string, opts ...NetworkCreateOpts) error

func (*Client) CreateVolume

func (c *Client) CreateVolume(ctx context.Context, name string, labels map[string]string) error

func (*Client) ExtractTarToVolume

func (c *Client) ExtractTarToVolume(ctx context.Context, volumeName, targetPath string, r io.Reader) error

ExtractTarToVolume extracts a tar stream (stdin) into the volume targetPath without clearing existing files. It ensures targetPath exists.

func (*Client) ExtractZstdTarToVolume added in v0.3.0

func (c *Client) ExtractZstdTarToVolume(ctx context.Context, volumeName string, r io.Reader) error

ExtractZstdTarToVolume reads a zstd-compressed tar from r and extracts into the volume root.

func (*Client) InspectContainerLabels

func (c *Client) InspectContainerLabels(ctx context.Context, containerName string, keys []string) (map[string]string, error)

InspectContainerLabels returns selected labels from a container.

func (*Client) InspectMultipleContainerLabels

func (c *Client) InspectMultipleContainerLabels(ctx context.Context, containerNames []string, keys []string) (map[string]map[string]string, error)

InspectMultipleContainerLabels returns selected labels from multiple containers in a single call

func (*Client) InspectNetwork added in v0.3.0

func (c *Client) InspectNetwork(ctx context.Context, name string) (NetworkInspect, error)

InspectNetwork returns details about a docker network

func (*Client) InspectVolume added in v0.3.0

func (c *Client) InspectVolume(ctx context.Context, name string) (VolumeDetails, error)

InspectVolume returns driver/options/labels for a volume.

func (*Client) IsVolumeEmpty added in v0.3.0

func (c *Client) IsVolumeEmpty(ctx context.Context, volumeName string) (bool, error)

IsVolumeEmpty returns true if the volume has no files (ignores . and ..).

func (*Client) ListComposeContainersAll

func (c *Client) ListComposeContainersAll(ctx context.Context) ([]PsBrief, error)

ListComposeContainersAll lists all containers with compose labels (project/service) across the Docker context.

func (*Client) ListContainersUsingVolume added in v0.3.0

func (c *Client) ListContainersUsingVolume(ctx context.Context, volumeName string) ([]string, error)

ListContainersUsingVolume returns container names (running or stopped) that reference the volume.

func (*Client) ListNetworks

func (c *Client) ListNetworks(ctx context.Context) ([]string, error)

ListNetworks returns names of docker networks.

func (*Client) ListRunningContainersUsingVolume added in v0.3.0

func (c *Client) ListRunningContainersUsingVolume(ctx context.Context, volumeName string) ([]string, error)

ListRunningContainersUsingVolume returns names of running containers that reference the volume.

func (*Client) ListVolumes

func (c *Client) ListVolumes(ctx context.Context) ([]string, error)

ListVolumes returns names of docker volumes.

func (*Client) ReadFileFromVolume

func (c *Client) ReadFileFromVolume(ctx context.Context, volumeName, targetPath, relFile string) (string, error)

ReadFileFromVolume returns the contents of a file inside a mounted volume target path. If the file does not exist, it returns an empty string and no error.

func (*Client) RemoveContainer

func (c *Client) RemoveContainer(ctx context.Context, name string, force bool) error

RemoveContainer removes a container by name. If force is true, the container will be stopped if running and removed.

func (*Client) RemoveNetwork

func (c *Client) RemoveNetwork(ctx context.Context, name string) error

func (*Client) RemovePathsFromVolume

func (c *Client) RemovePathsFromVolume(ctx context.Context, volumeName, targetPath string, relPaths []string) error

RemovePathsFromVolume removes one or more relative paths from the mounted targetPath.

func (*Client) RemoveVolume

func (c *Client) RemoveVolume(ctx context.Context, name string) error

func (*Client) RestartContainer

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

RestartContainer restarts a container by name.

func (*Client) StartContainers added in v0.3.0

func (c *Client) StartContainers(ctx context.Context, names []string) error

StartContainers starts the given containers.

func (*Client) StopContainers added in v0.3.0

func (c *Client) StopContainers(ctx context.Context, names []string) error

StopContainers stops the given containers gracefully.

func (*Client) StreamTarFromVolume added in v0.3.0

func (c *Client) StreamTarFromVolume(ctx context.Context, volumeName string, w io.Writer) error

StreamTarFromVolume streams a tar of the root of the volume to w. The tar is created using numeric owners and includes xattrs/acls when supported.

func (*Client) StreamTarZstdFromVolume added in v0.3.0

func (c *Client) StreamTarZstdFromVolume(ctx context.Context, volumeName string, w io.Writer) error

StreamTarZstdFromVolume streams a zstd-compressed tar of the volume to w. It installs zstd in the helper container if missing (apk add).

func (*Client) SyncDirToVolume

func (c *Client) SyncDirToVolume(ctx context.Context, volumeName, targetPath, localDir string) error

SyncDirToVolume streams a tar of localDir to the named volume's targetPath. Requirements: - targetPath must be absolute and not '/' - Ensure destination exists in the helper container (mkdir -p) - Mount the volume at a fixed path in the helper container and operate there - Remove current contents then extract tar stream into targetPath

func (*Client) TarStatsFromVolume added in v0.3.0

func (c *Client) TarStatsFromVolume(ctx context.Context, volumeName string) (int64, int64, error)

TarStatsFromVolume calculates uncompressed tar size (bytes) and file count in the volume. It runs commands inside a helper container and returns (tarBytes, fileCount).

func (*Client) UpdateContainerLabels

func (c *Client) UpdateContainerLabels(ctx context.Context, containerName string, labels map[string]string) error

UpdateContainerLabels adds or updates labels for a running container.

func (*Client) VolumeExists

func (c *Client) VolumeExists(ctx context.Context, name string) (bool, error)

VolumeExists returns true if a volume with the given name exists in the Docker context, regardless of labels. This must not create the volume; it only lists existing names.

func (*Client) WithIdentifier

func (c *Client) WithIdentifier(id string) *Client

WithIdentifier sets an optional label identifier to scope discovery.

func (*Client) WriteFileToVolume

func (c *Client) WriteFileToVolume(ctx context.Context, volumeName, targetPath, relFile, content string) error

WriteFileToVolume writes content to a file inside a mounted volume target path, creating parent directories.

type ComposeConfigDoc

type ComposeConfigDoc struct {
	Services map[string]ComposeService `json:"services" yaml:"services"`
}

type ComposePort

type ComposePort struct {
	Target    int         `json:"target" yaml:"target"`
	Published interface{} `json:"published" yaml:"published"`
	Protocol  string      `json:"protocol" yaml:"protocol"`
}

type ComposePsItem

type ComposePsItem struct {
	Name       string             `json:"Name"`
	Service    string             `json:"Service"`
	Image      string             `json:"Image"`
	State      string             `json:"State"`
	Project    string             `json:"Project"`
	Publishers []ComposePublisher `json:"Publishers"`
}

ComposePsItem is a subset of fields from `docker compose ps --format json`.

type ComposePublisher

type ComposePublisher struct {
	URL           string `json:"URL"`
	TargetPort    int    `json:"TargetPort"`
	PublishedPort int    `json:"PublishedPort"`
	Protocol      string `json:"Protocol"`
}

type ComposeService

type ComposeService struct {
	Image string        `json:"image" yaml:"image"`
	Ports []ComposePort `json:"ports" yaml:"ports"`
}

type Exec

type Exec interface {
	Run(ctx context.Context, args ...string) (string, error)
	RunInDir(ctx context.Context, dir string, args ...string) (string, error)
	RunInDirWithEnv(ctx context.Context, dir string, extraEnv []string, args ...string) (string, error)
	RunWithStdin(ctx context.Context, stdin io.Reader, args ...string) (string, error)
	// RunWithStdout streams the stdout of the docker command to the provided writer without buffering it in memory.
	// Stderr is still captured and included in any returned error for debuggability.
	RunWithStdout(ctx context.Context, stdout io.Writer, args ...string) error
}

Exec abstracts docker command execution for ease of testing.

type ExecEvent

type ExecEvent struct {
	Phase    string // "start" or "finish"
	Args     []string
	Dir      string
	Duration time.Duration
	ExitCode int
	Err      error
}

ExecEvent describes a loggable moment in command execution.

type LoggerHook

type LoggerHook func(event ExecEvent)

LoggerHook receives start and finish events for command execution.

type NetworkCreateOpts added in v0.3.0

type NetworkCreateOpts struct {
	Driver       string
	Options      map[string]string
	Internal     bool
	Attachable   bool
	IPv6         bool
	Subnet       string
	Gateway      string
	IPRange      string
	AuxAddresses map[string]string
}

NetworkCreateOpts represents supported docker network create flags.

type NetworkInspect added in v0.3.0

type NetworkInspect struct {
	Name       string             `json:"Name"`
	Driver     string             `json:"Driver"`
	Options    map[string]string  `json:"Options"`
	Internal   bool               `json:"Internal"`
	Attachable bool               `json:"Attachable"`
	EnableIPv6 bool               `json:"EnableIPv6"`
	IPAM       NetworkInspectIPAM `json:"IPAM"`
	Containers map[string]struct {
		Name string `json:"Name"`
	} `json:"Containers"`
}

NetworkInspect represents the subset of docker network inspect we need

type NetworkInspectIPAM added in v0.3.0

type NetworkInspectIPAM struct {
	Driver string                     `json:"Driver"`
	Config []NetworkInspectIPAMConfig `json:"Config"`
}

NetworkInspectIPAM represents IPAM section of network inspect

type NetworkInspectIPAMConfig added in v0.3.0

type NetworkInspectIPAMConfig struct {
	Subnet       string            `json:"Subnet"`
	Gateway      string            `json:"Gateway"`
	IPRange      string            `json:"IPRange"`
	AuxAddresses map[string]string `json:"AuxiliaryAddresses"`
}

NetworkInspectIPAMConfig represents a single IPAM config entry

type Options

type Options struct {
	Dir     string
	Env     []string
	Stdin   io.Reader
	Timeout time.Duration
}

Options controls execution behavior per call.

type PsBrief

type PsBrief struct {
	Project string
	Service string
	Name    string
}

PsBrief represents a container with compose labels.

type Result

type Result struct {
	Stdout   string
	Stderr   string
	ExitCode int
	Duration time.Duration
}

Result contains structured outcome of a command.

type SystemExec

type SystemExec struct {
	ContextName    string
	DefaultTimeout time.Duration
	Logger         LoggerHook
}

SystemExec is a real implementation that shells out to the docker CLI.

func (SystemExec) Run

func (s SystemExec) Run(ctx context.Context, args ...string) (string, error)

func (SystemExec) RunDetailed

func (s SystemExec) RunDetailed(ctx context.Context, opts Options, args ...string) (Result, error)

func (SystemExec) RunInDir

func (s SystemExec) RunInDir(ctx context.Context, dir string, args ...string) (string, error)

func (SystemExec) RunInDirWithEnv

func (s SystemExec) RunInDirWithEnv(ctx context.Context, dir string, extraEnv []string, args ...string) (string, error)

func (SystemExec) RunWithStdin

func (s SystemExec) RunWithStdin(ctx context.Context, stdin io.Reader, args ...string) (string, error)

func (SystemExec) RunWithStdout added in v0.3.0

func (s SystemExec) RunWithStdout(ctx context.Context, stdout io.Writer, args ...string) error

RunWithStdout executes the docker command and streams stdout to the provided writer. It does not buffer stdout in memory.

func (*SystemExec) WithDefaultTimeout

func (s *SystemExec) WithDefaultTimeout(d time.Duration) *SystemExec

WithDefaultTimeout sets a default timeout for all runs when Options.Timeout is not provided.

func (*SystemExec) WithLogger

func (s *SystemExec) WithLogger(h LoggerHook) *SystemExec

WithLogger sets a logger hook to observe command execution.

type VolumeDetails added in v0.3.0

type VolumeDetails struct {
	Driver  string            `json:"Driver"`
	Options map[string]string `json:"Options"`
	Labels  map[string]string `json:"Labels"`
}

VolumeDetails contains driver, options and labels of a volume.

Jump to

Keyboard shortcuts

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