docker

package
v1.13.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ContextArchiveExts = []string{".dockercontext", ".tar.gz", ".tgz", ".tar"}

ContextArchiveExts lists supported Docker context archive extensions. Keep multi-part extensions before shorter suffixes when order matters.

Functions

func AddNodeLabel

func AddNodeLabel(ctx context.Context, nodeID string, key string, value string) error

AddNodeLabel adds or updates a label on a node.

func BuildRawLogArgs

func BuildRawLogArgs(ctxName, serviceID string, extra ...string) []string

BuildRawLogArgs constructs the docker CLI arguments for "service logs --raw". Extra flags (e.g. "--follow", "--details", "--tail", "100") are inserted before the serviceID.

func CheckContextExportExists

func CheckContextExportExists(contextName string) bool

CheckContextExportExists checks if an export file already exists for a context

func CreateConfig

func CreateConfig(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Config, error)

CreateConfig creates a new config with the given name and data

func CreateConfigVersion

func CreateConfigVersion(ctx context.Context, baseConfig swarm.Config, newData []byte) (swarm.Config, error)

CreateConfigVersion creates a new config, optionally using labels to mark lineage.

func CreateContext

func CreateContext(name, dockerHost string) error

CreateContext creates a new Docker context with the given name and Docker host

func CreateContextWithCertFiles

func CreateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, skipTLSVerify bool) error

CreateContextWithCertFiles creates a Docker context with specific certificate file paths

func CreateContextWithTLS

func CreateContextWithTLS(name, dockerHost, tlsPath string, skipTLSVerify bool) error

CreateContextWithTLS creates a new Docker context with optional TLS configuration

func CreateNetwork

func CreateNetwork(ctx context.Context, name string, opts network.CreateOptions) (string, []string, error)

CreateNetwork creates a new Docker network. Returns the created network ID and any daemon warnings.

func CreateSecret

func CreateSecret(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Secret, error)

CreateSecret creates a new secret with the given name and data

func CreateSecretVersion

func CreateSecretVersion(ctx context.Context, baseSecret swarm.Secret, newData []byte) (swarm.Secret, error)

CreateSecretVersion creates a new secret, optionally using labels to mark lineage.

func CreateService

func CreateService(ctx context.Context, spec swarm.ServiceSpec) (string, error)

CreateService creates a service with the given spec and returns the service ID

func DeleteConfig

func DeleteConfig(ctx context.Context, nameOrID string) error

DeleteConfig deletes a config only if it's not referenced by any service.

func DeleteContext

func DeleteContext(contextName string) error

DeleteContext removes a Docker context

func DeleteSecret

func DeleteSecret(ctx context.Context, nameOrID string) error

DeleteSecret deletes a secret only if it's not referenced by any service.

func DemoteNode

func DemoteNode(ctx context.Context, nodeID string) error

DemoteNode sets the node role to worker (demotes a manager).

func DeployStack

func DeployStack(stackName string, yamlContent string) error

DeployStack deploys a stack with the provided name and YAML content.

func ExportContext

func ExportContext(contextName string) (string, error)

ExportContext exports a Docker context to a tar file in /tmp

func ExportContextWithForce

func ExportContextWithForce(contextName string) (string, error)

ExportContextWithForce exports a Docker context, removing existing file if present

func GetClient

func GetClient() (*client.Client, error)

GetClient returns a Docker SDK client configured based on the current Docker context. The client is cached as a package-level singleton; subsequent calls return the cached instance without spawning subprocesses or pinging the daemon. Call ResetClient to force a fresh client (e.g. after a context switch).

func GetContainerCount

func GetContainerCount() (int, error)

func GetContextFromEnv

func GetContextFromEnv() (string, error)

GetContextFromEnv returns the docker context to use. It prefers the DOCKER_CONTEXT environment variable (so the app can be run against a specific context, e.g. in CI or local testing). If that variable is not set, it falls back to calling `docker context show` to retrieve the active context. The returned string will not contain a trailing newline.

func GetCurrentContext

func GetCurrentContext() (string, error)

GetCurrentContext returns the name of the active Docker context.

func GetDockerContext

func GetDockerContext() (string, error)

GetDockerContext returns the current Docker context name.

func GetDockerVersion

func GetDockerVersion() (string, error)

func GetLocalNodeID

func GetLocalNodeID(ctx context.Context) (string, error)

GetLocalNodeID returns the swarm node ID of the daemon the active Docker client is connected to, or "" if it is not an active swarm node.

func GetNodeIDToHostnameMap

func GetNodeIDToHostnameMap() (map[string]string, error)

GetNodeIDToHostnameMap returns a copy of the cached map. Automatically initializes the cache if needed.

func GetNodeIDToHostnameMapFromDocker

func GetNodeIDToHostnameMapFromDocker(ctx context.Context) (map[string]string, error)

func GetServiceCount

func GetServiceCount() (int, error)

func GetServiceLogs

func GetServiceLogs(ctx context.Context, serviceID string) (string, error)

GetServiceLogs fetches and returns the logs from a service

func GetServiceTaskDiagnostics

func GetServiceTaskDiagnostics(ctx context.Context, serviceID string) (string, error)

GetServiceTaskDiagnostics returns a human-readable summary of tasks for a service. This is useful when a service produces no logs (e.g., image pull errors).

func GetStackInspection

func GetStackInspection(stackName string) (string, error)

GetStackInspection returns detailed information about a stack in JSON format

func GetStackNetworks

func GetStackNetworks(ctx context.Context, stackName string) ([]string, error)

GetStackNetworks returns the names of networks associated with a stack

func GetSwarmCPUCapacity

func GetSwarmCPUCapacity() (float64, error)

GetSwarmCPUCapacity returns total CPU cores across all nodes (fast).

func GetSwarmCPUUsage

func GetSwarmCPUUsage() (string, error)

GetSwarmCPUUsage returns actual CPU usage across running containers.

func GetSwarmMemCapacity

func GetSwarmMemCapacity() (int64, error)

GetSwarmMemCapacity returns total memory across all nodes (fast).

func GetSwarmMemUsage

func GetSwarmMemUsage() (string, error)

GetSwarmMemUsage returns actual memory usage across running containers.

func GetSwarmResourceUsage

func GetSwarmResourceUsage() (cpuPct string, memPct string, err error)

GetSwarmResourceUsage returns CPU and memory usage in a single pass, making one ContainerList call and one ContainerStats call per container instead of two separate passes. This halves the Docker API calls compared to calling GetSwarmCPUUsage + GetSwarmMemUsage independently.

func ImportContext

func ImportContext(filePath string) (string, error)

ImportContext imports a Docker context from an archive file Returns the name of the imported context

func Inspect

func Inspect(ctx context.Context, t InspectType, id string) (string, error)

Inspect fetches and returns structured JSON for any Docker object.

func InspectContext

func InspectContext(contextName string) (string, error)

InspectContext returns the detailed JSON inspection of a Docker context

func InspectNetwork

func InspectNetwork(ctx context.Context, networkID string) (network.Inspect, error)

InspectNetwork returns detailed information about a network

func InspectVolume

func InspectVolume(ctx context.Context, name string) (volume.Volume, error)

InspectVolume returns the raw SDK volume for the given name on the connected node.

func InvalidateSnapshot

func InvalidateSnapshot()

InvalidateSnapshot clears the cached snapshot, forcing a fresh fetch on next access. This should be called after a Docker context switch.

func IsSwarmLockedErr

func IsSwarmLockedErr(err error) bool

IsSwarmLockedErr reports whether err is the Docker daemon's "swarm is locked" error. A locked swarm is reachable (ping/info succeed) but every store-backed call (node/service/task/stack list, ...) fails with this message until the swarm is unlocked. See docs.docker.com/engine/swarm/swarm_manager_locking.

func ListConfigs

func ListConfigs(ctx context.Context) ([]swarm.Config, error)

ListConfigs retrieves all Docker Swarm configs.

func ListNetworks

func ListNetworks(ctx context.Context) ([]network.Summary, error)

ListNetworks returns all networks in the swarm

func ListSecrets

func ListSecrets(ctx context.Context) ([]swarm.Secret, error)

ListSecrets retrieves all Docker Swarm secrets.

func ListServicesUsingConfigID

func ListServicesUsingConfigID(ctx context.Context, configID string) ([]swarm.Service, error)

ListServicesUsingConfigID returns all services that reference a config by ID

func ListServicesUsingConfigName

func ListServicesUsingConfigName(ctx context.Context, name string) ([]swarm.Service, error)

ListServicesUsingConfigName returns all services that reference a config by name

func ListServicesUsingNetwork

func ListServicesUsingNetwork(ctx context.Context, networkID, networkName string) ([]string, error)

ListServicesUsingNetwork returns all services that are connected to a network. In Swarm, service network targets can be specified by ID or by name.

func ListServicesUsingSecretID

func ListServicesUsingSecretID(ctx context.Context, secretID string) ([]swarm.Service, error)

ListServicesUsingSecretID returns all services that reference a secret by ID

func ListServicesUsingSecretName

func ListServicesUsingSecretName(ctx context.Context, name string) ([]swarm.Service, error)

ListServicesUsingSecretName returns all services that reference a secret by name

func PromoteNode

func PromoteNode(ctx context.Context, nodeID string) error

PromoteNode sets the node role to manager (promotes a worker).

func PruneNetworks

func PruneNetworks(ctx context.Context) (network.PruneReport, error)

PruneNetworks removes all unused networks

func ReconstructStackCompose

func ReconstructStackCompose(stackName string) (string, error)

ReconstructStackCompose reconstructs a Docker Compose file from a running stack

func RefreshHostnameCache

func RefreshHostnameCache() error

RefreshHostnameCache forcibly refreshes the cache (e.g. triggered by UI). Safe to call concurrently.

func RefreshSnapshotAsync

func RefreshSnapshotAsync()

RefreshSnapshotAsync triggers a background refresh if one is not already running. It returns immediately.

func RemoveNetwork

func RemoveNetwork(ctx context.Context, networkID string) error

RemoveNetwork removes a network

func RemoveNode

func RemoveNode(ctx context.Context, nodeID string, force bool) error

RemoveNode removes a node from the swarm.

func RemoveNodeLabel

func RemoveNodeLabel(ctx context.Context, nodeID string, key string) error

RemoveNodeLabel removes a label from a node

func RemoveService

func RemoveService(ctx context.Context, serviceName string) error

RemoveService removes a service by name.

func RemoveStack

func RemoveStack(ctx context.Context, stackName string) error

RemoveStack removes all services in a stack by stack name.

func RemoveStackCLI

func RemoveStackCLI(stackName string) error

RemoveStackCLI tears down a stack via `docker stack rm`, the symmetric counterpart to DeployStack. Unlike RemoveStack (services only), this removes the stack's services, networks, configs and secrets while leaving volumes intact — matching standard Docker stack semantics.

func RemoveStackNetworks

func RemoveStackNetworks(ctx context.Context, stackName string) error

RemoveStackNetworks removes all networks associated with a stack

func RemoveVolume

func RemoveVolume(ctx context.Context, name string, force bool) error

RemoveVolume removes a named volume on the connected node. force deletes it even if it is referenced. Like ListVolumes, this acts on the connected node only; cross-node removal is left as an extension point.

func ResetClient

func ResetClient()

ResetClient closes the cached client (if any) and clears the cache so the next GetClient call creates a fresh connection. Safe to call when no client has been cached yet.

func RestartService

func RestartService(ctx context.Context, serviceName string) error

RestartService performs a rolling restart (like `docker service update --force`).

func RestartServiceAndWait

func RestartServiceAndWait(ctx context.Context, serviceName string) error

func RestartServiceWithProgress

func RestartServiceWithProgress(ctx context.Context, serviceName string, progressCh chan<- ProgressUpdate) error

func RollbackService

func RollbackService(ctx context.Context, serviceName string) error

RollbackService rolls back a service to its previous configuration.

func RotateConfigInServices

func RotateConfigInServices(ctx context.Context, oldCfg *swarm.Config, newCfg swarm.Config) error

RotateConfigInServices updates all services that reference oldCfg to use newCfg. If oldCfg is nil, it tries to infer affected services automatically based on labels or content.

func RotateSecretInServices

func RotateSecretInServices(ctx context.Context, oldSec *swarm.Secret, newSec swarm.Secret) error

RotateSecretInServices updates all services that reference oldSec to use newSec. If oldSec is nil, it tries to infer affected services automatically based on labels or content.

func ScaleService

func ScaleService(ctx context.Context, serviceID string, replicas uint64) error

ScaleService updates the replica count of a service by ID.

func ScaleServiceByName

func ScaleServiceByName(ctx context.Context, serviceName string, replicas uint64) error

ScaleServiceByName looks up a service by name and scales it.

func SetNodeAvailability

func SetNodeAvailability(ctx context.Context, nodeID string, availability swarm.NodeAvailability) error

SetNodeAvailability sets the availability of a node (active, pause, drain).

func SetSnapshot

func SetSnapshot(s *SwarmSnapshot)

SetSnapshot replaces the cached snapshot (useful for manual refresh).

func StructFieldsAsStringArray

func StructFieldsAsStringArray(v interface{}) []string

func TriggerRefreshIfNeeded

func TriggerRefreshIfNeeded()

TriggerRefreshIfNeeded will check the cache TTL and start a background refresh if the snapshot is empty or stale. Note: there is a benign TOCTOU race between the staleness check and the async refresh start — the worst case is a redundant refresh, which is harmless.

func UnlockSwarm

func UnlockSwarm(ctx context.Context, key string) error

UnlockSwarm submits the unlock key to the daemon for the current context.

func UpdateContextDescription

func UpdateContextDescription(name, description string) error

UpdateContextDescription updates only the description of a Docker context

func UpdateContextWithCertFiles

func UpdateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, skipTLSVerify bool) error

UpdateContextWithCertFiles updates a Docker context with specific certificate file paths

func UseContext

func UseContext(contextName string) error

UseContext switches to the specified Docker context

func ValidateContext

func ValidateContext(ctx context.Context, contextName string) error

ValidateContext checks if a context switch would succeed by attempting to connect

func ValidateStackYAML

func ValidateStackYAML(content string) error

ValidateStackYAML validates that the provided YAML content is a valid Docker Compose file.

Types

type ClientOps

type ClientOps interface {
	GetClient() (*client.Client, error)
	ResetClient()
}

ClientOps abstracts Docker client lifecycle for testability and extensibility.

type ClusterInfoOps

type ClusterInfoOps interface {
	GetCurrentContext() (string, error)
	GetContainerCount() (int, error)
	GetServiceCount() (int, error)
	GetSwarmCPUCapacity() (float64, error)
	GetSwarmMemCapacity() (int64, error)
	GetSwarmCPUUsage() (string, error)
	GetSwarmMemUsage() (string, error)
	GetSwarmResourceUsage() (cpuPct, memPct string, err error)
	GetDockerVersion() (string, error)
}

ClusterInfoOps abstracts cluster info queries for testability and extensibility.

type ComposeFile

type ComposeFile struct {
	Version  string                    `yaml:"version"`
	Services map[string]ComposeService `yaml:"services"`
	Networks map[string]map[string]any `yaml:"networks,omitempty"`
	Volumes  map[string]map[string]any `yaml:"volumes,omitempty"`
	Secrets  map[string]map[string]any `yaml:"secrets,omitempty"`
	Configs  map[string]map[string]any `yaml:"configs,omitempty"`
}

ComposeFile represents a Docker Compose file structure

type ComposeService

type ComposeService struct {
	Image       string            `yaml:"image,omitempty"`
	Command     any               `yaml:"command,omitempty"` // string or []string
	Entrypoint  any               `yaml:"entrypoint,omitempty"`
	WorkingDir  string            `yaml:"working_dir,omitempty"`
	User        string            `yaml:"user,omitempty"`
	Environment map[string]string `yaml:"environment,omitempty"`
	Labels      map[string]string `yaml:"labels,omitempty"`
	Ports       []string          `yaml:"ports,omitempty"`
	Networks    any               `yaml:"networks,omitempty"` // []string or map
	Volumes     []string          `yaml:"volumes,omitempty"`
	Secrets     []map[string]any  `yaml:"secrets,omitempty"`
	Configs     []map[string]any  `yaml:"configs,omitempty"`
	// Container runtime / security settings that round-trip through
	// `docker stack deploy` (see #430).
	Hostname        string            `yaml:"hostname,omitempty"`
	CapAdd          []string          `yaml:"cap_add,omitempty"`
	CapDrop         []string          `yaml:"cap_drop,omitempty"`
	Sysctls         map[string]string `yaml:"sysctls,omitempty"`
	Ulimits         map[string]any    `yaml:"ulimits,omitempty"`
	ExtraHosts      []string          `yaml:"extra_hosts,omitempty"`
	DNS             []string          `yaml:"dns,omitempty"`
	DNSSearch       []string          `yaml:"dns_search,omitempty"`
	DNSOpt          []string          `yaml:"dns_opt,omitempty"`
	ReadOnly        bool              `yaml:"read_only,omitempty"`
	Init            *bool             `yaml:"init,omitempty"`
	StopSignal      string            `yaml:"stop_signal,omitempty"`
	StopGracePeriod string            `yaml:"stop_grace_period,omitempty"`
	Deploy          map[string]any    `yaml:"deploy,omitempty"`
	Healthcheck     *Healthcheck      `yaml:"healthcheck,omitempty"`
	Logging         *Logging          `yaml:"logging,omitempty"`
	Extra           map[string]any    `yaml:",inline,omitempty"` // fallback
}

ComposeService represents a service in a Docker Compose file

type ConfigOps

type ConfigOps interface {
	ListConfigs(ctx context.Context) ([]swarm.Config, error)
	InspectConfig(ctx context.Context, nameOrID string) (*ConfigWithDecodedData, error)
	CreateConfig(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Config, error)
	CreateConfigVersion(ctx context.Context, baseConfig swarm.Config, newData []byte) (swarm.Config, error)
	RotateConfigInServices(ctx context.Context, oldCfg *swarm.Config, newCfg swarm.Config) error
	DeleteConfig(ctx context.Context, nameOrID string) error
	ListServicesUsingConfigID(ctx context.Context, configID string) ([]swarm.Service, error)
	ListServicesUsingConfigName(ctx context.Context, name string) ([]swarm.Service, error)
}

ConfigOps abstracts config operations for testability and extensibility.

type ConfigRef

type ConfigRef struct {
	ConfigID   string `json:"ConfigID"`
	ConfigName string `json:"ConfigName"`
	File       *struct {
		Name string `json:"Name"`
		UID  string `json:"UID,omitempty"`
		GID  string `json:"GID,omitempty"`
		Mode uint32 `json:"Mode,omitempty"`
	} `json:"File,omitempty"`
}

ConfigRef represents a config reference

type ConfigWithDecodedData

type ConfigWithDecodedData struct {
	Config swarm.Config
	Data   []byte
}

ConfigWithDecodedData is a helper struct with the decoded data included.

func InspectConfig

func InspectConfig(ctx context.Context, nameOrID string) (*ConfigWithDecodedData, error)

InspectConfig fetches and returns the config data.

func (*ConfigWithDecodedData) DisplayData

func (cfg *ConfigWithDecodedData) DisplayData() []byte

DisplayData returns the config payload in a human-readable form. Some payloads are stored gzip-compressed (e.g. SwarmCLI chart release records); those are transparently decompressed so the inspect/raw views show text rather than binary. Non-gzip payloads are returned unchanged.

func (*ConfigWithDecodedData) JSON

func (cfg *ConfigWithDecodedData) JSON() ([]byte, error)

func (*ConfigWithDecodedData) PrettyJSON

func (cfg *ConfigWithDecodedData) PrettyJSON() ([]byte, error)

PrettyJSON returns the JSON representation of the config, but pretty-printed (indented) for human-readable editing.

type ContainerSpec

type ContainerSpec struct {
	Image    string            `json:"Image"`
	Args     []string          `json:"Args,omitempty"`
	Command  []string          `json:"Command,omitempty"`
	Env      []string          `json:"Env,omitempty"`
	Dir      string            `json:"Dir,omitempty"`
	User     string            `json:"User,omitempty"`
	Hostname string            `json:"Hostname,omitempty"`
	Labels   map[string]string `json:"Labels,omitempty"`
	Mounts   []Mount           `json:"Mounts,omitempty"`
	Secrets  []SecretRef       `json:"Secrets,omitempty"`
	Configs  []ConfigRef       `json:"Configs,omitempty"`
	// Healthcheck durations arrive as nanosecond integers over the
	// `docker service inspect` CLI JSON.
	Healthcheck *HealthConfigJSON `json:"Healthcheck,omitempty"`
	// Runtime / security fields (see #430). StopGracePeriod is a nanosecond
	// integer; Init is a tri-state pointer (nil = inherit image default).
	CapabilityAdd   []string          `json:"CapabilityAdd,omitempty"`
	CapabilityDrop  []string          `json:"CapabilityDrop,omitempty"`
	Sysctls         map[string]string `json:"Sysctls,omitempty"`
	Ulimits         []Ulimit          `json:"Ulimits,omitempty"`
	Hosts           []string          `json:"Hosts,omitempty"`
	DNSConfig       *DNSConfig        `json:"DNSConfig,omitempty"`
	ReadOnly        bool              `json:"ReadOnly,omitempty"`
	Init            *bool             `json:"Init,omitempty"`
	StopSignal      string            `json:"StopSignal,omitempty"`
	StopGracePeriod int64             `json:"StopGracePeriod,omitempty"`
}

ContainerSpec represents the container specification

type ContextInfo

type ContextInfo struct {
	Name        string
	Current     bool
	Description string
	DockerHost  string
	TLS         bool
	Error       string
}

ContextInfo represents a Docker context with its metadata

func ListContexts

func ListContexts() ([]ContextInfo, error)

ListContexts returns all available Docker contexts using docker CLI

type ContextOps

type ContextOps interface {
	ListContexts() ([]ContextInfo, error)
	UseContext(contextName string) error
	ValidateContext(ctx context.Context, contextName string) error
	InspectContext(contextName string) (string, error)
	ExportContext(contextName string) (string, error)
	ExportContextWithForce(contextName string) (string, error)
	CheckContextExportExists(contextName string) bool
	DeleteContext(contextName string) error
	ImportContext(filePath string) (string, error)
	CreateContext(name, dockerHost string) error
	CreateContextWithTLS(name, dockerHost, tlsPath string, skipTLSVerify bool) error
	CreateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, skipTLSVerify bool) error
	UpdateContextDescription(name, description string) error
	UpdateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, skipTLSVerify bool) error
}

ContextOps abstracts Docker context operations for testability and extensibility.

type DNSConfig

type DNSConfig struct {
	Nameservers []string `json:"Nameservers,omitempty"`
	Search      []string `json:"Search,omitempty"`
	Options     []string `json:"Options,omitempty"`
}

DNSConfig mirrors the Swarm ContainerSpec.DNSConfig block.

type Deps

type Deps struct {
	Services    ServiceOps
	Nodes       NodeOps
	Tasks       TaskOps
	Stacks      StackOps
	Configs     ConfigOps
	Secrets     SecretOps
	Networks    NetworkOps
	Volumes     VolumeOps
	Contexts    ContextOps
	Snapshot    SnapshotOps
	ClusterInfo ClusterInfoOps
	Inspect     InspectOps
	Events      EventOps
	Client      ClientOps
	Hostname    HostnameOps
}

Deps aggregates all Docker operation interfaces. Views and commands receive this to access Docker operations through interfaces rather than package-level functions.

func DefaultDeps

func DefaultDeps() Deps

DefaultDeps returns a Deps with all default implementations that delegate to the existing package-level functions.

type EndpointSpec

type EndpointSpec struct {
	Mode  string       `json:"Mode,omitempty"` // vip/dnsrr
	Ports []PortConfig `json:"Ports,omitempty"`
}

EndpointSpec represents the endpoint specification

type Event

type Event struct {
	Type   string
	Action string
	Err    error
}

Event represents a Docker event (or an error/timeout while watching).

func WatchEvent

func WatchEvent() Event

WatchEvent listens for Docker events (service/config/network/node changes) using the Docker SDK and returns a single Event when one is observed. This is a blocking call; callers should wrap it in a goroutine or tea.Cmd.

type EventOps

type EventOps interface {
	WatchEvent() Event
}

EventOps abstracts Docker event watching for testability and extensibility.

type HealthConfigJSON

type HealthConfigJSON struct {
	Test          []string `json:"Test,omitempty"`
	Interval      int64    `json:"Interval,omitempty"`
	Timeout       int64    `json:"Timeout,omitempty"`
	StartPeriod   int64    `json:"StartPeriod,omitempty"`
	StartInterval int64    `json:"StartInterval,omitempty"`
	Retries       int      `json:"Retries,omitempty"`
}

HealthConfigJSON captures the Healthcheck block of a `docker service inspect` ContainerSpec. Durations are nanosecond integers.

type Healthcheck

type Healthcheck struct {
	Test          []string `json:"test,omitempty" yaml:"test,omitempty"`
	Interval      string   `json:"interval,omitempty" yaml:"interval,omitempty"`
	Timeout       string   `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	StartPeriod   string   `json:"start_period,omitempty" yaml:"start_period,omitempty"`
	StartInterval string   `json:"start_interval,omitempty" yaml:"start_interval,omitempty"`
	Retries       int      `json:"retries,omitempty" yaml:"retries,omitempty"`
	Disable       bool     `json:"disable,omitempty" yaml:"disable,omitempty"`
}

Healthcheck is the compose-shaped view of a service healthcheck, used both in reconstructed Compose YAML and in stack-inspect JSON. Durations are rendered as compose duration strings (e.g. "30s").

type HostnameOps

type HostnameOps interface {
	RefreshHostnameCache() error
	GetNodeIDToHostnameMap() (map[string]string, error)
}

HostnameOps abstracts hostname cache operations for testability and extensibility.

type InspectOps

type InspectOps interface {
	Inspect(ctx context.Context, t InspectType, id string) (string, error)
}

InspectOps abstracts resource inspection for testability and extensibility.

type InspectType

type InspectType string

InspectType enumerates supported resource types for inspect

const (
	InspectNode      InspectType = "node"
	InspectService   InspectType = "service"
	InspectContainer InspectType = "container"
	InspectStack     InspectType = "stack"
)

type LogDriver

type LogDriver struct {
	Name    string            `json:"Name,omitempty"`
	Options map[string]string `json:"Options,omitempty"`
}

LogDriver represents the Swarm `TaskTemplate.LogDriver` (`*swarm.Driver`): the logging driver name plus its options. It is nil when the service does not pin a log driver (the daemon default is used).

type Logging

type Logging struct {
	Driver  string            `json:"driver,omitempty" yaml:"driver,omitempty"`
	Options map[string]string `json:"options,omitempty" yaml:"options,omitempty"`
}

Logging is the compose-shaped view of a service's log driver, mirroring the Swarm `TaskTemplate.LogDriver` (`*swarm.Driver`). It is used both in reconstructed Compose YAML and in stack-inspect JSON. The compose `logging:` block carries a `driver:` name and an `options:` map.

type Mount

type Mount struct {
	Type        string `json:"Type"` // bind, volume, tmpfs
	Source      string `json:"Source,omitempty"`
	Target      string `json:"Target,omitempty"`
	ReadOnly    bool   `json:"ReadOnly,omitempty"`
	BindOptions *struct {
		Propagation string `json:"Propagation,omitempty"`
	} `json:"BindOptions,omitempty"`
	VolumeOptions *struct {
		NoCopy       bool              `json:"NoCopy,omitempty"`
		Labels       map[string]string `json:"Labels,omitempty"`
		DriverConfig *struct {
			Name    string            `json:"Name,omitempty"`
			Options map[string]string `json:"Options,omitempty"`
		} `json:"DriverConfig,omitempty"`
	} `json:"VolumeOptions,omitempty"`
	TmpfsOptions *struct {
		SizeBytes int64  `json:"SizeBytes,omitempty"`
		Mode      uint32 `json:"Mode,omitempty"`
	} `json:"TmpfsOptions,omitempty"`
}

Mount represents a mount specification

type NetRef

type NetRef struct {
	Target  string   `json:"Target"` // network ID
	Aliases []string `json:"Aliases,omitempty"`
}

NetRef represents a network reference

type NetworkOps

type NetworkOps interface {
	ListNetworks(ctx context.Context) ([]network.Summary, error)
	InspectNetwork(ctx context.Context, networkID string) (network.Inspect, error)
	RemoveNetwork(ctx context.Context, networkID string) error
	CreateNetwork(ctx context.Context, name string, opts network.CreateOptions) (string, []string, error)
	PruneNetworks(ctx context.Context) (network.PruneReport, error)
	ListServicesUsingNetwork(ctx context.Context, networkID, networkName string) ([]string, error)
}

NetworkOps abstracts network operations for testability and extensibility.

type NetworkWithUsage

type NetworkWithUsage struct {
	Network  network.Summary
	Services []string // Services using this network
}

NetworkWithUsage is a helper struct that includes usage information

func (*NetworkWithUsage) JSON

func (nw *NetworkWithUsage) JSON() ([]byte, error)

type NodeEntry

type NodeEntry struct {
	ID            string
	Version       string
	Hostname      string
	Role          string
	State         string
	Availability  string
	Manager       bool
	Addr          string
	Labels        map[string]string
	ManagerStatus string // Leader, Reachable, Unreachable, or ""
}

type NodeOps

type NodeOps interface {
	GetNodeIDToHostnameMapFromDocker(ctx context.Context) (map[string]string, error)
	DemoteNode(ctx context.Context, nodeID string) error
	PromoteNode(ctx context.Context, nodeID string) error
	SetNodeAvailability(ctx context.Context, nodeID string, availability swarm.NodeAvailability) error
	AddNodeLabel(ctx context.Context, nodeID, key, value string) error
	RemoveNodeLabel(ctx context.Context, nodeID, key string) error
	RemoveNode(ctx context.Context, nodeID string, force bool) error
}

NodeOps abstracts node operations for testability and extensibility.

type PartialListError

type PartialListError struct {
	NodeErrors map[string]string // node identifier -> error summary
	Note       string            // optional banner override; takes precedence over NodeErrors
}

PartialListError reports that a listing succeeded but is degraded: the returned items are valid and shown, with a non-fatal banner explaining the limitation, instead of failing outright. An aggregating implementation returns it when some nodes are unreachable (NodeErrors), or with a custom Note when the listing fell back to a narrower scope (e.g. connected-node only because the cross-node path is unavailable). The default single-node implementation never returns it.

func (*PartialListError) Error

func (e *PartialListError) Error() string

type Placement

type Placement struct {
	Constraints []string `json:"Constraints,omitempty"`
	Preferences []any    `json:"Preferences,omitempty"`
	MaxReplicas *uint64  `json:"MaxReplicas,omitempty"`
}

Placement represents placement constraints

type PortConfig

type PortConfig struct {
	Protocol      string `json:"Protocol,omitempty"` // tcp/udp
	TargetPort    uint32 `json:"TargetPort,omitempty"`
	PublishedPort uint32 `json:"PublishedPort,omitempty"`
	PublishMode   string `json:"PublishMode,omitempty"` // ingress/host
}

PortConfig represents a port configuration

type ProgressUpdate

type ProgressUpdate struct {
	Replaced int
	Running  int
	Total    int
}

type ResourceSpec

type ResourceSpec struct {
	NanoCPUs    int64 `json:"NanoCPUs,omitempty"`
	MemoryBytes int64 `json:"MemoryBytes,omitempty"`
	Pids        int64 `json:"Pids,omitempty"`
}

ResourceSpec represents resource specifications. Pids is only ever set on the Limits side (Swarm carries no reservation pids).

type Resources

type Resources struct {
	Limits       *ResourceSpec `json:"Limits,omitempty"`
	Reservations *ResourceSpec `json:"Reservations,omitempty"`
}

Resources represents resource constraints

type RestartPolicy

type RestartPolicy struct {
	Condition   string  `json:"Condition,omitempty"`
	Delay       int64   `json:"Delay,omitempty"`
	MaxAttempts *uint64 `json:"MaxAttempts,omitempty"`
	Window      int64   `json:"Window,omitempty"`
}

RestartPolicy represents the restart policy

type SecretOps

type SecretOps interface {
	ListSecrets(ctx context.Context) ([]swarm.Secret, error)
	InspectSecret(ctx context.Context, nameOrID string) (*SecretWithDecodedData, error)
	CreateSecret(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Secret, error)
	CreateSecretVersion(ctx context.Context, baseSecret swarm.Secret, newData []byte) (swarm.Secret, error)
	RotateSecretInServices(ctx context.Context, oldSec *swarm.Secret, newSec swarm.Secret) error
	DeleteSecret(ctx context.Context, nameOrID string) error
	ListServicesUsingSecretID(ctx context.Context, secretID string) ([]swarm.Service, error)
	ListServicesUsingSecretName(ctx context.Context, name string) ([]swarm.Service, error)
}

SecretOps abstracts secret operations for testability and extensibility.

type SecretRef

type SecretRef struct {
	SecretID   string `json:"SecretID"`
	SecretName string `json:"SecretName"`
	File       *struct {
		Name string `json:"Name"`
		UID  string `json:"UID,omitempty"`
		GID  string `json:"GID,omitempty"`
		Mode uint32 `json:"Mode,omitempty"`
	} `json:"File,omitempty"`
}

SecretRef represents a secret reference

type SecretWithDecodedData

type SecretWithDecodedData struct {
	Secret swarm.Secret
	Data   []byte // This will typically be nil/empty as secrets data cannot be retrieved
}

SecretWithDecodedData is a helper struct with the decoded data included. Note: Docker API doesn't return secret data for security reasons

func InspectSecret

func InspectSecret(ctx context.Context, nameOrID string) (*SecretWithDecodedData, error)

InspectSecret fetches and returns the secret metadata. Note: Docker API does not return secret data for security reasons.

func (*SecretWithDecodedData) JSON

func (sec *SecretWithDecodedData) JSON() ([]byte, error)

func (*SecretWithDecodedData) PrettyJSON

func (sec *SecretWithDecodedData) PrettyJSON() ([]byte, error)

PrettyJSON returns the JSON representation of the secret, but pretty-printed (indented) for human-readable editing.

type ServiceEntry

type ServiceEntry struct {
	StackName      string
	ServiceName    string
	ServiceID      string
	ReplicasOnNode int
	ReplicasTotal  int
	Status         string
	Mode           string
	Image          string
	Ports          string
	// Health is an aggregate health summary for the service's running replicas
	// (e.g. "2/2 healthy"); "" when unknown. The swarm API does not expose
	// container health, so the default loaders leave it empty; it is an
	// extension point populated by a ServiceOps decorator that can reach
	// per-node container state.
	Health string
	// PullProgress summarizes an image pull in flight for this service's tasks
	// (e.g. "pulling · 3/12 layers · 412 MB"); "" when nothing is being pulled or
	// the progress is unavailable. Like Health it is an extension point populated
	// by a ServiceOps decorator that can reach the nodes performing the pull; the
	// services view shows it in place of Status while it is set, since a service
	// whose image is still downloading otherwise reads as a bare "active".
	PullProgress string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func LoadAllServices

func LoadAllServices() []ServiceEntry

LoadAllServices returns every service in the swarm, across all stacks (including services with no stack, shown as "-"). Equivalent to `docker service ls`.

func LoadNodeServices

func LoadNodeServices(nodeID string) []ServiceEntry

func LoadStackServices

func LoadStackServices(stackName string) []ServiceEntry

type ServiceInspect

type ServiceInspect struct {
	Spec ServiceSpec `json:"Spec"`
}

ServiceInspect represents Docker service inspect output (partial)

type ServiceMode

type ServiceMode struct {
	Replicated *struct {
		Replicas *uint64 `json:"Replicas"`
	} `json:"Replicated,omitempty"`
	Global any `json:"Global,omitempty"`
}

ServiceMode represents the service mode (replicated or global)

type ServiceOps

type ServiceOps interface {
	ScaleService(ctx context.Context, serviceID string, replicas uint64) error
	ScaleServiceByName(ctx context.Context, serviceName string, replicas uint64) error
	RestartService(ctx context.Context, serviceName string) error
	RemoveService(ctx context.Context, serviceName string) error
	RollbackService(ctx context.Context, serviceName string) error
	RestartServiceAndWait(ctx context.Context, serviceName string) error
	RestartServiceWithProgress(ctx context.Context, serviceName string, progressCh chan<- ProgressUpdate) error
	LoadNodeServices(nodeID string) []ServiceEntry
	LoadStackServices(stackName string) []ServiceEntry
	LoadAllServices() []ServiceEntry
	GetServiceLogs(ctx context.Context, serviceID string) (string, error)
	GetServiceTaskDiagnostics(ctx context.Context, serviceID string) (string, error)
	CreateService(ctx context.Context, spec swarm.ServiceSpec) (string, error)
}

ServiceOps abstracts service operations for testability and extensibility.

type ServiceSpec

type ServiceSpec struct {
	Name           string            `json:"Name"`
	Labels         map[string]string `json:"Labels"`
	TaskTemplate   TaskTemplate      `json:"TaskTemplate"`
	Mode           ServiceMode       `json:"Mode"`
	Networks       []NetRef          `json:"Networks"`
	EndpointSpec   *EndpointSpec     `json:"EndpointSpec,omitempty"`
	UpdateConfig   *UpdateConfig     `json:"UpdateConfig,omitempty"`
	RollbackConfig *UpdateConfig     `json:"RollbackConfig,omitempty"`
}

ServiceSpec represents the service specification

type ServiceSummary

type ServiceSummary struct {
	Name            string            `json:"name"`
	ID              string            `json:"id"`
	Image           string            `json:"image"`
	Mode            string            `json:"mode"`
	Replicas        string            `json:"replicas"`
	Ports           []string          `json:"ports,omitempty"`
	Secrets         []string          `json:"secrets,omitempty"`
	Configs         []string          `json:"configs,omitempty"`
	Labels          map[string]string `json:"labels,omitempty"`
	ContainerLabels map[string]string `json:"container_labels,omitempty"`
	Healthcheck     *Healthcheck      `json:"healthcheck,omitempty"`
	Logging         *Logging          `json:"logging,omitempty"`
	CreatedAt       time.Time         `json:"created_at"`
	UpdatedAt       time.Time         `json:"updated_at"`
}

ServiceSummary contains summary information about a service

type SnapshotOps

type SnapshotOps interface {
	GetSnapshot() *SwarmSnapshot
	SetSnapshot(s *SwarmSnapshot)
	InvalidateSnapshot()
	RefreshSnapshot() (*SwarmSnapshot, error)
	RefreshSnapshotAsync()
	TriggerRefreshIfNeeded()
	GetOrRefreshSnapshot() (*SwarmSnapshot, error)
}

SnapshotOps abstracts snapshot cache operations for testability and extensibility.

type Stack

type Stack struct {
	Name         string
	ServiceCount int
}

Stack represents a unique Docker stack.

type StackEntry

type StackEntry struct {
	Name         string
	ServiceCount int
	NodeCount    int
}

StackEntry is a lightweight representation of a Docker stack, used for display and cached in SwarmSnapshot.

type StackInspection

type StackInspection struct {
	Name         string           `json:"name"`
	Services     []ServiceSummary `json:"services"`
	Networks     []string         `json:"networks,omitempty"`
	Volumes      []string         `json:"volumes,omitempty"`
	Secrets      []string         `json:"secrets,omitempty"`
	Configs      []string         `json:"configs,omitempty"`
	ServiceCount int              `json:"service_count"`
	TaskCount    int              `json:"task_count"`
	CreatedAt    time.Time        `json:"created_at,omitempty"`
	UpdatedAt    time.Time        `json:"updated_at,omitempty"`
}

StackInspection contains detailed information about a stack

type StackOps

type StackOps interface {
	RemoveStack(ctx context.Context, stackName string) error
	RemoveStackNetworks(ctx context.Context, stackName string) error
	DeployStack(stackName string, yamlContent string) error
	ValidateStackYAML(content string) error
	InspectStack(stackName string) (string, error)
	ReconstructStackCompose(stackName string) (string, error)
}

StackOps abstracts stack operations for testability and extensibility.

type StackService

type StackService struct {
	NodeID         string
	StackName      string
	ServiceName    string
	ServiceID      string
	ReplicasOnNode int
	ReplicasTotal  int
}

StackService is a lightweight representation of a Swarm service within a stack.

type SwarmNode

type SwarmNode struct {
	ID            string
	Hostname      string
	Status        string
	Availability  string
	ManagerStatus string
}

func (SwarmNode) String

func (s SwarmNode) String() string

type SwarmSnapshot

type SwarmSnapshot struct {
	Nodes     []swarm.Node
	Services  []swarm.Service
	Tasks     []swarm.Task
	Fetched   time.Time
	ClusterID string
	// Locked is true when the swarm is reachable but encrypted/locked. In that
	// case the entity lists are empty until the swarm is unlocked.
	Locked bool
}

SwarmSnapshot contains the in-memory swarm state.

func GetOrRefreshSnapshot

func GetOrRefreshSnapshot() (*SwarmSnapshot, error)

GetOrRefreshSnapshot returns the current snapshot, refreshing it if the cache is empty or too old.

func GetSnapshot

func GetSnapshot() *SwarmSnapshot

GetSnapshot returns the cached snapshot if it's still valid.

func RefreshSnapshot

func RefreshSnapshot() (*SwarmSnapshot, error)

RefreshSnapshot fetches all swarm data (nodes, services, tasks) at once and updates the global cache.

func (*SwarmSnapshot) FindService

func (s *SwarmSnapshot) FindService(serviceID string) *swarm.Service

FindService looks up a service by ID in the snapshot.

func (*SwarmSnapshot) FindServiceByName

func (s *SwarmSnapshot) FindServiceByName(name string) *swarm.Service

FindServiceByName looks up a service by its name in the snapshot.

func (SwarmSnapshot) ToNodeEntries

func (s SwarmSnapshot) ToNodeEntries() []NodeEntry

ToNodeEntries converts the full nodes into display-friendly entries.

func (SwarmSnapshot) ToStackEntries

func (s SwarmSnapshot) ToStackEntries() []StackEntry

ToStackEntries aggregates services by stack name and produces StackEntry slices.

type TaskEntry

type TaskEntry struct {
	ID           string
	Name         string
	ServiceName  string
	Image        string
	NodeName     string
	ContainerID  string
	DesiredState string
	CurrentState string
	Error        string
	Ports        string
	// Health is the container-level health status (e.g. "healthy",
	// "unhealthy", "starting"); "" when the container has no healthcheck or
	// the status is unknown. The swarm task snapshot does not carry it, so the
	// default loaders leave it empty; it is an extension point populated by a
	// TaskOps decorator that can reach per-node container state.
	Health string
	// ContainerState is the container's live lifecycle state as reported by the
	// on-node agent (e.g. "running", "restarting", "exited", "dead"); "" by
	// default. Like Health it is an extension point populated by a TaskOps
	// decorator. Unlike CurrentState (the swarm task state) it reflects the
	// container's `docker ps` state, which the remote Swarm API cannot report;
	// the services view shows it as a fallback when Health is empty so container
	// errors surface even for images without a healthcheck.
	ContainerState string
	// PullProgress summarizes the image pull the task's node is currently
	// performing for it (e.g. "pulling · 3/12 layers · 412 MB"); "" when nothing
	// is being pulled or the progress is unavailable. A task whose image is still
	// downloading sits in "preparing" with no further detail — the Swarm API
	// carries no pull progress at all — so the default loaders leave this empty;
	// it is an extension point populated by a TaskOps decorator that can reach
	// the node performing the pull.
	PullProgress string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

TaskEntry represents a task in a human-readable format

func GetTasksForService

func GetTasksForService(serviceID string) ([]TaskEntry, error)

GetTasksForService returns all tasks for a specific service ID from the cached snapshot.

func GetTasksForStack

func GetTasksForStack(stackName string) ([]TaskEntry, error)

GetTasksForStack returns all tasks for services in the given stack

func (TaskEntry) StatusText

func (t TaskEntry) StatusText() string

StatusText is the task's status cell: the live image-pull summary when a decorator supplied one (a pulling task otherwise shows only a bare "preparing"), else the swarm task state.

type TaskOps

type TaskOps interface {
	GetTasksForStack(stackName string) ([]TaskEntry, error)
	GetTasksForService(serviceID string) ([]TaskEntry, error)
}

TaskOps abstracts task query operations for testability and extensibility.

type TaskTemplate

type TaskTemplate struct {
	ContainerSpec *ContainerSpec `json:"ContainerSpec,omitempty"`
	Resources     *Resources     `json:"Resources,omitempty"`
	RestartPolicy *RestartPolicy `json:"RestartPolicy,omitempty"`
	Placement     *Placement     `json:"Placement,omitempty"`
	Networks      []NetRef       `json:"Networks,omitempty"`
	ForceUpdate   uint64         `json:"ForceUpdate,omitempty"`
	LogDriver     *LogDriver     `json:"LogDriver,omitempty"`
}

TaskTemplate represents the task template specification

type Ulimit

type Ulimit struct {
	Name string `json:"Name"`
	Hard int64  `json:"Hard"`
	Soft int64  `json:"Soft"`
}

Ulimit mirrors a Swarm ContainerSpec ulimit entry (go-units `Ulimit`, which carries no JSON tags, so the keys are PascalCase).

type UpdateConfig

type UpdateConfig struct {
	Parallelism     uint64  `json:"Parallelism,omitempty"`
	Delay           int64   `json:"Delay,omitempty"`
	FailureAction   string  `json:"FailureAction,omitempty"`
	Monitor         int64   `json:"Monitor,omitempty"`
	MaxFailureRatio float32 `json:"MaxFailureRatio,omitempty"`
	Order           string  `json:"Order,omitempty"`
}

UpdateConfig mirrors the Swarm `UpdateConfig` (used for both the update and rollback strategies). Durations (Delay, Monitor) arrive as nanosecond integers over the `docker service inspect` CLI JSON.

type VolumeInfo

type VolumeInfo struct {
	Name       string
	Stack      string // com.docker.stack.namespace label, "" if not stack-managed
	Driver     string
	Mountpoint string
	Created    time.Time
	Host       string // node hostname the volume lives on (display)
	NodeID     string // swarm node ID the volume lives on; "" for the CE single-node impl, filled by aggregating implementations for node-addressed actions
	Labels     map[string]string
	Raw        *volume.Volume // underlying SDK object, for inspect
}

VolumeInfo is the edition-agnostic view of a Docker volume consumed by the volumes view. The default (CE) implementation populates it from the connected node only; the Host field is an extension point so an implementation that aggregates across all swarm nodes can report which node each volume lives on.

func ListVolumes

func ListVolumes(ctx context.Context) ([]VolumeInfo, error)

ListVolumes returns the volumes on the connected Docker node.

docker volume ls is per-node: this lists only the volumes local to the daemon the current context points at. Listing volumes across every swarm node requires reaching each node individually and is left as an extension point (see VolumeOps).

type VolumeOps

type VolumeOps interface {
	ListVolumes(ctx context.Context) ([]VolumeInfo, error)
	InspectVolume(ctx context.Context, name string) (volume.Volume, error)
}

VolumeOps abstracts volume operations for testability and extensibility.

The default implementation lists volumes on the connected node only. Implementations that aggregate volumes across all swarm nodes can be substituted via Deps without changing the volumes view.

Jump to

Keyboard shortcuts

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