containerapi

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 24 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 containerapi is the one client of the Docker Engine API and of Podman's libpod API that the Docker and Podman extensions share (SPEC §10.20 "The engine client", D22). Both engines are spoken to over HTTP on a Unix socket, or on tcp:// with TLS, with the standard library only: no Docker SDK and no new module.

A Client is made for one Kind of engine and one Endpoint. It negotiates the API version with /_ping and /version on its first call (Docker: at least 1.41; Podman: at least version 4, whose libpod paths are /v4.0.0/libpod/...), and it turns the two engines' different JSON into the same types (Container, Image, Network, Volume, Pod, Event, DiskUsage), so the views above it do not know which engine answers. The calls are the ones of SPEC §10.20: containers, images (with pull progress), networks, volumes, pods (Podman), the event stream, logs (the multiplexed stream split into stdout and stderr), exec (output captured, not interactive) and "system df".

Every call that does I/O takes a ctx as its first parameter. A stream (Events, Logs, PullImage) ends when its ctx is cancelled and then returns nil, because the caller asked for it. Response bodies are limited (Options.MaxBody, and MaxFrame for the log stream), and a failure keeps the engine's own message. All errors have a tag that starts with ContainerAPI.

Find looks for the engine to use: the setting, the environment, Docker's contexts and the default sockets; for Podman it starts a "podman system service" of its own on a private socket when none answers (StartService), stopped with Close.

The package containerapitest has a fake engine that speaks both APIs, for the default tests, and a harness for tests against the user's real Docker and Podman that touches only things it created and labelled.

Index

Constants

View Source
const (
	// MinDockerAPI is the oldest Docker API version the Client works with, MaxDockerAPI the newest one it uses: with a newer
	// engine it still asks for this version, which every newer engine understands.
	MinDockerAPI = "1.41"
	MaxDockerAPI = "1.47"
	// LibpodAPI is the version in the paths of Podman's libpod API, and MinPodmanMajor the oldest Podman (major version).
	LibpodAPI      = "4.0.0"
	MinPodmanMajor = 4
)

The API versions the Client speaks (SPEC §10.20).

View Source
const (
	// DefaultDockerSocket is where the Docker daemon listens.
	DefaultDockerSocket = "/var/run/docker.sock"
	// RootfulPodmanSocket is the socket of Podman running as root.
	RootfulPodmanSocket = "/run/podman/podman.sock"
)

The default sockets (SPEC §10.20 "Which engine").

View Source
const (
	LabelCompose        = "com.docker.compose.project"
	LabelComposeService = "com.docker.compose.service"
)

LabelCompose is the label that Compose puts on the containers of a project, and LabelComposeService the one with the name of the service.

View Source
const (
	// DefaultMaxBody is the most bytes of a JSON response the Client reads.
	DefaultMaxBody = 32 << 20
)
View Source
const DefaultMaxExecOutput = 4 << 20

DefaultMaxExecOutput is the most bytes of output, both streams together, that Exec collects.

View Source
const LabelPodmanCompose = "io.podman.compose.project"

LabelPodmanCompose is the label that podman-compose puts on the containers of a project, next to the one of Docker's Compose when its version sets that too (SPEC §10.20 "Podman only").

View Source
const MaxFrame = 1 << 20

MaxFrame is the largest frame of the multiplexed stream that Demux accepts. Engines write frames of at most 32 KiB; a header that claims more is a damaged stream, not a reason to allocate that much.

View Source
const MaxLogLine = 64 << 10

MaxLogLine is the longest line the Logs call hands over; a longer line is cut into pieces of this size.

Variables

This section is empty.

Functions

func Demux

func Demux(r io.Reader, fn func(Frame) error) error

Demux splits the multiplexed stream that the engines send for the logs and the exec output of a container that has no terminal: frames of an 8-byte header (the stream in the first byte, three zero bytes, the length as a big-endian 32-bit number) and the payload. fn is called for each frame; its error ends Demux and is returned. A stream that ends between two frames is a normal end; one that ends in the middle of a frame, an unknown stream, a header with non-zero reserved bytes and a frame longer than MaxFrame are errors with the tag ContainerAPIFrameInvalid. A failing reader is ContainerAPIStreamFailed.

func ShortID

func ShortID(id string) string

ShortID returns the first 12 characters of an id, without a "sha256:" prefix.

Types

type Attempt

type Attempt struct {
	// Source says why it was tried ("the setting containers.host", "DOCKER_HOST", ...), Endpoint is where, Err why it did
	// not answer ("" for the one that did).
	Source, Endpoint, Err string
}

Attempt is a place Find looked at.

type Client

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

Client talks to one engine. It is safe for use from several goroutines.

func New

func New(kind Kind, ep Endpoint, opts Options) *Client

New makes a Client for the engine of the given kind at ep. It does no I/O: the first call negotiates the API version (Negotiate does it at once, to find out whether the engine answers).

func (*Client) Close

func (c *Client) Close()

Close closes the idle connections of the Client. The Client can still be used afterwards.

func (*Client) CreateContainer

func (c *Client) CreateContainer(ctx context.Context, spec ContainerSpec) (CreateResult, error)

CreateContainer makes a container from spec, without starting it. The image has to be there; create does not pull it. A spec with a Pod is for Podman only (ContainerAPINotSupported for Docker).

func (*Client) CreateNetwork

func (c *Client) CreateNetwork(ctx context.Context, spec NetworkSpec) (string, error)

CreateNetwork makes a network and returns its id.

func (*Client) CreatePod

func (c *Client) CreatePod(ctx context.Context, spec PodSpec) (string, error)

CreatePod makes a pod and returns its id (Podman only).

func (*Client) CreateVolume

func (c *Client) CreateVolume(ctx context.Context, spec VolumeSpec) (*Volume, error)

CreateVolume makes a volume.

func (*Client) DiskUsage

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

DiskUsage returns what the images, containers, volumes and build cache use ("system df"). The size maps are keyed by the image id without "sha256:" and by the volume name.

func (*Client) Endpoint

func (c *Client) Endpoint() Endpoint

Endpoint returns where the engine listens.

func (*Client) Events

func (c *Client) Events(ctx context.Context, opts EventsOptions, fn func(Event) error) error

Events reads the engine's event stream and calls fn for each event until ctx is cancelled (then it returns nil), fn returns an error (which Events returns), or the stream ends. A stream that ends by itself while there is no Until is the engine going away: that is the error ContainerAPIStreamEnded, so that the caller can connect again.

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, id string, opts ExecOptions) (ExecResult, error)

Exec runs a command in a running container without a terminal and collects its output (create, start, read the multiplexed stream, inspect for the exit status). It does not feed the command's input.

func (*Client) ImageHistory

func (c *Client) ImageHistory(ctx context.Context, name string) ([]HistoryEntry, error)

ImageHistory returns the layers of an image, newest first.

func (*Client) InspectContainer

func (c *Client) InspectContainer(ctx context.Context, id string) (*ContainerInspect, error)

InspectContainer returns the details of a container (by id or name), with the engine's JSON in Raw.

func (*Client) InspectImage

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

InspectImage returns the details of an image (by name or id), with the engine's JSON in Raw.

func (*Client) InspectNetwork

func (c *Client) InspectNetwork(ctx context.Context, id string) (*Network, error)

InspectNetwork returns one network (by id or name), with the engine's JSON in Raw.

func (*Client) InspectPod

func (c *Client) InspectPod(ctx context.Context, id string) (*Pod, error)

InspectPod returns one pod (by id or name), with the engine's JSON in Raw (Podman only).

func (*Client) InspectVolume

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

InspectVolume returns one volume (by name), with the engine's JSON in Raw.

func (*Client) KillContainer

func (c *Client) KillContainer(ctx context.Context, id, signal string) error

KillContainer sends a signal ("SIGKILL" when signal is empty) to a container's main process.

func (*Client) Kind

func (c *Client) Kind() Kind

Kind returns the engine's kind.

func (*Client) ListContainers

func (c *Client) ListContainers(ctx context.Context, opts ListContainersOptions) ([]Container, error)

ListContainers lists the containers. The names have no leading slash and the ports are in one form for both engines.

func (*Client) ListImages

func (c *Client) ListImages(ctx context.Context, opts ListImagesOptions) ([]Image, error)

ListImages lists the images. An image with no name has Dangling set and no RepoTags.

func (*Client) ListNetworks

func (c *Client) ListNetworks(ctx context.Context, filters Filters) ([]Network, error)

ListNetworks lists the networks that match filters (all of them without filters).

func (*Client) ListPods

func (c *Client) ListPods(ctx context.Context, filters Filters) ([]Pod, error)

ListPods lists the pods that match filters (Podman only).

func (*Client) ListVolumes

func (c *Client) ListVolumes(ctx context.Context, filters Filters) ([]Volume, error)

ListVolumes lists the volumes that match filters (all of them without filters).

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, id string, opts LogsOptions, fn func(LogLine) error) error

Logs reads the logs of a container and calls fn for each line. The multiplexed stream is split into stdout and stderr lines; a container with a terminal has one stream, which is reported as stdout. Without Follow it returns when the logs are done; with it, when ctx is cancelled (then it returns nil), the container stops, or fn returns an error (which Logs returns). The part of a line still unfinished when the stream ends is emitted too, unless ctx was cancelled.

func (*Client) Negotiate

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

Negotiate finds out which API version to speak with /_ping and /version, and returns what the engine says about itself. The first call does the work, a later one returns the same answer; a failed call is tried again by the next one.

The errors have the tags ContainerAPIConnectFailed (nothing answers on the socket), ContainerAPIVersionTooOld (Docker below 1.41, Podman below 4), ContainerAPIVersionTooNew (an engine whose oldest version is newer than MaxDockerAPI), ContainerAPIEngineMismatch (a Podman Client on an engine that is not Podman) and the tags of every call.

func (*Client) PauseContainer

func (c *Client) PauseContainer(ctx context.Context, id string) error

PauseContainer freezes the processes of a container.

func (*Client) PodDo

func (c *Client) PodDo(ctx context.Context, id string, action PodAction) error

PodDo applies an action to a pod and its containers (Podman only). Stopping a pod that is stopped is not an error.

func (*Client) PruneContainers

func (c *Client) PruneContainers(ctx context.Context, filters Filters) (PruneResult, error)

PruneContainers removes the stopped containers that match filters (all of them without filters).

func (*Client) PruneImages

func (c *Client) PruneImages(ctx context.Context, opts PruneImagesOptions) (PruneResult, error)

PruneImages removes the unused images that match opts.Filters: the dangling ones, or every unused one with opts.All.

func (*Client) PruneNetworks

func (c *Client) PruneNetworks(ctx context.Context, filters Filters) (PruneResult, error)

PruneNetworks removes the unused networks that match filters.

func (*Client) PrunePods

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

PrunePods removes the stopped pods (Podman only).

func (*Client) PruneVolumes

func (c *Client) PruneVolumes(ctx context.Context, filters Filters) (PruneResult, error)

PruneVolumes removes the unused volumes that match filters.

func (*Client) PullImage

func (c *Client) PullImage(ctx context.Context, ref string, progress func(PullProgress)) error

PullImage pulls an image by reference ("busybox:1.37", "ghcr.io/org/app@sha256:..."), calling progress (when it is not nil) for each line the engine sends. It returns when the pull is complete. A failure the engine reports in the stream is a ContainerAPIPullFailed error.

func (*Client) RemoveContainer

func (c *Client) RemoveContainer(ctx context.Context, id string, opts RemoveOptions) error

RemoveContainer removes a container. A running one is removed only with opts.Force.

func (*Client) RemoveImage

func (c *Client) RemoveImage(ctx context.Context, name string, opts RemoveImageOptions) (RemoveImageResult, error)

RemoveImage removes an image (or one of its names), and says which names were taken off and which images went.

func (*Client) RemoveNetwork

func (c *Client) RemoveNetwork(ctx context.Context, id string) error

RemoveNetwork removes a network (by id or name).

func (*Client) RemovePod

func (c *Client) RemovePod(ctx context.Context, id string, force bool) error

RemovePod removes a pod and its containers (Podman only). A pod that runs is removed only with force.

func (*Client) RemoveVolume

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

RemoveVolume removes a volume. A volume that a container uses is removed only with force.

func (*Client) RenameContainer

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

RenameContainer gives a container a new name.

func (*Client) RestartContainer

func (c *Client) RestartContainer(ctx context.Context, id string, timeout time.Duration) error

RestartContainer stops and starts a container; timeout is as for StopContainer.

func (*Client) StartContainer

func (c *Client) StartContainer(ctx context.Context, id string) error

StartContainer starts a container. Starting one that runs already is not an error.

func (*Client) StopContainer

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

StopContainer stops a container: SIGTERM, then SIGKILL after timeout (the engine's default when timeout is not positive, and at least one second otherwise). Stopping one that is stopped already is not an error.

func (*Client) StopPod

func (c *Client) StopPod(ctx context.Context, id string, timeout time.Duration) error

StopPod stops a pod and its containers: SIGTERM, then SIGKILL after timeout (Podman's default, ten seconds, when timeout is not positive). Stopping a pod that is stopped is not an error (Podman only).

func (*Client) TagImage

func (c *Client) TagImage(ctx context.Context, name, repo, tag string) error

TagImage gives an image another name: repo and tag ("tag" empty is latest).

func (*Client) UnpauseContainer

func (c *Client) UnpauseContainer(ctx context.Context, id string) error

UnpauseContainer thaws a paused container.

type Container

type Container struct {
	// ID is the full container id.
	ID string
	// Names are the names of the container, without the leading slash Docker adds.
	Names []string
	// Image is the image the container was made from, ImageID its id.
	Image, ImageID string
	// Command is the command the container runs, as one line.
	Command string
	// Created is when the container was made. StartedAt is when it last started; Docker's list does not say, so it is
	// the zero time there.
	Created, StartedAt time.Time
	// State is one of created, running, paused, restarting, removing, exited, dead and stopped; Status is the engine's
	// sentence ("Up 2 hours"; empty from Podman).
	State, Status string
	// Ports are the published and exposed ports.
	Ports []Port
	// Labels are the labels of the container.
	Labels map[string]string
	// Pod and PodName are the id and the name of the pod of the container (Podman; empty otherwise).
	Pod, PodName string
	// Networks are the names of the networks the container is connected to.
	Networks []string
}

Container is one row of the container list.

func (Container) ComposeProject

func (c Container) ComposeProject() string

ComposeProject returns the Compose project of the container, or "" when it was not made by Compose (Docker's label, else the one of podman-compose).

func (Container) Name

func (c Container) Name() string

Name returns the first name of the container, or its short id when it has none.

func (Container) Running

func (c Container) Running() bool

Running reports whether the container is running (or paused or restarting, which still hold a process).

type ContainerInspect

type ContainerInspect struct {
	// ID is the full id, Name the name without the slash, Image the image id and ImageName the name the container was
	// made from.
	ID, Name, Image, ImageName string
	// Created is when the container was made.
	Created time.Time
	// State is the state.
	State ContainerState
	// Env, Cmd, Entrypoint, WorkingDir, Hostname, User, Labels and Tty are the container's configuration.
	Env, Cmd, Entrypoint []string
	WorkingDir, Hostname string
	User                 string
	Labels               map[string]string
	Tty                  bool
	// Ports are the published ports, keyed by "80/tcp".
	Ports map[string][]PortBinding
	// Networks are the names of the networks the container is connected to.
	Networks []string
	// Mounts are the mounts.
	Mounts []Mount
	// Pod is the id of the pod of the container (Podman).
	Pod string
	// Raw is the JSON the engine sent, for the Inspect action.
	Raw json.RawMessage
}

ContainerInspect is the part of an inspected container that the views use, with the whole JSON in Raw.

func ParseInspect

func ParseInspect(raw []byte) (*ContainerInspect, error)

ParseInspect reads the JSON an engine answers to the inspect of a container (Docker's or Podman's) into a ContainerInspect with the JSON in Raw. It fails with ContainerAPIInspectInvalid.

type ContainerSpec

type ContainerSpec struct {
	// Name is the container's name; empty lets the engine pick one.
	Name string
	// Image is the image to run; it has to be there already, create does not pull.
	Image string
	// Cmd and Entrypoint replace the image's command and entrypoint when set.
	Cmd, Entrypoint []string
	// Env is the environment as "NAME=value".
	Env []string
	// Labels are put on the container.
	Labels map[string]string
	// Ports are published.
	Ports []PortMapping
	// Binds are the mounts as "source:destination[:options]": a source that starts with "/" or "." is a path on the
	// host, any other source is the name of a volume.
	Binds []string
	// AutoRemove removes the container when it stops (docker run --rm).
	AutoRemove bool
	// Network is the network to connect to; empty is the engine's default.
	Network string
	// Pod is the pod to put the container in (Podman only).
	Pod string
	// WorkingDir and User override the image's.
	WorkingDir, User string
	// Tty gives the container a terminal.
	Tty bool
}

ContainerSpec says what CreateContainer makes.

type ContainerState

type ContainerState struct {
	// Status is created, running, paused, restarting, removing, exited or dead.
	Status string
	// Running, Paused, Restarting, OOMKilled and Dead are the flags of the state.
	Running, Paused, Restarting, OOMKilled, Dead bool
	// Pid is the process id on the host (0 when stopped).
	Pid int
	// ExitCode is the code the last run ended with.
	ExitCode int
	// Error is the engine's error text of the last start.
	Error string
	// StartedAt and FinishedAt are the times of the last start and stop; the zero time when it never did.
	StartedAt, FinishedAt time.Time
	// Health is the status of the health check ("healthy", "unhealthy", "starting"), empty without one.
	Health string
}

ContainerState is the state part of an inspected container.

type CreateResult

type CreateResult struct {
	// ID is the id of the new container.
	ID string
	// Warnings are the engine's warnings.
	Warnings []string
}

CreateResult is what CreateContainer returns.

type DiskUsage

type DiskUsage struct {
	// Images, Containers, Volumes and BuildCache are the usage of each kind (the build cache is Docker's).
	Images, Containers, Volumes, BuildCache Usage
	// ImageSizes and VolumeSizes are the bytes of each image (by id) and volume (by name) where the engine says, for the
	// confirmation of a remove.
	ImageSizes, VolumeSizes map[string]int64
}

DiskUsage is the result of "system df".

func (DiskUsage) Total

func (d DiskUsage) Total() int64

Total returns the bytes of every kind together.

type DockerContext

type DockerContext struct {
	// Name is the name of the context ("default" for the one Docker always has).
	Name string
	// Description is the description it was made with.
	Description string
	// Host is the engine's host (unix:///..., tcp://...).
	Host string
	// SkipTLSVerify is the context's setting of that name.
	SkipTLSVerify bool
	// TLSDir holds the context's certificates (ca.pem, cert.pem, key.pem) when it has any.
	TLSDir string
	// Current marks the context the Docker CLI would use now.
	Current bool
}

DockerContext is a context of the Docker CLI.

func DockerContexts

func DockerContexts(getenv func(string) string) ([]DockerContext, error)

DockerContexts lists the contexts of the Docker CLI (the picker of the Containers view): "default" first, then the others by name, and marks the current one. Without a home folder or DOCKER_CONFIG only "default" is listed. getenv nil is os.Getenv.

type Endpoint

type Endpoint struct {
	// Network is "unix" or "tcp".
	Network string
	// Address is the path of the socket, or host:port.
	Address string
	// TLS is the configuration of the connection, nil for plain HTTP.
	TLS *tls.Config
}

Endpoint is where an engine listens.

func ParseHost

func ParseHost(host string, tlsOpts TLSOptions) (Endpoint, error)

ParseHost reads a host as DOCKER_HOST, CONTAINER_HOST and the settings write it: unix:///path, a bare absolute path, tcp://host[:port], http://host[:port] and https://host[:port]. A tcp host uses TLS when tlsOpts say so or the scheme is https. ssh://, npipe:// and fd:// are not built (SPEC §10.20 "Not built").

The errors have the tags ContainerAPIHostInvalid, ContainerAPIHostUnsupported and ContainerAPITLSFailed.

func UnixEndpoint

func UnixEndpoint(path string) Endpoint

UnixEndpoint returns the endpoint of a Unix socket.

func (Endpoint) Secure

func (e Endpoint) Secure() bool

Secure reports whether the connection uses TLS.

func (Endpoint) String

func (e Endpoint) String() string

String returns the endpoint as a host the engines' tools take: unix:///path or tcp://host:port.

type Event

type Event struct {
	// Type is container, image, network, volume, pod, daemon, ...; Action is start, die, create, pull, ...
	Type, Action string
	// ID is the id (or name) of what the event is about.
	ID string
	// Attributes are the actor's attributes: its name, its image and its labels.
	Attributes map[string]string
	// Scope is local or swarm.
	Scope string
	// Time is when it happened.
	Time time.Time
}

Event is an event of the engine's event stream.

type EventsOptions

type EventsOptions struct {
	// Since replays the events from this time on (the zero time starts at now); Until ends the stream at this time (the zero
	// time never).
	Since, Until time.Time
	// Filters are the engine's filters ({"type": {"container"}}).
	Filters Filters
	// Ready, when it is not nil, is called once the engine has accepted the subscription, before the first event is read: an
	// event that happens after Ready is not missed.
	Ready func()
}

EventsOptions are the options of Events.

type ExecOptions

type ExecOptions struct {
	// Cmd is the command and its arguments.
	Cmd []string
	// Env is added to the container's environment, as "NAME=value".
	Env []string
	// WorkingDir and User override the container's.
	WorkingDir, User string
	// MaxOutput is the most bytes of output collected; 0 is DefaultMaxExecOutput. More output is dropped and Truncated is set.
	MaxOutput int
	// Wait is how long to wait for the exit status after the output has ended; 0 is five seconds.
	Wait time.Duration
}

ExecOptions say what Exec runs.

type ExecResult

type ExecResult struct {
	// Stdout and Stderr are the output.
	Stdout, Stderr string
	// ExitCode is the exit status; -1 when the command had not ended (Running).
	ExitCode int
	// Running reports a command that was still running when Exec stopped waiting for it.
	Running bool
	// Truncated reports that output beyond MaxOutput was dropped.
	Truncated bool
}

ExecResult is what Exec collected.

type Filters

type Filters map[string][]string

Filters are the filters of a list or prune call, as the engines take them: a name and the values that match, for example {"label": {"dev.emetos.test=1"}}.

type FindOptions

type FindOptions struct {
	// Kind is the engine to find.
	Kind Kind
	// Host is the setting (containers.host, podman.host); empty is no setting.
	Host string
	// Context is the Docker context the user picked in the view (Docker only); it wins over every other source, because
	// the user chose it in the UI. Empty is none.
	Context string
	// Getenv reads the environment (DOCKER_HOST, DOCKER_CONTEXT, DOCKER_CONFIG, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH,
	// CONTAINER_HOST, HOME, XDG_RUNTIME_DIR, PATH); nil is os.Getenv. A test passes a map, so that it never reads the
	// user's environment, home or sockets.
	Getenv func(string) string
	// Client tunes the Clients made.
	Client Options
	// ProbeTimeout bounds the question to each candidate; 0 is three seconds.
	ProbeTimeout time.Duration
	// DockerSocket and RootfulPodmanSocket replace the default sockets (DefaultDockerSocket, RootfulPodmanSocket); a test points
	// them at a folder of its own, so that it never asks the engines of the computer it runs on.
	DockerSocket, RootfulPodmanSocket string
	// NoService stops Find from starting a Podman service of its own when no socket answers.
	NoService bool
	// Service says how that service is started (its Getenv defaults to this Getenv).
	Service ServiceOptions
}

FindOptions say where to look for the engine.

type Found

type Found struct {
	// Client talks to the engine.
	Client *Client
	// Info is what the engine says about itself.
	Info ServerInfo
	// Source says why this engine was chosen.
	Source string
	// Service is the Podman service that Find started, nil when an engine answered by itself.
	Service *Service
	// Attempts are all the places looked at, the one that answered last.
	Attempts []Attempt
}

Found is the engine Find connected to.

func Find

func Find(ctx context.Context, opts FindOptions) (*Found, error)

Find looks for the engine of opts.Kind and connects to it.

Docker: opts.Context, else opts.Host (containers.host), else DOCKER_HOST, else the current Docker context (DOCKER_CONTEXT, else "currentContext" of $DOCKER_CONFIG/config.json or ~/.docker/config.json, with its host and certificates from contexts/), else unix:///var/run/docker.sock. The first source that is set is the only one asked: an engine the user named is never replaced by another one.

Podman: opts.Host (podman.host), else CONTAINER_HOST, then (the user named nothing) the user's socket $XDG_RUNTIME_DIR/podman/podman.sock, then /run/podman/podman.sock, and when none answers a "podman system service" of Emetos's own (StartService), unless NoService.

When nothing answers, the error is ContainerAPIEngineNotFound; its message lists what was tried and why each failed, and its metadata "attempts" has the same as a list.

func (*Found) Close

func (f *Found) Close()

Close stops the Podman service that Find started, if any, and closes the connections.

type Frame

type Frame struct {
	// Stream is the output the data came from.
	Stream Stream
	// Data is the payload; it is valid only until fn returns.
	Data []byte
}

Frame is one piece of the multiplexed stream.

type HistoryEntry

type HistoryEntry struct {
	// ID is the id of the layer ("<missing>" for one that is not kept).
	ID string
	// Created is when the layer was made.
	Created time.Time
	// CreatedBy is the command that made it.
	CreatedBy string
	// Tags are the names of the image at this layer.
	Tags []string
	// Size is the size of the layer in bytes.
	Size int64
	// Comment is the comment of the layer.
	Comment string
}

HistoryEntry is a layer of an image's history.

type Image

type Image struct {
	// ID is the image id, with the "sha256:" prefix when the engine gives it.
	ID string
	// RepoTags are the names of the image ("repository:tag"); empty for a dangling image.
	RepoTags []string
	// RepoDigests are the digests of the image ("repository@sha256:...").
	RepoDigests []string
	// Created is when the image was built.
	Created time.Time
	// Size is the size in bytes.
	Size int64
	// Containers is the number of containers that use the image; -1 when the engine did not count.
	Containers int
	// Labels are the labels of the image.
	Labels map[string]string
	// Dangling reports an image with no name.
	Dangling bool
}

Image is one row of the image list.

type ImageInspect

type ImageInspect struct {
	// ID is the image id, RepoTags and RepoDigests its names.
	ID                    string
	RepoTags, RepoDigests []string
	// Created is when the image was built, Size its size in bytes.
	Created time.Time
	Size    int64
	// Architecture and OS are the platform of the image.
	Architecture, OS string
	// Env, Cmd, Entrypoint, WorkingDir, User, Labels and ExposedPorts are the image's configuration.
	Env, Cmd, Entrypoint []string
	WorkingDir, User     string
	Labels               map[string]string
	ExposedPorts         []string
	// Raw is the JSON the engine sent.
	Raw json.RawMessage
}

ImageInspect is the part of an inspected image that the views use, with the whole JSON in Raw.

type Kind

type Kind string

Kind is the engine a Client speaks to.

const (
	// KindDocker is the Docker Engine API (and anything that speaks it).
	KindDocker Kind = "docker"
	// KindPodman is Podman's libpod API.
	KindPodman Kind = "podman"
)

The two engines.

type LineSplitter

type LineSplitter struct {
	// Max is the longest line that is handed over whole; 0 is MaxLogLine.
	Max int
	// contains filtered or unexported fields
}

LineSplitter turns the frames of the multiplexed stream into lines: a frame may hold several lines or a part of one, and the two streams are kept apart. A line longer than Max is cut.

func (*LineSplitter) Flush

func (l *LineSplitter) Flush(emit func(Stream, string) error) error

Flush emits the part of a line that is left on each stream (the output of a program that ends without a line end).

func (*LineSplitter) Write

func (l *LineSplitter) Write(stream Stream, data []byte, emit func(Stream, string) error) error

Write adds the data of a frame to its stream and calls emit for each line that is complete. The error of emit stops it and is returned.

type ListContainersOptions

type ListContainersOptions struct {
	// All lists stopped containers too.
	All bool
	// Filters are the engine's filters.
	Filters Filters
}

ListContainersOptions are the options of ListContainers.

type ListImagesOptions

type ListImagesOptions struct {
	// All lists the intermediate images too.
	All bool
	// Filters are the engine's filters.
	Filters Filters
}

ListImagesOptions are the options of ListImages.

type LogLine

type LogLine struct {
	// Stream is stdout or stderr.
	Stream Stream
	// Time is the timestamp the engine put in front of the line, when LogsOptions.Timestamps asked for it.
	Time time.Time
	// Text is the line without its line end.
	Text string
}

LogLine is one line of a container's output.

type LogsOptions

type LogsOptions struct {
	// Stdout and Stderr choose the outputs; neither set means both.
	Stdout, Stderr bool
	// Follow keeps the call open for new output until ctx is cancelled or the container stops.
	Follow bool
	// Timestamps asks the engine to put a time in front of each line, which is parsed into LogLine.Time.
	Timestamps bool
	// Tail is the number of lines from the end to start with; 0 is all.
	Tail int
	// Since starts at this time; the zero time is the beginning.
	Since time.Time
}

LogsOptions are the options of Logs.

type Mount

type Mount struct {
	// Type is bind, volume or tmpfs; Name is the volume's name, Source the path on the host, Destination the path in the
	// container.
	Type, Name, Source, Destination string
	// RW reports whether the mount is writable.
	RW bool
}

Mount is a mount of a container.

type Network

type Network struct {
	// ID and Name identify the network.
	ID, Name string
	// Driver is bridge, host, overlay, macvlan, ...; Scope is local or swarm.
	Driver, Scope string
	// Created is when the network was made.
	Created time.Time
	// Internal reports a network with no outside access, IPv6 one with IPv6.
	Internal, IPv6 bool
	// Subnets are the address ranges.
	Subnets []Subnet
	// Labels are the labels of the network.
	Labels map[string]string
	// Raw is the JSON the engine sent for this network.
	Raw json.RawMessage
}

Network is a network.

type NetworkSpec

type NetworkSpec struct {
	// Name is the name of the network.
	Name string
	// Driver is the driver; empty is bridge.
	Driver string
	// Labels are put on the network.
	Labels map[string]string
	// Internal makes a network with no outside access.
	Internal bool
	// IPv6 turns IPv6 on.
	IPv6 bool
}

NetworkSpec says what CreateNetwork makes.

type Options

type Options struct {
	// MaxBody is the most bytes of a JSON response the Client reads; 0 is DefaultMaxBody. A longer response is an error
	// (ContainerAPIBodyTooLarge), not a truncated read.
	MaxBody int64
	// DialTimeout bounds the connect to the engine; 0 is 10 seconds.
	DialTimeout time.Duration
}

Options tune a Client.

type Pod

type Pod struct {
	// ID and Name identify the pod.
	ID, Name string
	// Status is Created, Running, Stopped, Exited, Paused or Degraded.
	Status string
	// Created is when the pod was made.
	Created time.Time
	// InfraID is the id of the pod's infra container.
	InfraID string
	// Labels are the labels of the pod.
	Labels map[string]string
	// Containers are the containers of the pod, the infra container among them.
	Containers []PodContainer
	// Raw is the JSON the engine sent for this pod.
	Raw json.RawMessage
}

Pod is a Podman pod.

type PodAction

type PodAction string

PodAction is something a pod can be told to do.

const (
	PodStart   PodAction = "start"
	PodRestart PodAction = "restart"
	PodKill    PodAction = "kill"
	PodPause   PodAction = "pause"
	PodUnpause PodAction = "unpause"
)

The actions of a pod.

type PodContainer

type PodContainer struct {
	// ID, Name and Status identify the container and say how it is.
	ID, Name, Status string
}

PodContainer is a container of a pod.

type PodSpec

type PodSpec struct {
	// Name is the name of the pod; empty lets Podman pick one.
	Name string
	// Labels are put on the pod.
	Labels map[string]string
	// Ports are published by the pod: the containers of a pod share one network, so a container cannot publish a port of its own.
	Ports []PortMapping
}

PodSpec says what CreatePod makes.

type Port

type Port struct {
	// IP is the host address the port is published on; empty when it is only exposed.
	IP string
	// PrivatePort is the port in the container, PublicPort the one on the host (0 when only exposed).
	PrivatePort, PublicPort uint16
	// Type is "tcp", "udp" or "sctp".
	Type string
}

Port is a port a container publishes or exposes.

type PortBinding

type PortBinding struct {
	// HostIP and HostPort are where the port is published on the host.
	HostIP, HostPort string
}

PortBinding is a published port of a container as inspect reports it.

type PortMapping

type PortMapping struct {
	// HostIP is the address on the host; empty is every interface (the test harness insists on 127.0.0.1).
	HostIP string
	// HostPort is the port on the host; 0 lets the engine pick one.
	HostPort uint16
	// ContainerPort is the port in the container.
	ContainerPort uint16
	// Protocol is "tcp" (the default) or "udp".
	Protocol string
}

PortMapping publishes a port of a container.

type PruneImagesOptions

type PruneImagesOptions struct {
	// All removes every unused image, not only the dangling ones.
	All bool
	// Filters are the engine's filters.
	Filters Filters
}

PruneImagesOptions are the options of PruneImages.

type PruneResult

type PruneResult struct {
	// Deleted are the ids or names of what went.
	Deleted []string
	// SpaceReclaimed is the number of bytes freed, when the engine says.
	SpaceReclaimed int64
}

PruneResult is what a prune call reports.

type PullProgress

type PullProgress struct {
	// ID is the layer the line is about (empty for the whole image).
	ID string
	// Status is the text of the line ("Downloading", "Pull complete", ...).
	Status string
	// Current and Total are bytes, when the line has them.
	Current, Total int64
}

PullProgress is one line of the progress of a pull.

type RemoveImageOptions

type RemoveImageOptions struct {
	// Force removes the image even when containers use it or it has several names.
	Force bool
	// NoPrune keeps the untagged parents (Docker).
	NoPrune bool
}

RemoveImageOptions are the options of RemoveImage.

type RemoveImageResult

type RemoveImageResult struct {
	// Untagged are the names that were taken off, Deleted the image ids that went.
	Untagged, Deleted []string
}

RemoveImageResult says what RemoveImage removed.

type RemoveOptions

type RemoveOptions struct {
	// Force removes a running container (kills it first).
	Force bool
	// Volumes removes the anonymous volumes of the container too.
	Volumes bool
}

RemoveOptions are the options of the remove calls.

type ServerInfo

type ServerInfo struct {
	// Kind is the engine's kind.
	Kind Kind
	// Engine is the engine's name ("Docker Engine - Community", "Podman Engine").
	Engine string
	// Version is the engine's own version ("29.9.2", "5.8.9").
	Version string
	// ServerAPIVersion is the newest API version the engine speaks, MinAPIVersion the oldest.
	ServerAPIVersion, MinAPIVersion string
	// APIVersion is the version the Client uses in its paths: the newest both sides speak ("1.47"; "4.0.0" for libpod).
	APIVersion string
	// OS and Arch are the engine's platform.
	OS, Arch string
}

ServerInfo is what the engine says about itself.

type Service

type Service struct {
	// Socket is the path of the Unix socket the service listens on.
	Socket string
	// contains filtered or unexported fields
}

Service is a "podman system service" that Emetos started on a socket of its own (SPEC §10.20 "Which engine"), so that nothing has to be enabled in systemd. It runs as a child in its own process group and ends with Stop, or when this process dies (the child gets SIGTERM then).

func StartService

func StartService(ctx context.Context, opts ServiceOptions) (*Service, error)

StartService starts "podman system service --time=0 unix://<socket>" and waits until the socket answers. The service is a child in a process group of its own. The errors have the tags ContainerAPIPodmanNotFound (no podman program), ContainerAPIPodmanStartFailed (it did not start, or ended at once; the message holds the end of its error output) and ContainerAPIPodmanTimeout (the socket did not answer in time).

func (*Service) Done

func (s *Service) Done() <-chan struct{}

Done is closed when the service has ended, whether by Stop or by itself.

func (*Service) Stop

func (s *Service) Stop()

Stop ends the service: SIGTERM to its process group, SIGKILL after the grace time, and the socket is removed. It is safe to call more than once and from several goroutines.

type ServiceOptions

type ServiceOptions struct {
	// Program is the podman program (found on PATH when it has no slash); empty is "podman".
	Program string
	// Getenv reads the variables PATH and XDG_RUNTIME_DIR; nil is os.Getenv.
	Getenv func(string) string
	// Env is the whole environment of the service; nil is the environment of this process.
	Env []string
	// SocketDir is the folder of the socket; empty is $XDG_RUNTIME_DIR/emetos, and a folder made in the temporary folder
	// when there is no XDG_RUNTIME_DIR.
	SocketDir string
	// PID names the socket (podman-<PID>.sock); 0 is the process id of this process.
	PID int
	// ReadyTimeout is how long to wait for the socket to answer; 0 is 15 seconds.
	ReadyTimeout time.Duration
	// Grace is how long Stop waits after SIGTERM before it kills the process group; 0 is five seconds.
	Grace time.Duration
	// Client tunes the Client that probes the socket.
	Client Options
}

ServiceOptions say how StartService runs "podman system service".

type Stream

type Stream uint8

Stream says which output a frame or a line belongs to.

const (
	// StreamStdin is the header value 0, which engines do not send for logs.
	StreamStdin Stream = 0
	// StreamStdout and StreamStderr are the container's two outputs.
	StreamStdout Stream = 1
	StreamStderr Stream = 2
)

The streams of the multiplexed log and exec output.

func (Stream) String

func (s Stream) String() string

String returns "stdin", "stdout" or "stderr".

type Subnet

type Subnet struct {
	// Subnet is the range in CIDR form and Gateway the gateway address.
	Subnet, Gateway string
}

Subnet is a subnet of a network.

type TLSOptions

type TLSOptions struct {
	// Verify turns TLS on and checks the server's certificate (DOCKER_TLS_VERIFY).
	Verify bool
	// CertDir holds ca.pem, cert.pem and key.pem (DOCKER_CERT_PATH). A missing ca.pem means the system's roots, and a
	// missing cert.pem or key.pem means no client certificate.
	CertDir string
	// SkipVerify turns TLS on without checking the server's certificate (a Docker context made with skip-tls-verify).
	SkipVerify bool
}

TLSOptions say how a tcp:// host is secured (SPEC §10.20): the variables of the Docker CLI, DOCKER_TLS_VERIFY and DOCKER_CERT_PATH, in a struct.

type Usage

type Usage struct {
	// Count is how many there are, Active how many are in use, Size the bytes they use and Reclaimable the bytes that
	// removing the unused ones would free.
	Count, Active int
	Size          int64
	Reclaimable   int64
}

Usage is the disk usage of one kind of object.

type Volume

type Volume struct {
	// Name identifies the volume.
	Name string
	// Driver is the volume driver, Mountpoint the path on the host and Scope local or global.
	Driver, Mountpoint, Scope string
	// Created is when the volume was made.
	Created time.Time
	// Labels and Options are the volume's.
	Labels, Options map[string]string
	// Size is the bytes the volume uses when the engine counted them (Docker, with "system df"), else -1.
	Size int64
	// Raw is the JSON the engine sent for this volume.
	Raw json.RawMessage
}

Volume is a volume.

type VolumeSpec

type VolumeSpec struct {
	// Name is the name of the volume; empty lets the engine pick one.
	Name string
	// Driver is the driver; empty is local.
	Driver string
	// Labels are put on the volume.
	Labels map[string]string
}

VolumeSpec says what CreateVolume makes.

Directories

Path Synopsis
Package containerapitest is the test side of containerapi (SPEC §10.20, step 18.1): a fake engine that speaks both the Docker Engine API and Podman's libpod API, for the default tests of the container extensions, and a harness for the tests against the user's real Docker and Podman (build tags emetos_docker and emetos_podman), which touches only the things it made itself: containers, networks, volumes and pods named emetos-test-<random> that carry the label dev.emetos.test=1, with ports published on 127.0.0.1 only, removed when the test ends (also when it fails).
Package containerapitest is the test side of containerapi (SPEC §10.20, step 18.1): a fake engine that speaks both the Docker Engine API and Podman's libpod API, for the default tests of the container extensions, and a harness for the tests against the user's real Docker and Podman (build tags emetos_docker and emetos_podman), which touches only the things it made itself: containers, networks, volumes and pods named emetos-test-<random> that carry the label dev.emetos.test=1, with ports published on 127.0.0.1 only, removed when the test ends (also when it fails).
fakeengine command
Command fakeengine serves the fake Docker engine of containerapitest on a Unix socket, with a scenario of containers, images, networks and volumes, until it gets SIGINT or SIGTERM.
Command fakeengine serves the fake Docker engine of containerapitest on a Unix socket, with a scenario of containers, images, networks and volumes, until it gets SIGINT or SIGTERM.

Jump to

Keyboard shortcuts

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