runtime

package
v0.1.0-alpha.8 Latest Latest
Warning

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

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

Documentation

Overview

docker.go is the ONLY file permitted to import the Docker SDK (spec rule 3). It maps the frozen ContainerRuntime interface onto Docker Engine v28.

Package runtime defines the ContainerRuntime interface — the ONLY place in the codebase allowed to touch the Docker SDK is its docker implementation (docker.go, task T-15). Everything else (agent, builder, volumes, jobs) consumes this interface; tests use testutil/fakeruntime.

FROZEN CONTRACT: extend by adding methods deliberately, never by leaking Docker SDK types through it.

Index

Constants

View Source
const (
	LabelAssignmentID  = "dev.zattera/assignment-id"
	LabelEnvironmentID = "dev.zattera/environment-id"
	LabelAppID         = "dev.zattera/app-id"
	LabelProjectID     = "dev.zattera/project-id"
	LabelBuildID       = "dev.zattera/build-id"
	LabelJobID         = "dev.zattera/job-id"
	LabelRole          = "dev.zattera/role" // "service" | "build" | "job" | "system"
)

Common label keys set on created objects.

View Source
const ManagedLabel = "dev.zattera/managed"

ManagedLabel marks every object Zattera creates. List operations MUST filter on it so we never touch user-owned containers.

Variables

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

ErrNotFound is returned for unknown containers/networks/volumes.

Functions

func EnginePlatform

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

EnginePlatform queries the local engine's platform with a short-lived client. It exists because the node registers itself (and joins) before the long-lived runtime is constructed, and the node's advertised os-arch must describe the engine, not the daemon binary (T-97).

Types

type ContainerInfo

type ContainerInfo struct {
	ID      string
	Name    string
	Image   string
	Labels  map[string]string
	Running bool
}

ContainerInfo is a normalized list entry.

type ContainerRuntime

type ContainerRuntime interface {
	EnsureImage(ctx context.Context, ref string, auth *RegistryAuth, progress func(status string)) error
	// ImageLoad imports an image tar stream (docker-save format) into the local
	// image store. Used by the dev builder to load a freshly built image without
	// a registry round-trip.
	ImageLoad(ctx context.Context, tar io.Reader) error
	CreateContainer(ctx context.Context, spec ContainerSpec) (id string, err error)
	StartContainer(ctx context.Context, id string) error
	StopContainer(ctx context.Context, id string, timeout time.Duration) error
	RemoveContainer(ctx context.Context, id string, force bool) error
	InspectContainer(ctx context.Context, id string) (ContainerState, error)
	ListContainers(ctx context.Context, labels map[string]string) ([]ContainerInfo, error)
	Logs(ctx context.Context, id string, opts LogsOptions) (<-chan LogEntry, error)
	Exec(ctx context.Context, id string, spec ExecSpec, stdin io.Reader, stdout, stderr io.Writer, resize <-chan TermSize) (exitCode int, err error)
	Stats(ctx context.Context, id string) (StatsSample, error)
	Top(ctx context.Context, id string) (titles []string, processes [][]string, err error)
	// CopyFrom streams a tar archive of a container path; CopyTo extracts one.
	CopyFrom(ctx context.Context, id, path string) (io.ReadCloser, error)
	CopyTo(ctx context.Context, id, path string, tarStream io.Reader) error

	EnsureNetwork(ctx context.Context, spec NetworkSpec) (NetworkInfo, error)
	RemoveNetwork(ctx context.Context, name string) error
	EnsureVolume(ctx context.Context, name string, labels map[string]string) error
	RemoveVolume(ctx context.Context, name string) error
	// VolumeHostPath returns the host filesystem path of a named volume's data
	// (used by the snapshot engine).
	VolumeHostPath(ctx context.Context, name string) (string, error)

	// Ping verifies the engine is reachable (startup check).
	Ping(ctx context.Context) error
}

ContainerRuntime abstracts the container engine on one node.

Semantics every implementation (and the fake) must honor:

  • EnsureImage is idempotent; progress may be nil.
  • CreateContainer never starts the container.
  • StopContainer sends SIGTERM, waits spec.StopGrace (or the passed timeout if > 0), then SIGKILL. Stopping a stopped container is a no-op.
  • RemoveContainer(force=true) removes running containers.
  • ListContainers filters by ALL given labels (AND); implementations must additionally always filter on ManagedLabel.
  • Logs returns a channel that is closed when the log stream ends or ctx is canceled. With Follow, it stays open.
  • Exec blocks until the process exits and returns its exit code.

type ContainerSpec

type ContainerSpec struct {
	Name       string
	Image      string
	Command    []string // empty = image default (Docker CMD)
	Entrypoint []string // empty = image default (Docker ENTRYPOINT)
	Env        []string // "KEY=value"
	Labels     map[string]string
	Ports      []PortBinding
	Mounts     []Mount
	Resources  Resources
	Restart    RestartPolicy
	// Network to attach (per project+env bridge). Empty = default bridge.
	Network string
	// DNS servers for the container (the per-network internal resolver).
	DNS []string
	// WorkingDir override; empty = image default.
	WorkingDir string
	// User override ("uid:gid"); empty = image default.
	User string
	// Privileged is required only for system containers (never services).
	Privileged bool
	// StopGrace between SIGTERM and SIGKILL at StopContainer time.
	StopGrace time.Duration
}

ContainerSpec is everything needed to create a container.

type ContainerState

type ContainerState struct {
	ID      string
	Name    string
	Running bool
	// Restarting is Docker's crash-loop backoff state. CAUTION: Docker keeps
	// State.Running=true while Restarting, and NetworkSettings.Ports is empty —
	// callers treating Running as "up" will wait on a container that is dying
	// in a loop (T-98).
	Restarting bool
	ExitCode   int
	OOMKilled  bool
	StartedAt  time.Time
	FinishedAt time.Time
	// Ports actually bound (HostPort filled in).
	Ports  []PortBinding
	Labels map[string]string
	// IPAddress on its primary attached network.
	IPAddress string
	Image     string
}

ContainerState is a normalized inspect result.

type Docker

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

Docker implements ContainerRuntime against a local Docker Engine.

func NewDocker

func NewDocker() (*Docker, error)

NewDocker connects to the engine using standard env configuration and negotiates the API version.

func (*Docker) CopyFrom

func (d *Docker) CopyFrom(ctx context.Context, id, path string) (io.ReadCloser, error)

CopyFrom streams a tar of a container path.

func (*Docker) CopyTo

func (d *Docker) CopyTo(ctx context.Context, id, path string, tarStream io.Reader) error

CopyTo extracts a tar stream into a container path.

func (*Docker) CreateContainer

func (d *Docker) CreateContainer(ctx context.Context, spec ContainerSpec) (string, error)

CreateContainer creates (but never starts) a container. Tty is always false so log streams stay multiplexed.

func (*Docker) EnsureImage

func (d *Docker) EnsureImage(ctx context.Context, ref string, auth *RegistryAuth, progress func(status string)) error

EnsureImage pulls ref unless it is already present locally. Progress lines are forwarded to progress (may be nil). Context cancellation aborts the pull.

func (*Docker) EnsureNetwork

func (d *Docker) EnsureNetwork(ctx context.Context, spec NetworkSpec) (NetworkInfo, error)

EnsureNetwork creates a bridge network with a fixed subnet, or returns the existing one.

func (*Docker) EnsureVolume

func (d *Docker) EnsureVolume(ctx context.Context, name string, labels map[string]string) error

EnsureVolume creates a named volume unless it exists.

func (*Docker) Exec

func (d *Docker) Exec(ctx context.Context, id string, spec ExecSpec, stdin io.Reader, stdout, stderr io.Writer, resize <-chan TermSize) (int, error)

Exec runs a command in a container and returns its exit code.

func (*Docker) ImageLoad

func (d *Docker) ImageLoad(ctx context.Context, tar io.Reader) error

ImageLoad imports a docker-save-format tar stream into the local image store.

func (*Docker) InspectContainer

func (d *Docker) InspectContainer(ctx context.Context, id string) (ContainerState, error)

InspectContainer returns a normalized state; ErrNotFound if it is gone.

func (*Docker) ListContainers

func (d *Docker) ListContainers(ctx context.Context, labels map[string]string) ([]ContainerInfo, error)

ListContainers filters by ManagedLabel plus every requested label (AND).

func (*Docker) Logs

func (d *Docker) Logs(ctx context.Context, id string, opts LogsOptions) (<-chan LogEntry, error)

Logs streams demuxed, timestamped log lines. The channel closes at stream end or on ctx cancellation.

func (*Docker) Ping

func (d *Docker) Ping(ctx context.Context) error

Ping verifies the engine is reachable.

func (*Docker) Platform

func (d *Docker) Platform(ctx context.Context) (string, error)

Platform returns the engine's execution platform as a raw "os/arch" string (e.g. "linux/aarch64" — Docker reports uname-style arch, so callers must normalize). This is what containers actually run on, which is NOT the daemon binary's platform on macOS/Windows: there the daemon is darwin/ windows while the engine runs a linux VM (T-97).

func (*Docker) RemoveContainer

func (d *Docker) RemoveContainer(ctx context.Context, id string, force bool) error

RemoveContainer removes a container; force removes a running one. Removing an absent container is a no-op.

func (*Docker) RemoveNetwork

func (d *Docker) RemoveNetwork(ctx context.Context, name string) error

RemoveNetwork removes a network; absent is a no-op.

func (*Docker) RemoveVolume

func (d *Docker) RemoveVolume(ctx context.Context, name string) error

RemoveVolume removes a named volume; absent is a no-op.

func (*Docker) StartContainer

func (d *Docker) StartContainer(ctx context.Context, id string) error

StartContainer starts a created container.

func (*Docker) Stats

func (d *Docker) Stats(ctx context.Context, id string) (StatsSample, error)

Stats returns a one-shot resource sample.

func (*Docker) StopContainer

func (d *Docker) StopContainer(ctx context.Context, id string, timeout time.Duration) error

StopContainer sends SIGTERM then SIGKILL after the timeout (or the engine default when timeout <= 0). Stopping a stopped/absent container is a no-op.

func (*Docker) Top

func (d *Docker) Top(ctx context.Context, id string) ([]string, [][]string, error)

Top lists processes running in a container.

func (*Docker) VolumeHostPath

func (d *Docker) VolumeHostPath(ctx context.Context, name string) (string, error)

VolumeHostPath returns the host path of a named volume's data.

type ExecSpec

type ExecSpec struct {
	Command []string
	TTY     bool
	Env     []string
	WorkDir string
}

ExecSpec runs a command inside a running container.

type LogEntry

type LogEntry struct {
	Time   time.Time
	Stderr bool
	Line   string
}

LogEntry is one demuxed log line.

type LogsOptions

type LogsOptions struct {
	Since  time.Time
	Follow bool
	Tail   int // 0 = all
}

LogsOptions selects a log window.

type Mount

type Mount struct {
	VolumeName string // named Docker volume (preferred)
	HostPath   string // bind mount (system use only)
	Target     string
	ReadOnly   bool
}

Mount attaches a named volume or a host path.

type NetworkInfo

type NetworkInfo struct {
	ID      string
	Name    string
	Subnet  string
	Gateway string
}

NetworkInfo describes an existing network.

type NetworkSpec

type NetworkSpec struct {
	Name   string
	Subnet string // CIDR, e.g. "10.201.4.0/24"
	Labels map[string]string
}

NetworkSpec creates a bridge network with a fixed subnet.

type PortBinding

type PortBinding struct {
	Name          string // PortSpec.name, for correlation
	ContainerPort uint32
	Protocol      string // "tcp" | "udp"
	HostIP        string // mesh IP for cluster traffic; never 0.0.0.0 unless explicit
	HostPort      uint32
}

PortBinding publishes a container port on a host IP. HostPort 0 lets the runtime allocate one; the effective port is reported via Inspect.

type RegistryAuth

type RegistryAuth struct {
	Username string
	Password string
	// ServerAddress like "10.90.0.1:5000"; empty for Docker Hub.
	ServerAddress string
}

RegistryAuth is basic-auth for image pulls/pushes.

type Resources

type Resources struct {
	CPUMillis uint32 // 1000 = one core (converted to NanoCPUs)
	MemoryMB  uint32
	PidsLimit int64
}

Resources are cgroup limits.

type RestartPolicy

type RestartPolicy string

RestartPolicy mirrors Docker's.

const (
	RestartNever         RestartPolicy = "no"
	RestartOnFailure     RestartPolicy = "on-failure"
	RestartUnlessStopped RestartPolicy = "unless-stopped"
)

type StatsSample

type StatsSample struct {
	CPUPercent  float64
	MemoryBytes uint64
	NetRxBytes  uint64
	NetTxBytes  uint64
}

StatsSample is a one-shot resource reading.

type TermSize

type TermSize struct {
	Cols uint32
	Rows uint32
}

TermSize is a TTY resize event.

Jump to

Keyboard shortcuts

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