docker

package
v1.10.11 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: AGPL-3.0, Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package docker is the Docker seam the platform-stack engine talks through. It declares the narrow client interface the engine needs and the types that cross it — deliberately none of them from the Docker SDK, so a caller may back this with any implementation.

Index

Constants

View Source
const (
	// LabelPrefix namespaces every platform-applied Docker label.
	LabelPrefix = "io.miabi."

	LabelApp         = "io.miabi.app"          // application id
	LabelDeployment  = "io.miabi.deployment"   // deployment id
	LabelDatabase    = "io.miabi.database"     // database instance id
	LabelStack       = "io.miabi.stack"        // stack id
	LabelVolume      = "io.miabi.volume"       // volume id
	LabelJob         = "io.miabi.job"          // one-shot job container (transient)
	LabelRole        = "io.miabi.role"         // platform-infra role (node-gateway, …)
	LabelNode        = "io.miabi.node"         // node slug
	LabelWorkspace   = "io.miabi.workspace"    // owning workspace id
	LabelManaged     = "io.miabi.managed"      // "true" on managed raw resources/services
	LabelPipelineRun = "io.miabi.pipeline-run" // pipeline run id (transient)
	LabelSizeBytes   = "io.miabi.size_bytes"   // volume size hint

	// LabelPartOf marks a resource as part of the Miabi platform stack
	// (PartOfMiabi). One exact-match key, so the whole stack is a single Docker
	// label filter rather than a scan against a list of roles.
	LabelPartOf = "io.miabi.part-of"
	// LabelManagedBy names who owns the resource's LIFECYCLE, which is not who it belongs to. A
	// compose-owned container may be observed and updated in place, but recreating it out-of-band is
	// silently reverted by the next `docker compose up -d`.
	LabelManagedBy = "io.miabi.managed-by"
	// LabelProtected ("true") refuses ad-hoc destructive operations from the generic containers list.
	// Declared, never inferred: platform infrastructure is not automatically undeletable (a transient
	// GC container is infra too), and a role allowlist in the guard would drift from the roles.
	LabelProtected = "io.miabi.protected"
	// LabelSpecHash fingerprints the run spec a platform component was created from, so `miabi
	// install` can tell "already what the manifest asks for" from "changed" without re-deriving
	// Docker's own normalization. See services/platformstack.
	LabelSpecHash = "io.miabi.spec-hash"
)

Platform Docker label keys. Every container / volume / service Miabi creates carries a back-reference label to its owning record under io.miabi.* (reverse-DNS of miabi.io). These are the single source of truth — do not hand-write the string literals elsewhere.

View Source
const (
	// Platform stack (examples/compose/compose.yaml + the agent).
	RoleControlPlane       = "control-plane"
	RolePlatformDB         = "platform-db"
	RolePlatformCache      = "platform-cache"
	RoleGateway            = "gateway" // the central, compose-managed gateway
	RoleAgent              = "agent"
	RoleControlPlaneWorker = "worker" // a split-out `command: ["worker"]` service

	// Infrastructure Miabi provisions itself.
	RoleNodeGateway      = "node-gateway"
	RoleNodeGatewayRedis = "node-gateway-redis"
	// RoleMetadataGuard is the per-node helper that keeps containers off the cloud metadata service.
	RoleMetadataGuard = "metadata-guard"
	// RolePlatformInternal marks the private network the platform's own components talk over. It is
	// the label, not the name, that guards it: an operator who renames the network in the manifest
	// must not thereby make it attachable from the app-facing APIs.
	RolePlatformInternal = "platform-internal"
	RoleRegistry         = "registry"
	RoleRegistryGC       = "registry-gc" // transient: deliberately NOT protected
)

Roles carried by LabelRole. The platform-stack roles are new; the infra roles were already in use as string literals at their call sites and are named here so there is one spelling of each.

View Source
const (
	// ManagedByCompose: created by examples/compose/compose.yaml. Miabi may read it and update
	// it in place, but must write any version change back to the compose env too —
	// otherwise `docker compose up -d` reverts the upgrade.
	ManagedByCompose = "compose"
	// ManagedByMiabi: Miabi created it and may freely recreate it.
	ManagedByMiabi = "miabi"
	// ManagedByExternal: installed out-of-band (install-agent.sh on a node Miabi
	// does not otherwise control).
	ManagedByExternal = "external"
)

Lifecycle owners for LabelManagedBy.

View Source
const ManagedLabel = LabelManaged

ManagedLabel marks resources created by Miabi (kept as a named alias for the many call sites that tag raw containers/volumes/services).

View Source
const PartOfMiabi = "miabi"

PartOfMiabi is the only value LabelPartOf takes today. Named so call sites read as an identity check rather than a string compare.

Variables

View Source
var ErrNotFound = errors.New("docker: resource not found")

ErrNotFound reports that a container, image, network or volume does not exist. Callers compare against it with errors.Is rather than matching on the engine's message text.

Functions

func IsManaged

func IsManaged(labels map[string]string) bool

IsManaged reports whether a resource carries any platform label — i.e. it is owned by Miabi and must not be a blanket prune/delete target.

func IsPlatformInfra

func IsPlatformInfra(labels map[string]string) bool

IsPlatformInfra reports whether a resource is platform infrastructure (carries a role label) — the node's edge gateway / its Redis. Such resources are managed through their own pages, never reclaimed or hidden as "someone else's".

func IsPlatformNetwork added in v1.10.6

func IsPlatformNetwork(labels map[string]string) bool

IsPlatformNetwork reports whether a Docker network belongs to Miabi itself — the private network its own components talk over, the shared proxy fabric, or anything else carrying a platform role.

The LABELS are the test, never the name: a network's name is the operator's to choose in the stack manifest, and a renamed one must stay just as closed. Callers that hold only a name resolve it against the engine first, matching the id as well — Docker reports an attachment either way, and a guard that compares names alone is bypassed by passing the id.

func IsPlatformStack

func IsPlatformStack(labels map[string]string) bool

IsPlatformStack reports whether a resource is part of Miabi's own stack — control plane, database/cache, central gateway, agent. Such resources are never offered for import and are never treated as a user's container.

func IsProtected

func IsProtected(labels map[string]string) bool

IsProtected reports whether destructive operations (stop/restart/remove) must be refused on a resource. Distinct from IsPlatformInfra: infra is "do not reclaim as an orphan", protected is "do not let a human break the platform by accident".

func IsReservedLabelKey

func IsReservedLabelKey(key string) bool

IsReservedLabelKey reports whether key is platform-reserved — i.e. a user is not allowed to set it as a custom container label.

func LabelValue

func LabelValue(labels map[string]string, key string) (value string, ok bool)

LabelValue reads a platform label by its io.miabi.* key. ok is false when the label is absent.

func ManagedBy

func ManagedBy(labels map[string]string) string

ManagedBy returns the resource's lifecycle owner (compose / miabi / external), or "" when unlabeled — e.g. a stack installed before platform labels existed.

func PlatformLabels

func PlatformLabels(role, managedBy string, extra map[string]string) map[string]string

PlatformLabels is the label set every Miabi platform component carries. Use it rather than hand-writing the keys, so a component can never end up half-labeled — discoverable but not protected. extra is merged last and may not override the four keys set here.

func SanitizeUserLabels

func SanitizeUserLabels(in map[string]string) map[string]string

SanitizeUserLabels returns a copy of in with every reserved key removed, so user-supplied container labels can never set or spoof a platform label. Keys with an empty name are dropped. nil in → nil out.

func WorkspaceID

func WorkspaceID(labels map[string]string) (id uint, ok bool)

WorkspaceID returns the owning workspace id encoded in a resource's labels. ok is false when there is no (valid) workspace label — e.g. raw/system containers or platform infrastructure.

Types

type BindMount

type BindMount struct {
	Source   string // host path
	Target   string // container path
	ReadOnly bool
	// NoCreate refuses the mount when Source does not exist on the host instead of letting the
	// daemon create an empty directory for it. Storage classes rely on this: a class whose disk is
	// not mounted must fail loudly, not silently get a directory on the root filesystem.
	NoCreate bool
}

BindMount is a host path bound into a container.

type Client

type Client interface {
	ListContainers(ctx context.Context, all bool) ([]Container, error)
	InspectContainer(ctx context.Context, id string) (Container, error)
	InspectContainerConfig(ctx context.Context, id string) (ContainerConfig, error)
	RunContainer(ctx context.Context, spec RunSpec) (string, error)
	RestartContainer(ctx context.Context, id string, timeoutSeconds int) error
	RemoveContainer(ctx context.Context, id string, force bool) error
	RunOneShot(ctx context.Context, spec RunSpec) (exitCode int, logs string, err error)

	PullImage(ctx context.Context, ref string, auth *RegistryAuth) error
	ImageExists(ctx context.Context, ref string) (bool, error)

	EnsureNetworkSpec(ctx context.Context, spec NetworkSpec) (string, error)
	// NetworkConnect / NetworkDisconnect move a RUNNING container between networks. The stack engine
	// otherwise recreates a component to change its spec, but a network split cannot be done that way:
	// between recreates the stack would be half on each network and the control plane would lose its
	// database. Attaching live first makes any recreate order safe.
	NetworkConnect(ctx context.Context, name, containerID string, aliases []string) error
	NetworkDisconnect(ctx context.Context, name, containerID string, force bool) error

	CreateVolume(ctx context.Context, name string, labels map[string]string, sizeBytes int64) (Volume, error)
	InspectVolume(ctx context.Context, name string) (Volume, error)
	RemoveVolume(ctx context.Context, name string, force bool) error
}

Client is the subset of a Docker engine the stack engine drives — 15 of the 68 methods the server's own client exposes. It is deliberately narrow: the CLI backs it with a moby/moby implementation, the control plane satisfies it structurally with the client it already has, and neither side's Docker SDK ever appears in a signature.

type Container

type Container struct {
	ID           string             `json:"id"`
	Names        []string           `json:"names"`
	Image        string             `json:"image"`
	State        string             `json:"state"`
	Status       string             `json:"status"`
	Health       string             `json:"health,omitempty"` // "", "starting", "healthy", "unhealthy"
	Restarting   bool               `json:"restarting,omitempty"`
	RestartCount int                `json:"restart_count,omitempty"`
	ExitCode     int                `json:"exit_code,omitempty"`
	StartedAt    string             `json:"started_at,omitempty"` // RFC3339 from inspect
	Created      int64              `json:"created"`
	Ports        []Port             `json:"ports,omitempty"`
	Labels       map[string]string  `json:"labels,omitempty"`
	Networks     []ContainerNetwork `json:"networks,omitempty"` // populated by InspectContainer
}

Container is a summary of a Docker container.

type ContainerConfig

type ContainerConfig struct {
	ID            string            `json:"id"`
	Name          string            `json:"name"`
	Image         string            `json:"image"` // c.Config.Image (repo[:tag])
	State         string            `json:"state"`
	Command       []string          `json:"command,omitempty"`
	Entrypoint    []string          `json:"entrypoint,omitempty"`
	Env           []string          `json:"env,omitempty"`  // KEY=VALUE (effective)
	User          string            `json:"user,omitempty"` // c.Config.User: "uid[:gid]" or a name; "" = image default
	Labels        map[string]string `json:"labels,omitempty"`
	Ports         []PortMapping     `json:"ports,omitempty"`    // published host ports
	Mounts        []ContainerMount  `json:"mounts,omitempty"`   // volume + bind mounts
	Networks      []string          `json:"networks,omitempty"` // attached network names
	RestartPolicy string            `json:"restart_policy"`     // no|always|unless-stopped|on-failure[:N]
	MemoryBytes   int64             `json:"memory_bytes"`
	NanoCPUs      int64             `json:"nano_cpus"`
}

ContainerConfig is the full inspected configuration of a container, used by the import flow to adopt a pre-existing container as a Miabi app. It carries the runtime fields a summary Container omits (env, mounts, command, limits, restart policy).

type ContainerMount

type ContainerMount struct {
	Type        string `json:"type"` // "volume" | "bind" | ...
	Name        string `json:"name,omitempty"`
	Source      string `json:"source,omitempty"`
	Destination string `json:"destination"`
	ReadOnly    bool   `json:"read_only"`
}

ContainerMount is a mount on an inspected container. For Type "volume", Name is the Docker volume name; Source is the host path for binds.

type ContainerNetwork

type ContainerNetwork struct {
	Name      string `json:"name"`
	IPAddress string `json:"ip_address"`
	// IPv6Address is empty on a single-stack network. It answers the one question enabling IPv6
	// creates that nothing else can: the network detail shows the v6 SUBNET, this shows whether a
	// container was actually given an address out of it — a container started before the switch was
	// flipped has none.
	IPv6Address string `json:"ipv6_address,omitempty"`
	Gateway     string `json:"gateway,omitempty"`
	// Aliases are the container's DNS aliases on this network — the only stable way to address it, so
	// moving a container between networks (see the bridge -> overlay migration in services/network)
	// must carry them across verbatim rather than recomputing them.
	Aliases []string `json:"aliases,omitempty"`
}

ContainerNetwork is a container's attachment to a Docker network (its in-network IP). IPs are ephemeral — they change when the container is recreated; prefer the network alias for stable addressing.

type FileEntry added in v1.8.1

type FileEntry struct {
	Path    string
	Content string
	Mode    string
}

FileEntry is one file materialized inside a container. Mode is a 3- or 4-digit octal string; empty means 0644.

type GPURequest

type GPURequest struct {
	DeviceIDs    []string   // resolved GPU UUIDs; nil selects by Count instead
	Count        int        // used only when DeviceIDs is nil (-1 = all devices)
	Capabilities [][]string // e.g. [["gpu"]]
}

GPURequest describes a set of GPU devices to attach via the NVIDIA runtime (Docker DeviceRequests). Either DeviceIDs (resolved GPU UUIDs) pins exact cards, or Count asks for N-any-of-kind (-1 = all). Capabilities is the driver capability set, [["gpu"]] for NVIDIA.

type HealthcheckSpec

type HealthcheckSpec struct {
	Test        []string // e.g. ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]
	Interval    time.Duration
	Timeout     time.Duration
	Retries     int
	StartPeriod time.Duration
}

HealthcheckSpec configures a container healthcheck (Docker HEALTHCHECK).

type NetworkSpec

type NetworkSpec struct {
	Name       string
	Driver     string // "" = bridge; "overlay" for swarm
	Internal   bool
	Attachable bool // overlay networks that standalone containers may join
	Encrypted  bool // overlay data-plane encryption
	Subnet     string
	Gateway    string
	Labels     map[string]string
	EnableIPv6 *bool
	IPv6Subnet string
}

NetworkSpec describes a managed network to create. An empty Driver defaults to "bridge". Subnet/Gateway, when set, are passed as explicit IPAM so creation does not draw from Docker's built-in default-address-pools.

type Port

type Port struct {
	PrivatePort uint16 `json:"private_port"`
	PublicPort  uint16 `json:"public_port,omitempty"`
	Protocol    string `json:"protocol"`
}

Port maps a container port to a host port.

type PortMapping

type PortMapping struct {
	ContainerPort int    `json:"container_port"`
	Protocol      string `json:"protocol"`
	HostPort      int    `json:"host_port,omitempty"`
}

PortMapping is a container port and the host port it is published on (0 = not published).

type RegistryAuth

type RegistryAuth struct {
	Server   string // registry host, e.g. registry-1.docker.io, ghcr.io
	Username string
	Password string
}

RegistryAuth holds credentials for pulling from a private registry.

type RunSpec

type RunSpec struct {
	Name       string
	Image      string
	Hostname   string   // container hostname (uname -n); blank = Docker default
	Env        []string // KEY=VALUE
	Entrypoint []string // optional entrypoint override
	Cmd        []string // optional command override
	// WorkingDir sets the container's working directory (Docker WORKDIR). Blank
	// uses the image default. Pipeline steps set it to the shared workspace
	// (/workspace) so commands run against the checked-out repository.
	WorkingDir string
	Labels     map[string]string
	Networks   []string // networks to attach
	// NetworkMode is the container's network mode; "host" shares the node's network namespace and
	// ignores Networks. Blank = Docker's default.
	NetworkMode string
	// NetworkAliases are DNS aliases applied on each attached network, giving
	// the container a stable name the reverse proxy can target across deploys.
	NetworkAliases []string
	// AliasesByNetwork sets extra DNS aliases on specific networks only (network
	// name -> aliases). Used to expose an app by its service name within its
	// stack network without leaking that name onto the shared gateway network.
	AliasesByNetwork map[string][]string
	// Ports maps "containerPort/proto" -> "hostPort" (e.g. "80/tcp" -> "8080").
	Ports map[string]string
	// PortBindIPs optionally maps "containerPort/proto" -> host bind IP, to publish
	// a port on a specific interface (e.g. a node's private address) instead of
	// 0.0.0.0. Keys match Ports; a missing/empty entry means all interfaces.
	PortBindIPs map[string]string
	// Mounts maps volume name -> container path.
	Mounts map[string]string
	// NoCopyVolumes disables Docker's copy-up (image->volume seeding) for the named volumes in Mounts.
	// Set under the restricted profile, where volumes are already seeded and chowned: copy-up would
	// re-apply the image mount-dir's ownership on every start, leaving the process unable to write.
	NoCopyVolumes bool
	// ReadOnlyMounts names volumes in Mounts to mount read-only. Backup helpers set it: a container
	// that only reads the data it archives should not hold a writable handle to the one copy of it.
	ReadOnlyMounts []string
	// Binds are host path -> container path bind mounts. Used only for
	// allow-listed privileged host mounts (e.g. the Docker socket); the source
	// is a server-resolved host path, never client input.
	Binds []BindMount
	// Resource limits (0 = unlimited).
	MemoryBytes int64
	NanoCPUs    int64
	// GPUs requests whole-device GPU access via the NVIDIA runtime. Empty = none.
	// Each entry either pins specific devices by UUID (DeviceIDs) or asks for N
	// of any kind (Count); -1 Count means "all GPUs" (used by the inventory probe).
	GPUs []GPURequest
	// RestartPolicy is the Docker restart policy ("no", "always",
	// "unless-stopped", "on-failure"). Empty defaults to "unless-stopped".
	RestartPolicy string
	// Healthcheck is the container health probe; nil disables it.
	Healthcheck *HealthcheckSpec
	// Container security (restricted profile). User overrides the user the container runs as ("uid",
	// "uid:gid", or a name); empty means the image's default. NoNewPrivileges sets that securityOpt;
	// CapDrop drops the listed Linux capabilities (e.g. "NET_RAW").
	User            string
	NoNewPrivileges bool
	CapDrop         []string
	// CapAdd and Devices are per-application grants, allow-listed before they get
	// here (models.NormalizeCapabilities / NormalizeDevices).
	CapAdd  []string
	Devices []string
	// ReadOnlyRootfs mounts the container's root filesystem read-only (--read-only).
	ReadOnlyRootfs bool
	// GroupAdd are supplementary groups (Docker --group-add), by GID or name. The
	// control plane needs the host's "docker" group to read /var/run/docker.sock when
	// it does not run as root — the same thing compose.yaml's `group_add` does.
	GroupAdd []string
	// Files are written into the container between create and start, which is how
	// configuration files are projected without a host bind: no path on the node,
	// nothing to distribute to a remote engine, and the write is scoped to this
	// container. Re-applied on every deploy, so an in-place rewrite by the app does
	// not survive one.
	Files []FileEntry
}

RunSpec describes a container to create and start.

type Volume

type Volume struct {
	Name       string            `json:"name"`
	Driver     string            `json:"driver"`
	Mountpoint string            `json:"mountpoint"`
	CreatedAt  string            `json:"created_at,omitempty"`
	Labels     map[string]string `json:"labels,omitempty"`
}

Volume summarizes a Docker volume.

Jump to

Keyboard shortcuts

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