Documentation
¶
Index ¶
- Variables
- func AddNodeLabel(ctx context.Context, nodeID string, key string, value string) error
- func BuildRawLogArgs(ctxName, serviceID string, extra ...string) []string
- func CheckContextExportExists(contextName string) bool
- func ClientFor(ctxName string) (*client.Client, error)
- func CreateConfig(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Config, error)
- func CreateConfigVersion(ctx context.Context, baseConfig swarm.Config, newData []byte) (swarm.Config, error)
- func CreateConfigWith(ctx context.Context, cli *client.Client, name string, data []byte, ...) (swarm.Config, error)
- func CreateContext(name, dockerHost string) error
- func CreateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, ...) error
- func CreateContextWithTLS(name, dockerHost, tlsPath string, skipTLSVerify bool) error
- func CreateNetwork(ctx context.Context, name string, opts network.CreateOptions) (string, []string, error)
- func CreateNetworkWith(ctx context.Context, cli *client.Client, name string, ...) (string, []string, error)
- func CreateSecret(ctx context.Context, name string, data []byte, labels map[string]string) (swarm.Secret, error)
- func CreateSecretVersion(ctx context.Context, baseSecret swarm.Secret, newData []byte) (swarm.Secret, error)
- func CreateService(ctx context.Context, spec swarm.ServiceSpec) (string, error)
- func DeleteConfig(ctx context.Context, nameOrID string) error
- func DeleteConfigWith(ctx context.Context, cli *client.Client, nameOrID string) error
- func DeleteContext(contextName string) error
- func DeleteSecret(ctx context.Context, nameOrID string) error
- func DemoteNode(ctx context.Context, nodeID string) error
- func DeployStack(stackName string, yamlContent string) error
- func DeployStackInContext(ctx context.Context, ctxName, stackName, yamlContent string, ...) error
- func DeployStackResolved(ctx context.Context, stackName string, yamlContent string, ...) error
- func ExportContext(contextName string) (string, error)
- func ExportContextWithForce(contextName string) (string, error)
- func GetClient() (*client.Client, error)
- func GetContainerCount() (int, error)
- func GetContextFromEnv() (string, error)
- func GetCurrentContext() (string, error)
- func GetDockerContext() (string, error)
- func GetDockerVersion() (string, error)
- func GetLocalNodeID(ctx context.Context) (string, error)
- func GetNodeIDToHostnameMap() (map[string]string, error)
- func GetNodeIDToHostnameMapFromDocker(ctx context.Context) (map[string]string, error)
- func GetServiceCount() (int, error)
- func GetServiceLogs(ctx context.Context, serviceID string) (string, error)
- func GetServiceTaskDiagnostics(ctx context.Context, serviceID string) (string, error)
- func GetStackInspection(stackName string) (string, error)
- func GetStackNetworks(ctx context.Context, stackName string) ([]string, error)
- func GetSwarmCPUCapacity() (float64, error)
- func GetSwarmCPUUsage() (string, error)
- func GetSwarmMemCapacity() (int64, error)
- func GetSwarmMemUsage() (string, error)
- func GetSwarmResourceUsage() (cpuPct string, memPct string, err error)
- func ImportContext(filePath string) (string, error)
- func Inspect(ctx context.Context, t InspectType, id string) (string, error)
- func InspectContext(contextName string) (string, error)
- func InspectNetwork(ctx context.Context, networkID string) (network.Inspect, error)
- func InspectVolume(ctx context.Context, name string) (volume.Volume, error)
- func InvalidateSnapshot()
- func IsSwarmLockedErr(err error) bool
- func ListConfigs(ctx context.Context) ([]swarm.Config, error)
- func ListConfigsWith(ctx context.Context, cli *client.Client) ([]swarm.Config, error)
- func ListNetworks(ctx context.Context) ([]network.Summary, error)
- func ListNetworksWith(ctx context.Context, cli *client.Client) ([]network.Summary, error)
- func ListSecrets(ctx context.Context) ([]swarm.Secret, error)
- func ListSecretsWith(ctx context.Context, cli *client.Client) ([]swarm.Secret, error)
- func ListServicesUsingConfigID(ctx context.Context, configID string) ([]swarm.Service, error)
- func ListServicesUsingConfigName(ctx context.Context, name string) ([]swarm.Service, error)
- func ListServicesUsingNetwork(ctx context.Context, networkID, networkName string) ([]string, error)
- func ListServicesUsingSecretID(ctx context.Context, secretID string) ([]swarm.Service, error)
- func ListServicesUsingSecretName(ctx context.Context, name string) ([]swarm.Service, error)
- func PromoteNode(ctx context.Context, nodeID string) error
- func PruneNetworks(ctx context.Context) (network.PruneReport, error)
- func ReconstructStackCompose(stackName string) (string, error)
- func RefreshHostnameCache() error
- func RefreshSnapshotAsync()
- func RemoveNetwork(ctx context.Context, networkID string) error
- func RemoveNetworkWith(ctx context.Context, cli *client.Client, networkID string) error
- func RemoveNode(ctx context.Context, nodeID string, force bool) error
- func RemoveNodeLabel(ctx context.Context, nodeID string, key string) error
- func RemoveService(ctx context.Context, serviceName string) error
- func RemoveStack(ctx context.Context, stackName string) error
- func RemoveStackCLI(ctx context.Context, stackName string) error
- func RemoveStackCLIInContext(ctx context.Context, ctxName, stackName string) error
- func RemoveStackNetworks(ctx context.Context, stackName string) error
- func RemoveVolume(ctx context.Context, name string, force bool) error
- func RemoveVolumeWith(ctx context.Context, cli *client.Client, name string, force bool) error
- func ResetClient()
- func RestartService(ctx context.Context, serviceName string) error
- func RestartServiceAndWait(ctx context.Context, serviceName string) error
- func RestartServiceWithProgress(ctx context.Context, serviceName string, progressCh chan<- ProgressUpdate) error
- func RollbackService(ctx context.Context, serviceName string) error
- func RotateConfigInServices(ctx context.Context, oldCfg *swarm.Config, newCfg swarm.Config) error
- func RotateSecretInServices(ctx context.Context, oldSec *swarm.Secret, newSec swarm.Secret) error
- func ScaleService(ctx context.Context, serviceID string, replicas uint64) error
- func ScaleServiceByName(ctx context.Context, serviceName string, replicas uint64) error
- func ServicesUsingConfigs(ctx context.Context) (map[string][]swarm.Service, error)
- func ServicesUsingConfigsWith(ctx context.Context, cli *client.Client) (map[string][]swarm.Service, error)
- func ServicesUsingSecrets(ctx context.Context) (map[string][]swarm.Service, error)
- func ServicesUsingSecretsWith(ctx context.Context, cli *client.Client) (map[string][]swarm.Service, error)
- func SetNodeAvailability(ctx context.Context, nodeID string, availability swarm.NodeAvailability) error
- func SetSnapshot(s *SwarmSnapshot)
- func StructFieldsAsStringArray(v interface{}) []string
- func TriggerRefreshIfNeeded()
- func UnlockSwarm(ctx context.Context, key string) error
- func UpdateContextDescription(name, description string) error
- func UpdateContextWithCertFiles(name, description, dockerHost, caFile, certFile, keyFile string, ...) error
- func UseContext(contextName string) error
- func ValidateContext(ctx context.Context, contextName string) error
- func ValidateStackYAML(content string) error
- type ClientOps
- type ClusterInfoOps
- type ComposeFile
- type ComposeService
- type ConfigOps
- type ConfigRef
- type ConfigWithDecodedData
- type ContainerSpec
- type ContextInfo
- type ContextOps
- type DNSConfig
- type Deps
- type EndpointSpec
- type Event
- type EventOps
- type HealthConfigJSON
- type Healthcheck
- type HostnameOps
- type InspectOps
- type InspectType
- type LogDriver
- type Logging
- type Mount
- type NetRef
- type NetworkOps
- type NetworkWithUsage
- type NodeEntry
- type NodeOps
- type PartialListError
- type Placement
- type PortConfig
- type ProgressUpdate
- type ResolveImage
- type ResourceSpec
- type Resources
- type RestartPolicy
- type SecretOps
- type SecretRef
- type SecretWithDecodedData
- type ServiceConvergence
- type ServiceEntry
- type ServiceInspect
- type ServiceMode
- type ServiceOps
- type ServiceSpec
- type ServiceSummary
- type SnapshotOps
- type Stack
- type StackEntry
- type StackInspection
- type StackOps
- type StackService
- type SwarmNode
- type SwarmSnapshot
- func GetOrRefreshSnapshot() (*SwarmSnapshot, error)
- func GetOrRefreshSnapshotCtx(ctx context.Context) (*SwarmSnapshot, error)
- func GetSnapshot() *SwarmSnapshot
- func RefreshSnapshot() (*SwarmSnapshot, error)
- func RefreshSnapshotCtx(ctx context.Context) (*SwarmSnapshot, error)
- func SnapshotWith(parent context.Context, c client.APIClient) (*SwarmSnapshot, error)
- func (snap *SwarmSnapshot) DesiredReplicas(svc swarm.Service) int
- func (s *SwarmSnapshot) FindService(serviceID string) *swarm.Service
- func (s *SwarmSnapshot) FindServiceByName(name string) *swarm.Service
- func (snap *SwarmSnapshot) StackConvergence(stackName string) []ServiceConvergence
- func (snap *SwarmSnapshot) StackServices(stackName string) []ServiceEntry
- func (s SwarmSnapshot) ToNodeEntries() []NodeEntry
- func (s SwarmSnapshot) ToStackEntries() []StackEntry
- type TaskEntry
- type TaskOps
- type TaskTemplate
- type Ulimit
- type UpdateConfig
- type VolumeInfo
- type VolumeOps
Constants ¶
This section is empty.
Variables ¶
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 ¶
AddNodeLabel adds or updates a label on a node.
func BuildRawLogArgs ¶
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 ¶
CheckContextExportExists checks if an export file already exists for a context
func ClientFor ¶
ClientFor returns a client for an explicitly named Docker context, cached per name.
It is the seam that lets a caller address a specific swarm. GetClient resolves DOCKER_CONTEXT or `docker context show` and caches one client for the whole process — correct for a single-swarm CLI, and unusable for anything that has to reconcile two swarms at once, because there is no argument by which to ask for the other one.
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 CreateConfigWith ¶
func CreateConfigWith(ctx context.Context, cli *client.Client, name string, data []byte, labels map[string]string) (swarm.Config, error)
CreateConfigWith is CreateConfig against an explicit client.
func CreateContext ¶
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 ¶
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 CreateNetworkWith ¶
func CreateNetworkWith(ctx context.Context, cli *client.Client, name string, opts network.CreateOptions) (string, []string, error)
CreateNetworkWith is CreateNetwork against an explicit client.
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 ¶
CreateService creates a service with the given spec and returns the service ID
func DeleteConfig ¶
DeleteConfig deletes a config only if it's not referenced by any service.
func DeleteConfigWith ¶
DeleteConfigWith is DeleteConfig against an explicit client.
func DeleteContext ¶
DeleteContext removes a Docker context
func DeleteSecret ¶
DeleteSecret deletes a secret only if it's not referenced by any service.
func DemoteNode ¶
DemoteNode sets the node role to worker (demotes a manager).
func DeployStack ¶
DeployStack deploys a stack with the provided name and YAML content, leaving image resolution at Docker's default. See DeployStackResolved.
It is the TUI's entry point, and a Bubble Tea command has no context to inherit, so the background one is spelled out here instead of being pushed onto every caller. Everything below this takes a context.
func DeployStackInContext ¶
func DeployStackInContext(ctx context.Context, ctxName, stackName, yamlContent string, resolve ResolveImage, files map[string][]byte) error
DeployStackInContext deploys a stack to an explicitly named Docker context.
`docker stack deploy` has no SDK equivalent, so this shells out; naming the context is what keeps the target an argument rather than whatever DOCKER_CONTEXT or `docker context show` happens to say at the moment the command runs.
Cancelling ctx kills the child. Nothing else can reach it: the CLI holds its own connection to the daemon, so a caller being torn down while the daemon is unresponsive would otherwise sit on a `docker stack deploy` that never returns.
files are the chart files the manifest's file: and env_file: keys name, keyed by their slash-separated chart-relative path; they are written beside the manifest so those keys resolve to them. nil for a manifest that names none.
func DeployStackResolved ¶
func DeployStackResolved(ctx context.Context, stackName string, yamlContent string, resolve ResolveImage) error
DeployStackResolved deploys a stack with an explicit image-resolution mode, on whichever context the process is pointed at.
func ExportContext ¶
ExportContext exports a Docker context to a tar file in /tmp
func ExportContextWithForce ¶
ExportContextWithForce exports a Docker context, removing existing file if present
func GetClient ¶
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 GetContextFromEnv ¶
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 ¶
GetCurrentContext returns the name of the active Docker context.
func GetDockerContext ¶
GetDockerContext returns the current Docker context name.
func GetDockerVersion ¶
func GetLocalNodeID ¶
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 ¶
GetNodeIDToHostnameMap returns a copy of the cached map. Automatically initializes the cache if needed.
func GetServiceCount ¶
func GetServiceLogs ¶
GetServiceLogs fetches and returns the logs from a service
func GetServiceTaskDiagnostics ¶
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 ¶
GetStackInspection returns detailed information about a stack in JSON format
func GetStackNetworks ¶
GetStackNetworks returns the names of networks associated with a stack
func GetSwarmCPUCapacity ¶
GetSwarmCPUCapacity returns total CPU cores across all nodes (fast).
func GetSwarmCPUUsage ¶
GetSwarmCPUUsage returns actual CPU usage across running containers.
func GetSwarmMemCapacity ¶
GetSwarmMemCapacity returns total memory across all nodes (fast).
func GetSwarmMemUsage ¶
GetSwarmMemUsage returns actual memory usage across running containers.
func GetSwarmResourceUsage ¶
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 ¶
ImportContext imports a Docker context from an archive file Returns the name of the imported context
func InspectContext ¶
InspectContext returns the detailed JSON inspection of a Docker context
func InspectNetwork ¶
InspectNetwork returns detailed information about a network
func InspectVolume ¶
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 ¶
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 ¶
ListConfigs retrieves all Docker Swarm configs.
func ListConfigsWith ¶
ListConfigsWith is ListConfigs against an explicit client.
func ListNetworks ¶
ListNetworks returns all networks in the swarm, on the ambient context.
func ListNetworksWith ¶
ListNetworksWith is ListNetworks against an explicit client.
func ListSecrets ¶
ListSecrets retrieves all Docker Swarm secrets.
func ListSecretsWith ¶
ListSecretsWith is ListSecrets against an explicit client.
func ListServicesUsingConfigID ¶
ListServicesUsingConfigID returns all services that reference a config by ID
func ListServicesUsingConfigName ¶
ListServicesUsingConfigName returns all services that reference a config by name
func ListServicesUsingNetwork ¶
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 ¶
ListServicesUsingSecretID returns all services that reference a secret by ID
func ListServicesUsingSecretName ¶
ListServicesUsingSecretName returns all services that reference a secret by name
func PromoteNode ¶
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 ¶
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 ¶
RemoveNetwork removes a network on the ambient context.
func RemoveNetworkWith ¶
RemoveNetworkWith is RemoveNetwork against an explicit client.
func RemoveNode ¶
RemoveNode removes a node from the swarm.
func RemoveNodeLabel ¶
RemoveNodeLabel removes a label from a node
func RemoveService ¶
RemoveService removes a service by name.
func RemoveStack ¶
RemoveStack removes all services in a stack by stack name.
func RemoveStackCLI ¶
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 RemoveStackCLIInContext ¶
RemoveStackCLIInContext is RemoveStackCLI against an explicitly named context. As with DeployStackInContext, cancelling ctx kills the child.
func RemoveStackNetworks ¶
RemoveStackNetworks removes all networks associated with a stack
func RemoveVolume ¶
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 RemoveVolumeWith ¶
RemoveVolumeWith is RemoveVolume against an explicit client.
func ResetClient ¶
func ResetClient()
ResetClient closes every cached client and clears the caches so the next GetClient or ClientFor call creates a fresh connection. Safe to call when nothing has been cached yet. Named clients are dropped too: a context switch is not the only reason to reset, and a `docker context update` invalidates a pinned client just as surely as the ambient one.
func RestartService ¶
RestartService performs a rolling restart (like `docker service update --force`).
func RestartServiceAndWait ¶
func RestartServiceWithProgress ¶
func RestartServiceWithProgress(ctx context.Context, serviceName string, progressCh chan<- ProgressUpdate) error
func RollbackService ¶
RollbackService rolls back a service to its previous configuration.
func RotateConfigInServices ¶
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 ¶
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 ¶
ScaleService updates the replica count of a service by ID.
func ScaleServiceByName ¶
ScaleServiceByName looks up a service by name and scales it.
func ServicesUsingConfigs ¶
ServicesUsingConfigs indexes services by the configs they reference.
The single-config lookups above each list every service and filter, which is right for one question and wrong for many: asking about N configs costs N full service listings. This asks once and answers all of them.
Keyed by both ConfigID and ConfigName, because a reference carries both and callers hold one or the other. A service appears once per key it references, even if it mounts the same config at several paths.
func ServicesUsingConfigsWith ¶
func ServicesUsingConfigsWith(ctx context.Context, cli *client.Client) (map[string][]swarm.Service, error)
ServicesUsingConfigsWith is ServicesUsingConfigs against an explicit client.
func ServicesUsingSecrets ¶
ServicesUsingSecrets indexes services by the secrets they reference.
The single-secret lookups above each list every service and filter, which is right for one question and wrong for many: asking about N secrets costs N full service listings. This asks once and answers all of them.
Keyed by both SecretID and SecretName, because a reference carries both and callers hold one or the other. A service appears once per key it references, even if it mounts the same secret at several paths.
func ServicesUsingSecretsWith ¶
func ServicesUsingSecretsWith(ctx context.Context, cli *client.Client) (map[string][]swarm.Service, error)
ServicesUsingSecretsWith is ServicesUsingSecrets against an explicit client.
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 ¶
UnlockSwarm submits the unlock key to the daemon for the current context.
func UpdateContextDescription ¶
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 ¶
UseContext switches to the specified Docker context
func ValidateContext ¶
ValidateContext checks if a context switch would succeed by attempting to connect
func ValidateStackYAML ¶
ValidateStackYAML validates that the provided YAML content is a valid Docker Compose file.
Types ¶
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
// ServicesUsingConfigs answers "which services reference this config" for
// every config at once, keyed by config ID and name.
//
// It replaces per-config lookups in this seam. ListServicesUsingConfigID and
// ListServicesUsingConfigName still exist on the package for a caller with a
// single config, but each lists every service and filters, so a loop over
// them scales the whole service listing by the number of configs.
ServicesUsingConfigs(ctx context.Context) (map[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 ¶
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 InspectConfigWith ¶
func InspectConfigWith(ctx context.Context, cli *client.Client, nameOrID string) (*ConfigWithDecodedData, error)
InspectConfigWith is InspectConfig against an explicit client.
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 ¶
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 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 ResolveImage ¶
type ResolveImage string
ResolveImage selects how the daemon resolves image tags to digests at deploy time, mirroring `docker stack deploy --resolve-image`.
The empty value passes no flag, leaving Docker's own default of "always": the manager queries the registry for every service on every deploy. That makes a deploy fail when the registry is unreachable even though every node already has the image, and it rewrites the spec to repo:tag@sha256:..., so anything diffing desired against live sees every service as changed.
"changed" re-resolves only when the compose file's image string differs from the com.docker.stack.image label the CLI stashes, which is what a reconciler wants. "never" has an open upstream rollout bug (moby#51658).
const ( ResolveImageDefault ResolveImage = "" ResolveImageAlways ResolveImage = "always" ResolveImageChanged ResolveImage = "changed" ResolveImageNever ResolveImage = "never" )
func (ResolveImage) Valid ¶
func (r ResolveImage) Valid() bool
Valid reports whether r is a mode the docker CLI accepts.
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
// ServicesUsingSecrets answers "which services reference this secret" for
// every secret at once, keyed by secret ID and name.
//
// It replaces per-secret lookups in this seam. ListServicesUsingSecretID and
// ListServicesUsingSecretName still exist on the package for a caller with a
// single secret, but each lists every service and filters, so a loop over
// them scales the whole service listing by the number of secrets.
ServicesUsingSecrets(ctx context.Context) (map[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 ServiceConvergence ¶
type ServiceConvergence struct {
Name string
Mode string
// Running counts tasks that are actually running, on an active node.
Running int
// Desired is the target count over active nodes.
Desired int
// Completed counts tasks that ran to completion on an active node. Only
// meaningful together with Job: for a long-running service a completed task
// is one swarm is about to replace, not one that finished its work.
Completed int
// Job reports a service swarm will not restart after a clean exit — a
// restart policy of "none" or "on-failure". Such a service is *supposed* to
// end with no task running, so Running < Desired is its success state, not
// a failure to converge (issue #443).
//
// A task that exits non-zero and exhausts its restart budget ends Failed,
// never Complete, so counting only completed tasks keeps the distinction
// that matters: finished versus broken.
Job bool
// UpdateState is the raw swarm UpdateStatus.State, empty when the service
// has never been updated. Note that a nil UpdateStatus means "no rollout has
// ever run", NOT "the rollout finished".
UpdateState string
// Monitor is UpdateConfig.Monitor: the window after a task is created during
// which its failure still counts against the rollout. Zero when unset.
Monitor time.Duration
// NewestTaskAge is how long the newest running task has been alive, measured
// from task creation — the same instant swarm measures Monitor from.
//
// A caller waiting out the monitor window needs it: a task only reports
// running once its healthcheck passes, so by then start_period and the
// checks that followed have already consumed part of the window, and
// sometimes all of it. Zero when nothing is running.
NewestTaskAge time.Duration
}
ServiceConvergence is what a caller needs to decide whether one service has finished rolling out. It is deliberately separate from ServiceEntry: that struct backs the services view, where ReplicasOnNode mirrors `docker service ls` and so keeps counting a superseded task while its container runs. Running here drops the outgoing generation, which is the question --wait asks and the services view answers with UpToDate instead (see issue #480).
func LoadStackConvergence ¶
func LoadStackConvergence(stackName string) []ServiceConvergence
LoadStackConvergence returns per-service convergence facts for a stack.
Running counts tasks whose ACTUAL state is running — not their desired state. Up-to-dateness comes free: on a rolling update Swarm marks superseded tasks DesiredState=shutdown, so requiring both DesiredState and Status.State to be running counts exactly the current generation.
type ServiceEntry ¶
type ServiceEntry struct {
StackName string
ServiceName string
ServiceID string
ReplicasOnNode int
ReplicasTotal int
// UpToDate counts the replicas running the service's *current* generation.
// ReplicasOnNode counts every running task, superseded ones included, so it
// matches `docker service ls` — which means a start-first rollout reads as
// fully converged while the outgoing generation is what is actually up. The
// two together say what one ratio cannot: how many replicas are serving, and
// how many of those are the version being rolled out (issue #480).
UpToDate int
// RollingOut reports a rollout in flight — updating, paused, or either
// rollback state. It gates the display of UpToDate: outside a rollout a
// replica short of the current generation is a restart, not a stale version.
RollingOut bool
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
LoadStackServices returns a stack's services from the process-wide snapshot.
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 StackEntry ¶
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 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 GetOrRefreshSnapshotCtx ¶
func GetOrRefreshSnapshotCtx(ctx context.Context) (*SwarmSnapshot, error)
GetOrRefreshSnapshotCtx is GetOrRefreshSnapshot under a context the caller can cancel; see RefreshSnapshotCtx for why both spellings exist. A cache hit never consults the context, because it never talks to the daemon.
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 RefreshSnapshotCtx ¶
func RefreshSnapshotCtx(ctx context.Context) (*SwarmSnapshot, error)
RefreshSnapshotCtx is RefreshSnapshot under a context the caller can cancel.
It exists beside RefreshSnapshot rather than replacing it because the TUI is the overwhelming majority of the callers and has no context to give: a Bubble Tea command refreshing the cache after a scale or a restart would have to invent one. The release engine does have one — a reconcile it must be able to abort — and this is how it reaches the four API calls the refresh makes.
func SnapshotWith ¶
SnapshotWith fetches a snapshot from an explicit client and returns it WITHOUT touching the process-wide cache.
That omission is the point. The cache is a single global with a 3s TTL and a background refresh goroutine, sized for a TUI redrawing one swarm; two reconciles against different swarms sharing it would not merely read each other's data, they would evict each other's. A caller holding an explicit client owns its own freshness.
It takes the interface rather than *client.Client because it only ever calls NodeList, ServiceList, TaskList and Info, and a consumer that holds an APIClient — normally for testability — should not have to write a second snapshot builder that misses the locked-swarm handling below.
func (*SwarmSnapshot) DesiredReplicas ¶
func (snap *SwarmSnapshot) DesiredReplicas(svc swarm.Service) int
DesiredReplicas is the service's target task count against this snapshot: the declared replicas, or for a global service one per node that can currently run one. Exported for callers outside this package that would otherwise duplicate the mode switch and get the global case wrong (issue #480).
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) StackConvergence ¶
func (snap *SwarmSnapshot) StackConvergence(stackName string) []ServiceConvergence
StackConvergence is LoadStackConvergence against an already-fetched snapshot, so a caller polling one specific swarm for convergence does not read another swarm's tasks out of the process-wide cache.
func (*SwarmSnapshot) StackServices ¶
func (snap *SwarmSnapshot) StackServices(stackName string) []ServiceEntry
StackServices returns a stack's services from an already-fetched snapshot, so a caller holding a snapshot of a specific swarm can read it without going through the process-wide cache.
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
// Slot is the replica this task belongs to, so two tasks of the same slot
// read as one replica being replaced rather than as two replicas. Zero for a
// global service, whose tasks carry no slot and are identified by node.
Slot int
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 ¶
GetTasksForService returns all tasks for a specific service ID from the cached snapshot.
func GetTasksForStack ¶
GetTasksForStack returns all tasks for services in the given stack
func (TaskEntry) StatusText ¶
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 ¶
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).
func ListVolumesWith ¶
ListVolumesWith is ListVolumes against an explicit client.
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.
Source Files
¶
- client.go
- client_ops.go
- clusterinfo_ops.go
- config.go
- config_ops.go
- context.go
- context_ops.go
- convergence.go
- event_ops.go
- events.go
- hostname.go
- hostname_ops.go
- info.go
- inspect.go
- inspect_ops.go
- network.go
- network_ops.go
- node.go
- node_ops.go
- ops.go
- secret.go
- secret_ops.go
- service.go
- service_helpers.go
- service_ops.go
- snapshot.go
- snapshot_ops.go
- stack.go
- stack_binds.go
- stack_deploy.go
- stack_inspect.go
- stack_ops.go
- stack_remove.go
- stack_to_compose.go
- swarm_lock.go
- task.go
- task_ops.go
- utils.go
- volume.go
- volume_ops.go