runtime

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 108 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package runtime wraps the containerd client and nerdctl libraries.

All container operations performed by nerdui go through this package so that containers created from the UI stay fully compatible with the nerdctl CLI.

Index

Constants

View Source
const (
	// DefaultAddress is the default containerd socket path.
	DefaultAddress = "/run/containerd/containerd.sock"
	// DefaultNamespace is the default containerd namespace used by nerdctl.
	DefaultNamespace = "default"
)
View Source
const (
	ComposeUp      = "up"
	ComposeDown    = "down"
	ComposeStart   = "start"
	ComposeStop    = "stop"
	ComposeRestart = "restart"
	ComposePull    = "pull"
)

Stack operations (#28) and their `nerdctl compose` arguments.

View Source
const (
	StateCreated    = "created"
	StateRunning    = "running"
	StatePaused     = "paused"
	StateRestarting = "restarting"
	StateExited     = "exited"
	StateUnknown    = "unknown"
)

Container states (API).

View Source
const (
	PluginOK    = "ok"
	PluginSkip  = "skip"
	PluginError = "error"
)

Plugin statuses.

View Source
const (
	MinStatsInterval = time.Second
	MaxStatsInterval = 10 * time.Second
)

Sampling interval bounds (#16).

View Source
const MaxPreviewBytes = 256 << 10

MaxPreviewBytes limits a file preview.

View Source
const MaxSaveImages = 50

MaxSaveImages limits the images of one archive.

View Source
const MaxVolumeEntries = 5000

MaxVolumeEntries limits a directory listing.

Variables

Actions lists all container actions.

View Source
var ErrNotConnected error = notConnected{}

ErrNotConnected is returned when containerd cannot be reached. It satisfies errdefs.IsUnavailable, so the API maps it to 503 (ADR-0006).

View Source
var ErrStackContainer = fmt.Errorf("%w: the container belongs to a compose stack; edit or redeploy the stack", errdefs.ErrFailedPrecondition)

ErrStackContainer is returned for containers of compose stacks: they are recreated by the stack.

Functions

func ActionContext

func ActionContext(ctx context.Context) (context.Context, context.CancelFunc)

ActionContext detaches an action from the HTTP request: a closed browser tab must not abort a stop or remove halfway. The action is still bounded by actionTimeout.

func ComposeArgs

func ComposeArgs(project, dir, op string, opts ComposeOptions) ([]string, error)

ComposeArgs returns the `nerdctl compose` arguments of an operation on project in dir, after the global flags. The project is the stack name; the directory gives the default files.

func ContainerName

func ContainerName(lbls map[string]string) string

ContainerName returns the nerdctl container name stored in labels.

func ContainerdSupported

func ContainerdSupported(version string) bool

ContainerdSupported reports whether this build supports a containerd version (e.g. "v2.3.7").

func CreateArgs

func CreateArgs(s CreateSpec) ([]string, error)

CreateArgs validates the spec and returns the arguments of `nerdctl create` after the subcommand. Values are passed as --flag=value, so none can be taken for a flag; the command follows the image, where nerdctl stops parsing flags.

func ExpectedExit added in v0.2.0

func ExpectedExit(namespace, id, project string, at time.Time) bool

ExpectedExit reports whether a container that exited at the given time was being stopped, restarted or removed by nerdui, alone or as part of its compose project.

func LoadNerdctlConfig

func LoadNerdctlConfig() (*config.Config, string, error)

LoadNerdctlConfig reads nerdctl.toml exactly like the nerdctl CLI does ($NERDCTL_TOML or the platform default, e.g. /etc/nerdctl/nerdctl.toml) so nerdui uses the same data root and CNI paths as the CLI. A missing file yields nerdctl's defaults.

func NerdctlLibraryVersion

func NerdctlLibraryVersion() string

NerdctlLibraryVersion returns the version of the nerdctl module linked into the binary.

func NetworkCreateArgs

func NetworkCreateArgs(spec NetworkSpec) ([]string, error)

NetworkCreateArgs validates spec and returns the arguments of `nerdctl network create`. Values use the --flag=value form and the name follows "--", so nothing is read as a flag.

func Redeploy added in v0.2.0

func Redeploy(ctx context.Context, rt Runtime, namespace, project, dir string, opts RedeployOptions, out io.Writer) error

Redeploy pulls the images of a stack and recreates the services whose image changed, then brings the stack (or the given services) up (ADR-0042).

`nerdctl compose up` recreates a container only when the service's configuration changed; a tag that now points to a newer image is not a change (nerdctl 2.3 and 2.4), and `--force-recreate` would also recreate the dependencies of the services. So the images' digests are compared before and after the pull, and the containers of changed services are removed: `up` creates them again and leaves every other container as it is. Containers created by nerdctl 2.4+ also record their image digest, which catches images pulled earlier without recreating.

func RunCommand

func RunCommand(s CreateSpec) (string, error)

RunCommand is the `nerdctl run -d` equivalent of a spec, quoted for a POSIX shell, shown before creating (#17).

func SupportedContainerdMinors

func SupportedContainerdMinors() []string

SupportedContainerdMinors returns the containerd minors supported by this build.

Types

type Action

type Action string

Action is a container lifecycle operation (#11, #12).

const (
	ActionStart   Action = "start"
	ActionStop    Action = "stop"
	ActionRestart Action = "restart"
	ActionKill    Action = "kill"
	ActionPause   Action = "pause"
	ActionUnpause Action = "unpause"
	ActionRemove  Action = "remove"
)

Container actions.

func (Action) Valid

func (a Action) Valid() bool

Valid reports whether a is a known action.

type ActionOptions

type ActionOptions struct {
	// Force removes a running or paused container (killing it first).
	Force bool
	// Volumes also removes anonymous volumes of the container.
	Volumes bool
}

ActionOptions tune an action. Force and Volumes apply to remove only.

type CNIInfo

type CNIInfo struct {
	Path    string   `json:"path"`
	NetConf string   `json:"netConfPath"`
	Version string   `json:"version,omitempty"`
	Plugins []string `json:"plugins"`
	Error   string   `json:"error,omitempty"`
}

CNIInfo describes the CNI plugins nerdctl uses for container networks.

type Client

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

Client is a lazily connected containerd client.

func New

func New(address, namespace string, opts ...Option) *Client

New creates a client. The connection is established on first use, so nerdui can start even when containerd is temporarily unavailable.

func (*Client) Address

func (c *Client) Address() string

Address returns the containerd socket address.

func (*Client) Close

func (c *Client) Close() error

Close closes the underlying connection, if any.

func (*Client) Compose

func (c *Client) Compose() Compose

Compose returns compose operations of the local containerd.

func (*Client) ContainerName

func (c *Client) ContainerName(ctx context.Context, namespace, id string) string

ContainerName returns the nerdctl name of a container, or "" when it has none or is gone (event history, #65).

func (*Client) Containers

func (c *Client) Containers() Containers

Containers returns container operations of the local containerd.

func (*Client) CreateNamespace

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

CreateNamespace creates a containerd namespace (#195). The name follows containerd's identifier rules.

func (*Client) Events

func (c *Client) Events() EventSource

Events returns the event source of the local containerd.

func (*Client) Images

func (c *Client) Images() Images

Images returns image operations of the local containerd.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (Info, error)

Info collects host and runtime information like `nerdctl info` and `nerdctl version`, plus the containerd plugin list (`ctr plugins ls`) and CNI plugin versions.

func (*Client) Namespace

func (c *Client) Namespace() string

Namespace returns the default containerd namespace.

func (*Client) Namespaces

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

Namespaces lists containerd namespaces in sorted order.

func (*Client) Nerdctl

func (c *Client) Nerdctl(ctx context.Context) NerdctlStatus

Nerdctl reports the host nerdctl binary and whether mutations are allowed (ADR-0011).

func (*Client) Networks

func (c *Client) Networks() Networks

Networks returns network operations of the local containerd.

func (*Client) Ports

func (c *Client) Ports(ctx context.Context) (PortsReport, error)

Ports collects the ports of every namespace's containers and marks conflicts.

func (*Client) Prune

func (c *Client) Prune(ctx context.Context, namespace string, opts PruneOptions, out io.Writer) error

Prune runs nerdctl's prunes in the order of `nerdctl system prune` and writes their output to out. A missing BuildKit daemon skips the build cache with a note instead of failing.

func (*Client) PrunePreview

func (c *Client) PrunePreview(ctx context.Context, namespace string, allImages bool) (PrunePreview, error)

PrunePreview lists what a prune of the namespace would remove.

func (*Client) Registries

func (c *Client) Registries() Registries

Registries returns the registry logins of the local host.

func (*Client) RemoveNamespace

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

RemoveNamespace removes an empty namespace (#195). Besides containerd's own check (containers, images, content, snapshots, leases), nerdctl's volumes and user-defined networks must be gone: containerd does not know about them and they would be left behind.

func (*Client) Summary

func (c *Client) Summary(ctx context.Context, volumeSizes bool) (Summary, error)

Summary counts containers, images, volumes and networks of every namespace and reports the disk usage of images (and volumes with volumeSizes) and the data filesystems.

func (*Client) System

func (c *Client) System() System

System returns system-level operations (versions, namespaces).

func (*Client) Versions

func (c *Client) Versions(ctx context.Context) (Versions, error)

Versions returns containerd server and nerdctl library versions.

func (*Client) Volumes

func (c *Client) Volumes() Volumes

Volumes returns volume operations of the local containerd.

type Component

type Component struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
	Commit  string `json:"commit,omitempty"`
	// Error explains why the version is unknown (binary missing, unexpected output).
	Error string `json:"error,omitempty"`
}

Component is the version of a runtime component (containerd, runc, buildctl).

type Compose

type Compose interface {
	// Services returns the services of a project that run by default (no profile), loading
	// file from dir under the project name.
	Services(ctx context.Context, namespace, project, dir, file string) ([]string, error)
	// Describe loads a project found on disk under its own name (`name:` or the directory
	// name) for discovery and adoption (#25).
	Describe(ctx context.Context, dir, file string) (ComposeProject, error)
	// Validate loads the project of dir with compose and env as the content of its compose and
	// .env files (nil: the files on disk), without writing them. It returns the services or an
	// invalid-argument error explaining the problem.
	Validate(ctx context.Context, project, dir, composeName string, compose, env []byte) ([]string, error)
	// Run runs a stack operation with the host's `nerdctl compose` in dir (ADR-0026), writing
	// its output to out.
	Run(ctx context.Context, namespace, project, dir, op string, opts ComposeOptions, out io.Writer) error
}

Compose reads compose projects like `nerdctl compose` (ADR-0008): compose-go, at the version the linked nerdctl uses, with the project options of nerdctl's composer.New — includes, extends, profiles and .env interpolation behave the same.

type ComposeOptions

type ComposeOptions struct {
	// Volumes removes the project's named volumes on down (`down -v`): their data is lost.
	Volumes bool
	// RemoveOrphans removes containers of services no longer in the compose file (up, down).
	RemoveOrphans bool
	// Pull pulls images before up (`up --pull always`).
	Pull bool
	// Services limits up and pull to these services (#54); empty means all.
	Services []string
}

ComposeOptions modify a stack operation.

type ComposeProject

type ComposeProject struct {
	Name     string
	Services []string
	// Files are the compose files loaded (main, override, includes).
	Files []string
	// LocalPaths are paths inside the project directory the project uses besides its compose
	// and .env files: bind mounts, build contexts, env files, config and secret files.
	LocalPaths []string
}

ComposeProject describes a compose project on disk.

type ComposeRef

type ComposeRef struct {
	Project string `json:"project"`
	Service string `json:"service,omitempty"`
}

ComposeRef links a container to its compose project and service.

type Container

type Container struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Namespace string `json:"namespace"`
	Image     string `json:"image"`
	Command   string `json:"command"`
	// State is one of created, running, paused, restarting, exited, unknown.
	State string `json:"state"`
	// Health is healthy, unhealthy or starting when a healthcheck is configured.
	Health    string     `json:"health,omitempty"`
	ExitCode  *int       `json:"exitCode,omitempty"`
	ExitedAt  *time.Time `json:"exitedAt,omitempty"`
	StartedAt *time.Time `json:"startedAt,omitempty"`
	CreatedAt time.Time  `json:"createdAt"`
	Ports     []Port     `json:"ports"`
	// Compose is set for containers that belong to a compose project (ADR-0008).
	Compose  *ComposeRef       `json:"compose,omitempty"`
	Platform string            `json:"platform,omitempty"`
	Runtime  string            `json:"runtime,omitempty"`
	Labels   map[string]string `json:"labels"`
}

Container is the list representation of a container. Keep in sync with api/openapi.yaml.

type ContainerCounts

type ContainerCounts struct {
	Total     int `json:"total"`
	Running   int `json:"running"`
	Paused    int `json:"paused"`
	Stopped   int `json:"stopped"`
	Unhealthy int `json:"unhealthy"`
}

ContainerCounts counts containers by state (#63).

type ContainerSpec added in v0.1.1

type ContainerSpec struct {
	// ID is the container's full ID.
	ID   string     `json:"id"`
	Spec CreateSpec `json:"spec"`
	// Unsupported lists settings the create form cannot express; recreating would lose them.
	Unsupported []string `json:"unsupported"`
	// Running tells whether the container runs now (the new one is started if so).
	Running bool `json:"running"`
	// Stack is the compose project managing the container: recreate it through the stack.
	Stack string `json:"stack,omitempty"`
	// ImageChanged: the image tag points elsewhere than when the container was created, so
	// values equal to the old image's defaults may be kept explicitly.
	ImageChanged bool `json:"imageChanged,omitempty"`
}

ContainerSpec is what recreating a container would create (#18, ADR-0031): its settings as a CreateSpec, and the settings that cannot be carried over, which block recreating.

type Containers

type Containers interface {
	// List returns all containers of a namespace (any state), newest first.
	List(ctx context.Context, namespace string) ([]Container, error)
	// Do performs a lifecycle action on the container with the exact id (#11, #12).
	Do(ctx context.Context, namespace, id string, action Action, opts ActionOptions) error
	// Inspect returns the container as `nerdctl inspect` shows it (#13).
	Inspect(ctx context.Context, namespace, ref string, size bool) (any, error)
	// Logs passes the log lines of the container with the exact id to emit (#14).
	Logs(ctx context.Context, namespace, id string, opts LogOptions, emit LogEmitter) error
	// Top lists the processes of the running container with the exact id (#20).
	Top(ctx context.Context, namespace, id string) ([]Process, error)
	// Stats samples the running container with the exact id every interval (#16).
	Stats(ctx context.Context, namespace, id string, interval time.Duration, emit StatsEmitter) error
	// Exec runs an interactive process with a terminal until it exits or ctx ends (#15).
	Exec(ctx context.Context, namespace, id string, opts ExecOptions, stdin io.Reader, out io.Writer, resize <-chan TermSize) (int, error)
	// Create pulls if needed, creates with `nerdctl create` and optionally starts (#17).
	Create(ctx context.Context, namespace string, spec CreateSpec, start bool, out io.Writer) (string, error)
	// Spec reconstructs a container's settings for editing and recreating (#18).
	Spec(ctx context.Context, namespace, ref string) (ContainerSpec, error)
	// Recreate replaces a container with one created from spec, rolling back on failure (#18).
	Recreate(ctx context.Context, namespace, ref string, spec CreateSpec, opts RecreateOptions, out io.Writer) (string, error)
}

Containers covers container operations of an environment.

type CreateSpec

type CreateSpec struct {
	Image string `json:"image"`
	Name  string `json:"name,omitempty"`
	// Entrypoint replaces the image's entrypoint (first element) — nerdctl takes one value.
	Entrypoint string `json:"entrypoint,omitempty"`
	// Command replaces the image's command (argv after the image).
	Command  []string    `json:"command,omitempty"`
	Ports    []PortSpec  `json:"ports,omitempty"`
	Env      []EnvVar    `json:"env,omitempty"`
	Mounts   []MountSpec `json:"mounts,omitempty"`
	Network  string      `json:"network,omitempty"`
	Hostname string      `json:"hostname,omitempty"`
	User     string      `json:"user,omitempty"`
	Workdir  string      `json:"workdir,omitempty"`
	// CPUs and MemoryBytes are limits; 0 means none.
	CPUs        float64 `json:"cpus,omitempty"`
	MemoryBytes int64   `json:"memoryBytes,omitempty"`
	// Restart is no, always, unless-stopped or on-failure[:N].
	Restart string            `json:"restart,omitempty"`
	Labels  map[string]string `json:"labels,omitempty"`

	// Advanced settings (#18): extra networks after Network, a static IPv4 address in the
	// first network, privileges, devices and name resolution.
	ExtraNetworks []string `json:"extraNetworks,omitempty"`
	IP            string   `json:"ip,omitempty"`
	Privileged    bool     `json:"privileged,omitempty"`
	CapAdd        []string `json:"capAdd,omitempty"`
	CapDrop       []string `json:"capDrop,omitempty"`
	// Devices are host[:container[:permissions]], as in --device.
	Devices []string `json:"devices,omitempty"`
	DNS     []string `json:"dns,omitempty"`
	// ExtraHosts are name:address entries for /etc/hosts (--add-host); the address may be
	// host-gateway.
	ExtraHosts []string `json:"extraHosts,omitempty"`

	// Healthcheck overrides the image's healthcheck (#237).
	Healthcheck *HealthcheckSpec `json:"healthcheck,omitempty"`
}

CreateSpec is the typed request for a new container (#17, ADR-0003). Every field becomes a separate argument of `nerdctl create`; nothing goes through a shell.

type Deprecation

type Deprecation struct {
	ID             string    `json:"id"`
	Message        string    `json:"message"`
	LastOccurrence time.Time `json:"lastOccurrence,omitzero"`
}

Deprecation is a containerd warning about a deprecated feature in use.

type EnvVar

type EnvVar struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

EnvVar is an environment variable.

type Event

type Event struct {
	Timestamp time.Time `json:"ts"`
	Namespace string    `json:"namespace,omitempty"`
	// Topic is the containerd topic, e.g. "/containers/create" or "/tasks/exit".
	Topic string `json:"topic"`
	// Kind and Action are derived from the topic: "container"/"create", "task"/"exit".
	Kind   string `json:"kind"`
	Action string `json:"action"`
	// ID is the container ID for container and task events, the name for image and
	// namespace events.
	ID         string            `json:"id,omitempty"`
	Attributes map[string]string `json:"attributes,omitempty"`
}

Event is a containerd event in the API representation (ADR-0007). Keep in sync with api/openapi.yaml.

type EventSource

type EventSource interface {
	// Subscribe verifies the connection and starts a subscription. A non-nil error means
	// the subscription could not be established. Otherwise events are delivered until ctx
	// ends or the connection breaks; the error channel then receives the reason and both
	// channels are closed.
	Subscribe(ctx context.Context) (<-chan Event, <-chan error, error)
}

EventSource streams events of an environment.

type ExecOptions

type ExecOptions struct {
	// Cmd is the command; empty runs bash when the image has it, sh otherwise.
	Cmd []string
	// User is a name or UID[:GID] resolved in the container like `nerdctl exec --user`;
	// empty keeps the container's user.
	User    string
	Workdir string
	// Cols and Rows are the initial terminal size.
	Cols, Rows uint16
}

ExecOptions describe an interactive process in a container (#15, ADR-0022).

type Features

type Features struct {
	MemoryLimit    bool `json:"memoryLimit"`
	SwapLimit      bool `json:"swapLimit"`
	CPUCfsPeriod   bool `json:"cpuCfsPeriod"`
	CPUCfsQuota    bool `json:"cpuCfsQuota"`
	CPUShares      bool `json:"cpuShares"`
	CPUSet         bool `json:"cpuSet"`
	PidsLimit      bool `json:"pidsLimit"`
	OomKillDisable bool `json:"oomKillDisable"`
	IPv4Forwarding bool `json:"ipv4Forwarding"`
}

Features are the resource limits and kernel settings available to containers.

type Filesystem

type Filesystem struct {
	// Paths are the data directories on it (containerd's root, nerdctl's data root).
	Paths []string `json:"paths"`
	Total uint64   `json:"total"`
	Free  uint64   `json:"free"`
}

Filesystem is a filesystem holding container data.

type HealthInfo added in v0.2.0

type HealthInfo struct {
	// Status is starting, healthy or unhealthy.
	Status string
	// FailingStreak counts consecutive failed checks. nerdctl keeps it across restarts.
	FailingStreak int
	// Retries is how many failed checks in a row make the container unhealthy.
	Retries int
}

HealthInfo is a container's healthcheck state as nerdctl records it in its labels.

func ContainerHealth added in v0.2.0

func ContainerHealth(lbls map[string]string) (info HealthInfo, ok bool)

ContainerHealth reads the healthcheck state from a container's labels; ok is false for a container without a healthcheck or before its first check.

type HealthcheckSpec added in v0.2.0

type HealthcheckSpec struct {
	// Command runs with /bin/sh -c in the container; exit code 0 means healthy.
	Command     string `json:"command,omitempty"`
	Interval    string `json:"interval,omitempty"`
	Timeout     string `json:"timeout,omitempty"`
	StartPeriod string `json:"startPeriod,omitempty"`
	Retries     int    `json:"retries,omitempty"`
	// Disabled turns off a healthcheck of the image (--no-healthcheck); no other field is set.
	Disabled bool `json:"disabled,omitempty"`
}

HealthcheckSpec is a healthcheck as `nerdctl create --health-*` sets it. Durations are Go durations such as "30s" or "1m30s"; empty values keep the image's or nerdctl's defaults (30s interval and timeout, 3 retries, no start period).

type HistoryEntry added in v0.2.0

type HistoryEntry struct {
	Created   *time.Time `json:"created,omitempty"`
	CreatedBy string     `json:"createdBy"`
	Comment   string     `json:"comment,omitempty"`
	// EmptyLayer steps (ENV, CMD, …) add no layer.
	EmptyLayer bool `json:"emptyLayer"`
	// Size of the layer: unpacked on disk when the image is unpacked (Compressed false),
	// otherwise as stored in the registry.
	Size       int64 `json:"size"`
	Compressed bool  `json:"compressed,omitempty"`
}

HistoryEntry is a step of an image's history (#47), newest first like `nerdctl image history`. Keep in sync with api/openapi.yaml.

type Image

type Image struct {
	// Name is the full reference as stored in containerd, e.g. docker.io/library/nginx:1.27.
	Name string `json:"name"`
	// Repository and Tag are empty for images stored under a digest only (dangling).
	Repository string `json:"repository"`
	Tag        string `json:"tag"`
	// Digest is the target (index or manifest) digest; images sharing it are the same image.
	Digest    string    `json:"digest"`
	CreatedAt time.Time `json:"createdAt"`
	// Platforms are the platforms whose content is in the store, e.g. linux/amd64.
	Platforms []string `json:"platforms"`
	// Size is the unpacked size on disk (snapshots); ContentSize the stored blobs.
	Size        int64 `json:"size"`
	ContentSize int64 `json:"contentSize"`
	// Containers is the number of containers of the namespace created from this image.
	Containers int               `json:"containers"`
	Labels     map[string]string `json:"labels"`
}

Image is the list representation of an image (#42). Keep in sync with api/openapi.yaml.

type Images

type Images interface {
	// List returns the images of a namespace sorted by name.
	List(ctx context.Context, namespace string) ([]Image, error)
	// Pull pulls an image, writing terminal progress to out (#43).
	Pull(ctx context.Context, namespace, ref string, opts PullOptions, out io.Writer) error
	// Tag adds target as a reference to source (#44).
	Tag(ctx context.Context, namespace, source, target string) error
	// Remove removes an image reference; force as in `nerdctl rmi -f` (#44).
	Remove(ctx context.Context, namespace, ref string, force bool) error
	// Push pushes an image, writing terminal progress to out (#44).
	Push(ctx context.Context, namespace, ref string, opts PushOptions, out io.Writer) error
	// History returns the build steps and layer sizes of an image (#47).
	History(ctx context.Context, namespace, name string) ([]HistoryEntry, error)
	// RemoteDigest resolves a tag in its registry without pulling (#53).
	RemoteDigest(ctx context.Context, ref string) (string, error)
	// CheckSave verifies the images of an archive exist; Save writes them as a tar archive
	// and Load imports one (#46).
	CheckSave(ctx context.Context, namespace string, names []string) error
	Save(ctx context.Context, namespace string, names []string, w io.Writer) error
	Load(ctx context.Context, namespace string, r io.Reader) ([]string, error)
}

Images covers image operations of an environment.

type Info

type Info struct {
	// ID is the containerd server UUID.
	ID              string `json:"id"`
	Hostname        string `json:"hostname"`
	OperatingSystem string `json:"operatingSystem"`
	OSType          string `json:"osType"`
	Architecture    string `json:"architecture"`
	KernelVersion   string `json:"kernelVersion"`
	CPUs            int    `json:"cpus"`
	MemoryBytes     int64  `json:"memoryBytes"`
	CgroupDriver    string `json:"cgroupDriver"`
	CgroupVersion   string `json:"cgroupVersion"`
	Rootless        bool   `json:"rootless"`
	// Snapshotter is nerdctl's default snapshotter; Snapshotters are those containerd loaded.
	Snapshotter     string   `json:"snapshotter"`
	Snapshotters    []string `json:"snapshotters"`
	LogDrivers      []string `json:"logDrivers"`
	SecurityOptions []string `json:"securityOptions"`
	// Features are the cgroup and kernel capabilities reported by `nerdctl info`.
	Features   Features    `json:"features"`
	Components []Component `json:"components"`
	CNI        CNIInfo     `json:"cni"`
	// Warnings are `nerdctl info` warnings (missing limits, IP forwarding…).
	Warnings     []string      `json:"warnings"`
	Deprecations []Deprecation `json:"deprecations"`
	Plugins      []Plugin      `json:"plugins"`
}

Info describes the host and the container runtime of an environment (#66, ADR-0015). Host fields come from the machine nerdui runs on, which is the containerd host.

type Listener

type Listener struct {
	IP       string
	Port     int32
	Protocol string // tcp or udp
}

Listener is a socket of the host bound to a port: a listening TCP socket or a bound UDP socket (#62).

type LogEmitter

type LogEmitter func(LogLine) error

LogEmitter receives log lines in order; an error stops reading.

type LogLine

type LogLine struct {
	// Stream is "stdout" or "stderr".
	Stream string `json:"stream"`
	// Time is when the line was logged; zero when the log driver does not record it
	// (journald).
	Time time.Time `json:"ts,omitzero"`
	// Line is the text without the trailing newline, ANSI sequences preserved.
	Line string `json:"line"`
}

LogLine is one log entry.

type LogOptions

type LogOptions struct {
	// Follow keeps streaming new entries while the container runs.
	Follow bool
	// Tail limits the output to the last n entries (0 = all).
	Tail uint
	// Since and Until bound the entries by time: RFC 3339 or relative ("10m").
	Since, Until string
}

LogOptions select the log entries, like `nerdctl logs`.

type LoginResult

type LoginResult struct {
	Registry
	// Warning is set when the password is stored unencrypted in the docker config file.
	Warning string `json:"warning,omitempty"`
}

LoginResult reports a successful login.

type MountSpec

type MountSpec struct {
	Type     string `json:"type"` // volume, bind or tmpfs
	Source   string `json:"source,omitempty"`
	Target   string `json:"target"`
	ReadOnly bool   `json:"readOnly,omitempty"`
}

MountSpec is a volume, bind mount or tmpfs.

type NamespaceSummary

type NamespaceSummary struct {
	Name       string          `json:"name"`
	Containers ContainerCounts `json:"containers"`
	Images     int             `json:"images"`
	Volumes    int             `json:"volumes"`
	Networks   int             `json:"networks"`
}

NamespaceSummary counts the resources of one namespace.

type NerdctlStatus

type NerdctlStatus struct {
	// Path is the configured binary (--nerdctl-path).
	Path string `json:"path"`
	// Version is the host binary's version, empty when it could not be determined.
	Version string `json:"version,omitempty"`
	// Required is the major.minor that must match, e.g. "2.4" (the linked packages).
	Required string `json:"required"`
	// Compatible is true when major.minor of Version equals Required.
	Compatible bool `json:"compatible"`
	// CheckSkipped is true with --skip-nerdctl-version-check (unsupported configuration).
	CheckSkipped bool `json:"checkSkipped,omitempty"`
	// Error explains why the binary is missing or its version unknown.
	Error string `json:"error,omitempty"`
}

NerdctlStatus is the result of the nerdctl compatibility check (ADR-0011).

func (NerdctlStatus) Writable

func (s NerdctlStatus) Writable() bool

Writable reports whether mutating operations are allowed.

type Network

type Network struct {
	Name   string            `json:"name"`
	ID     string            `json:"id,omitempty"`
	Driver string            `json:"driver"`
	Labels map[string]string `json:"labels"`
	IPAM   []NetworkSubnet   `json:"ipam"`
	// Parent is the host interface of a macvlan or ipvlan network.
	Parent string `json:"parent,omitempty"`
	// Internal bridge networks have no gateway to the outside.
	Internal bool `json:"internal"`
	// Default is nerdctl's default network ("bridge").
	Default bool `json:"default"`
	// Removable is false for the default network, pre-defined networks and networks not created
	// by nerdctl.
	Removable  bool               `json:"removable"`
	File       string             `json:"file,omitempty"`
	Containers []NetworkContainer `json:"containers"`
}

Network is a CNI network. Keep in sync with api/openapi.yaml.

type NetworkContainer

type NetworkContainer struct {
	ID      string   `json:"id"`
	Name    string   `json:"name,omitempty"`
	Running bool     `json:"running"`
	IPs     []string `json:"ips,omitempty"`
	MAC     string   `json:"mac,omitempty"`
}

NetworkContainer is a container attached to a network; addresses are known while it runs.

type NetworkSpec

type NetworkSpec struct {
	Name   string `json:"name"`
	Driver string `json:"driver"` // bridge (default), macvlan, ipvlan
	Subnet string `json:"subnet,omitempty"`
	// Gateway and IPRange require Subnet.
	Gateway string `json:"gateway,omitempty"`
	IPRange string `json:"ipRange,omitempty"`
	// Parent is the host interface of a macvlan or ipvlan network (required for them).
	Parent   string            `json:"parent,omitempty"`
	Internal bool              `json:"internal,omitempty"`
	Labels   map[string]string `json:"labels,omitempty"`
}

NetworkSpec is a network to create.

type NetworkSubnet

type NetworkSubnet struct {
	Subnet     string `json:"subnet,omitempty"`
	Gateway    string `json:"gateway,omitempty"`
	RangeStart string `json:"rangeStart,omitempty"`
	RangeEnd   string `json:"rangeEnd,omitempty"`
}

NetworkSubnet is one IPAM range of a network.

type Networks

type Networks interface {
	// List returns the networks of a namespace sorted by name, with their containers.
	List(ctx context.Context, namespace string) ([]Network, error)
	// Create creates a network with the host nerdctl and returns it.
	Create(ctx context.Context, namespace string, spec NetworkSpec) (Network, error)
	// Remove removes a network like `nerdctl network rm`: refused (409) while a running
	// container uses it, for the default and pre-defined networks and for networks managed
	// outside nerdctl.
	Remove(ctx context.Context, namespace, name string) error
}

Networks are nerdctl's CNI networks (#60). Listing and removal use nerdctl's netutil; creation runs the host's `nerdctl network create`, whose options differ between nerdctl releases (ADR-0024).

type Option

type Option func(*Client)

Option configures a Client.

func WithComposeVars added in v0.2.0

func WithComposeVars(vars func(ctx context.Context, stack string) (map[string]string, error)) Option

WithComposeVars sets the source of stack variables (#35, ADR-0049): they are passed to `nerdctl compose` as environment variables and used when compose files are loaded.

func WithNerdctl

func WithNerdctl(path string, skipVersionCheck bool) Option

WithNerdctl sets the host nerdctl binary and whether its version check is skipped (ADR-0003, ADR-0011).

func WithNerdctlConfig

func WithNerdctlConfig(cfg *config.Config) Option

WithNerdctlConfig sets nerdctl's configuration (see LoadNerdctlConfig), so data_root, CNI paths and other settings match the nerdctl CLI on the host.

type Plugin

type Plugin struct {
	Type         string   `json:"type"`
	ID           string   `json:"id"`
	Platforms    []string `json:"platforms,omitempty"`
	Capabilities []string `json:"capabilities,omitempty"`
	// Status is ok, skip (not applicable to this host) or error.
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

Plugin is a containerd plugin as `ctr plugins ls` shows it.

type Port

type Port struct {
	HostIP        string `json:"hostIp,omitempty"`
	HostPort      int32  `json:"hostPort"`
	ContainerPort int32  `json:"containerPort"`
	Protocol      string `json:"protocol"`
}

Port is a published port.

type PortEntry

type PortEntry struct {
	Namespace     string `json:"namespace"`
	ContainerID   string `json:"containerId"`
	ContainerName string `json:"containerName,omitempty"`
	State         string `json:"state"`
	HostIP        string `json:"hostIp,omitempty"`
	HostPort      int32  `json:"hostPort,omitempty"`
	ContainerPort int32  `json:"containerPort"`
	Protocol      string `json:"protocol"`
	Published     bool   `json:"published"`
	// Conflicts describes other users of the same host port: containers (a stopped one cannot
	// start while another holds the port) and host processes.
	Conflicts []string `json:"conflicts,omitempty"`
}

PortEntry is a port of a container: published on the host (HostPort > 0) or only exposed by its image.

type PortSpec

type PortSpec struct {
	HostIP        string `json:"hostIp,omitempty"`
	HostPort      int    `json:"hostPort,omitempty"` // 0 = random
	ContainerPort int    `json:"containerPort"`
	Protocol      string `json:"protocol,omitempty"` // tcp (default) or udp
}

PortSpec publishes a container port.

type PortsReport

type PortsReport struct {
	Ports []PortEntry `json:"ports"`
	// HostChecked is true when the host's own listening sockets were compared too.
	HostChecked bool `json:"hostChecked"`
}

PortsReport lists the published and exposed ports of all containers of the host (#62). Keep in sync with api/openapi.yaml.

type Process added in v0.2.0

type Process struct {
	PID  int `json:"pid"`
	PPID int `json:"ppid"`
	// UID is the real user ID in the host's view; User its name on the host, when known.
	UID  int    `json:"uid"`
	User string `json:"user,omitempty"`
	// State is the kernel state letter: R running, S sleeping, D disk sleep, Z zombie, …
	State string `json:"state"`
	// CPU is the share of one CPU used since the process started, in percent (like ps).
	CPU float64 `json:"cpu"`
	// RSS is the resident memory in bytes.
	RSS     int64     `json:"rss"`
	Started time.Time `json:"started"`
	Command string    `json:"command"`
}

Process is a process of a container as the host sees it (#20). Keep in sync with api/openapi.yaml.

type PruneOptions

type PruneOptions struct {
	// Containers removes stopped containers.
	Containers bool
	// Images removes dangling images, or all images unused by containers with AllImages.
	Images    bool
	AllImages bool
	// Networks removes networks no container uses (except the default ones).
	Networks bool
	// BuildCache removes the BuildKit cache (all of it with AllImages, like nerdctl).
	BuildCache bool
}

PruneOptions selects what a prune removes (#52, ADR-0020). Volumes are not pruned by nerdui.

type PrunePreview

type PrunePreview struct {
	Containers []PrunedItem `json:"containers"`
	Images     []PrunedItem `json:"images"`
	// ImagesSize sums the unpacked sizes of the images; shared layers make the freed space
	// smaller.
	ImagesSize int64 `json:"imagesSize"`
	// BuildKit reports whether a BuildKit daemon is available for build cache pruning.
	BuildKit bool `json:"buildKit"`
}

PrunePreview estimates what a prune removes. Images are exact (nerdctl's own selection); containers are those stopped now; networks and build cache are not previewed.

type PrunedItem

type PrunedItem struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Size int64  `json:"size,omitempty"`
}

PrunedItem is a container or image a prune would remove.

type PullOptions

type PullOptions struct {
	// Platform pulls one platform (e.g. linux/arm64); empty means the host platform.
	Platform string
	// AllPlatforms pulls every platform of a multi-platform image (no unpack).
	AllPlatforms bool
}

PullOptions are the options of an image pull (#43).

type PushOptions

type PushOptions struct {
	// Platform pushes one platform; empty means the host platform.
	Platform string
	// AllPlatforms pushes every platform in the store.
	AllPlatforms bool
}

PushOptions are the options of an image push (#44).

type RecreateOptions added in v0.1.1

type RecreateOptions struct {
	// Pull pulls the image before replacing the container (an update).
	Pull bool
}

RecreateOptions control Recreate.

type RedeployOptions added in v0.2.0

type RedeployOptions struct {
	// Services limits the redeploy to these services; empty means all.
	Services []string
	// RemoveOrphans removes containers of services no longer in the compose file.
	RemoveOrphans bool
}

RedeployOptions modify Redeploy.

type Registries

type Registries interface {
	List(ctx context.Context) ([]Registry, error)
	// Login verifies the credentials with the registry and stores them.
	Login(ctx context.Context, server, username, password string) (LoginResult, error)
	// Logout removes the stored credentials of server.
	Logout(ctx context.Context, server string) error
}

Registries manages registry logins of the host (#51, ADR-0019): the docker config of the user running nerdui, shared with `nerdctl login` and used by pull, push and compose.

type Registry

type Registry struct {
	// Server is the key in the docker config, e.g. "https://index.docker.io/v1/" or
	// "registry.local:5000".
	Server   string `json:"server"`
	Username string `json:"username,omitempty"`
	// Aliases are the other keys the same login is stored under: nerdctl saves logins on port
	// 443 with and without the port, and logout removes all of them.
	Aliases []string `json:"aliases,omitempty"`
}

Registry is a registry the host is logged in to (#51). Keep in sync with api/openapi.yaml.

type Runtime

type Runtime interface {
	System() System
	Containers() Containers
	Images() Images
	Volumes() Volumes
	Networks() Networks
	Compose() Compose
	Registries() Registries
	Events() EventSource
	Close() error
}

Runtime is everything nerdui can do with one environment (ADR-0006). It is split into small interfaces so handlers depend only on what they use and can be tested with fakes. The local implementation is *Client; a remote agent implements the same interface in v2.

New capabilities (Containers, Images, Volumes, Networks, Stacks, Events) are added here together with the features that need them.

type StatsEmitter

type StatsEmitter func(StatsSample) error

StatsEmitter receives samples; an error stops the sampling.

type StatsSample

type StatsSample struct {
	Time time.Time `json:"ts"`
	// CPUPercent is relative to one CPU (200 = two CPUs busy), like docker and nerdctl.
	CPUPercent    float64 `json:"cpuPercent"`
	MemoryUsage   uint64  `json:"memoryUsage"`
	MemoryLimit   uint64  `json:"memoryLimit"`
	MemoryPercent float64 `json:"memoryPercent"`
	// Network and block I/O are cumulative bytes since the container started.
	NetworkRx  uint64 `json:"networkRx"`
	NetworkTx  uint64 `json:"networkTx"`
	BlockRead  uint64 `json:"blockRead"`
	BlockWrite uint64 `json:"blockWrite"`
	PIDs       uint64 `json:"pids"`
}

StatsSample is one measurement of a running container (#16), as `nerdctl stats` computes it. Keep in sync with api/openapi.yaml.

type Summary

type Summary struct {
	Containers ContainerCounts    `json:"containers"`
	Images     int                `json:"images"`
	Volumes    int                `json:"volumes"`
	Networks   int                `json:"networks"`
	Namespaces []NamespaceSummary `json:"namespaces"`
	// ImagesSize is the unpacked and content size of the images (shared layers counted once
	// per image).
	ImagesSize int64 `json:"imagesSize"`
	// VolumesSize is only computed on request: it walks every volume.
	VolumesSize *int64       `json:"volumesSize,omitempty"`
	Filesystems []Filesystem `json:"filesystems"`
}

Summary is the overview of a host across namespaces (#63). Keep in sync with api/openapi.yaml.

type System

type System interface {
	// Versions reports containerd and nerdctl versions.
	Versions(ctx context.Context) (Versions, error)
	// Namespaces lists containerd namespaces.
	Namespaces(ctx context.Context) ([]string, error)
	// CreateNamespace and RemoveNamespace manage namespaces (#195); only empty ones are removed.
	CreateNamespace(ctx context.Context, name string) error
	RemoveNamespace(ctx context.Context, name string) error
	// Nerdctl reports the nerdctl compatibility check; mutations require Writable().
	Nerdctl(ctx context.Context) NerdctlStatus
	// Info describes the host, runtime components and containerd plugins (#66).
	Info(ctx context.Context) (Info, error)
	// PrunePreview estimates what Prune removes; Prune runs nerdctl's prunes (#52).
	PrunePreview(ctx context.Context, namespace string, allImages bool) (PrunePreview, error)
	Prune(ctx context.Context, namespace string, opts PruneOptions, out io.Writer) error
	// Ports lists published and exposed ports of all namespaces with conflicts (#62).
	Ports(ctx context.Context) (PortsReport, error)
	// Summary counts resources of all namespaces and reports disk usage (#63).
	Summary(ctx context.Context, volumeSizes bool) (Summary, error)
}

System covers host-level information of an environment.

type TermSize

type TermSize struct{ Cols, Rows uint16 }

TermSize is a terminal size change.

type Versions

type Versions struct {
	Containerd         string `json:"containerd"`
	ContainerdRevision string `json:"containerdRevision"`
	// ContainerdSupported is false for versions outside SupportedContainerdMinors (ADR-0012).
	ContainerdSupported bool `json:"containerdSupported"`
	// SupportedContainerd are the containerd minors this build supports (ADR-0017).
	SupportedContainerd []string      `json:"supportedContainerd"`
	NerdctlLibrary      string        `json:"nerdctlLibrary"`
	Nerdctl             NerdctlStatus `json:"nerdctl"`
}

Versions describes the versions of the underlying runtime components.

type Volume

type Volume struct {
	Name       string            `json:"name"`
	Mountpoint string            `json:"mountpoint"`
	Labels     map[string]string `json:"labels"`
	// Anonymous volumes were created for a container without a name (`-v /data`).
	Anonymous bool `json:"anonymous"`
	// CreatedAt is the modification time of the volume directory (nerdctl keeps no date).
	CreatedAt time.Time `json:"createdAt,omitzero"`
	// Size in bytes; only with size=true.
	Size       *int64          `json:"size,omitempty"`
	Containers []VolumeMounter `json:"containers"`
}

Volume is a named volume. Keep in sync with api/openapi.yaml.

type VolumeDownload added in v0.2.0

type VolumeDownload struct {
	// Name is the base name of the download: the file's name, or <dir>.tar.gz.
	Name string
	// Size is the file size; -1 for an archive.
	Size  int64
	Write func(w io.Writer) error
	Close func() error
}

VolumeDownload is a file or directory of a volume, ready to be written to a client.

type VolumeEntry added in v0.2.0

type VolumeEntry struct {
	Name string `json:"name"`
	// Type is dir, file, symlink or other (devices, sockets, pipes).
	Type    string    `json:"type"`
	Size    int64     `json:"size"`
	Mode    string    `json:"mode"`
	ModTime time.Time `json:"modTime"`
	// Target of a symlink, and its type (dir or file) when it stays inside the volume.
	Target     string `json:"target,omitempty"`
	TargetType string `json:"targetType,omitempty"`
}

VolumeEntry is a file or directory in a volume (#58). Keep in sync with api/openapi.yaml.

type VolumeFile added in v0.2.0

type VolumeFile struct {
	Size    int64     `json:"size"`
	ModTime time.Time `json:"modTime"`
	// Content is the text of the file up to MaxPreviewBytes; empty for binary files.
	Content   string `json:"content"`
	Binary    bool   `json:"binary"`
	Truncated bool   `json:"truncated"`
}

VolumeFile is the beginning of a file in a volume, for a preview.

type VolumeMounter

type VolumeMounter struct {
	ID   string `json:"id"`
	Name string `json:"name,omitempty"`
}

VolumeMounter is a container that mounts a volume.

type Volumes

type Volumes interface {
	// List returns the volumes of a namespace sorted by name, with the containers that mount
	// them; size walks every volume and is only computed on request.
	List(ctx context.Context, namespace string, size bool) ([]Volume, error)
	// Create creates a volume like `nerdctl volume create`; an existing name is a conflict.
	Create(ctx context.Context, namespace, name string, lbls map[string]string) (Volume, error)
	// Remove removes a volume that no container (running or not) mounts; 409 otherwise.
	Remove(ctx context.Context, namespace, name string) error
	// ListFiles, PreviewFile and Download read the contents of a volume on the host (#58).
	ListFiles(namespace, name, dir string) ([]VolumeEntry, bool, error)
	PreviewFile(namespace, name, file string) (VolumeFile, error)
	Download(namespace, name, target string) (VolumeDownload, error)
	// Restore replaces the contents of a volume with an archive of Download("/") (#59).
	Restore(namespace, name string, r io.Reader) error
}

Volumes are nerdctl's named volumes (#57): directories in nerdctl's data root, per namespace, shared with the nerdctl CLI.

Jump to

Keyboard shortcuts

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