dockerx

package
v0.7.40 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package dockerx wraps the docker CLI behind the smallest interface the engine needs. The CLI, not an SDK: the runner targets "plain docker CE on a server", the CLI is the one interface guaranteed present there, and an interface this small stays fakeable — the whole execute path is unit-tested against Fake.

Fake is the test double for Client: it records every call in order and lets tests script failures and the agent container's behavior. The engine's whole lifecycle — ordering, teardown-on-every-path, env/mount resolution — is asserted against this recorder, so the execute path is proven without a docker daemon.

Index

Constants

View Source
const (
	KindDocker = "docker"
	KindPodman = "podman"
)

The kinds of container engine the runner drives: what the daemon says it is, not which CLI talks to it.

View Source
const (
	SchemeUnix  = "unix"
	SchemeNpipe = "npipe"
)

Endpoint schemes the docker and podman clients use.

View Source
const (
	EnvEngine = "AGENTRY_ENGINE"
	EnvDocker = "AGENTRY_DOCKER"
	EnvPodman = "AGENTRY_PODMAN"
)

Engine selection. AGENTRY_ENGINE names the CLI to drive ("docker" or "podman"); AGENTRY_DOCKER and AGENTRY_PODMAN name each binary. With no engine named and no docker endpoint given (DOCKER_HOST, DOCKER_CONTEXT), the client finds its engine on first use: the docker CLI when it reaches a daemon, else podman when it is installed and answers, else the docker CLI again, whose error then says what is missing. A miss is not kept, so an engine that starts later is found.

View Source
const DefaultBridge = "bridge"

DefaultBridge is docker's name for its default network, the one a container reaches past the host through.

View Source
const DefaultSocket = "/var/run/docker.sock"

DefaultSocket is the Docker Engine's conventional socket.

View Source
const HostUDSOpen = "--host-uds=open"

HostUDSOpen is the gVisor flag that lets a sandboxed container open a Unix socket bind-mounted from the host: the gateway's way to its run's docker filter (docker.gatewayRuntime).

View Source
const LogsAll = 0

LogsAll asks Logs for the whole log.

Variables

This section is empty.

Functions

func CheckHostUDSRegistration

func CheckHostUDSRegistration(table map[string]Runtime, runtime, gateway string) error

CheckHostUDSRegistration says why the registration named gateway is not the one named runtime plus HostUDSOpen: the same binary, the runtime's own arguments and that flag, nothing more. The receipt says the gateway ran under that runtime, so a registration that runs runc, or adds a flag such as --network=host or --host-uds=all, would make the claim false. A name missing from the table, or a registration with no binary, is refused too. nil when it is right.

func CheckHostUDSWrapper

func CheckHostUDSWrapper(path, runtime, gateway string) error

CheckHostUDSWrapper says why the file podman registers for the gateway's runtime (gateway, at path) is not a wrapper that runs the policy's runtime (registered at runtime) with HostUDSOpen: podman takes a path per runtime name and no arguments, so the gateway's runtime is a script that adds the flag, and the script is read for it. It must name the runtime's own path or the binary that path runs, since docker.runtime is itself a wrapper where the runtime needs a flag of its own (a rootless podman's --ignore-cgroups). A binary cannot be read that way and is refused with the recipe. nil when it is right.

func ConfigFile

func ConfigFile() string

ConfigFile is the docker CLI's configuration file, config.json under DOCKER_CONFIG or under ~/.docker; "" when neither names a directory.

func HostKernel

func HostKernel() string

HostKernel is this machine's kernel release, "" where it cannot be read (any system but Linux).

func ParseEndpoint

func ParseEndpoint(raw string) (scheme, addr string, err error)

ParseEndpoint splits a client endpoint into its scheme and its address: the socket's path for unix://, the pipe's for npipe://, host[:port] for tcp:// and ssh://. A bare absolute path is a Unix socket.

func PersonUser

func PersonUser(ctx context.Context, d Client) (string, error)

PersonUser is the --user a container runs as when the files it writes into the person's directories must be theirs: their own uid:gid on a rootful engine, and root on a rootless one, where the container's root is the person and any other uid is a subordinate one that cannot write their directories. "" leaves the image's own user, on a host without POSIX ids.

func PingSocket

func PingSocket(ctx context.Context, path string) error

PingSocket asks the Docker API on a Unix socket for /_ping: an engine is known by its answer, never by its socket file, which a stopped service can leave behind.

func RunDetachedUnder

func RunDetachedUnder(ctx context.Context, d Client, r RunSpec, class string) error

RunDetachedUnder is RunDetached for a container that may have to run under the policy's runtime (r.Runtime). Without one it is RunDetached. With one, the container is created, its runtime read back from the engine and compared, and only then started; a mismatch removes it and returns a *RuntimeMismatch naming class. On a podman engine on an SELinux host the container is created with its label disabled, since gVisor refuses a labelled container there. A client that cannot create and inspect (no Creator) is refused a runtime: the receipt says each container was checked, so an unchecked one never starts.

func RunForegroundUnder

func RunForegroundUnder(ctx context.Context, d Client, r RunSpec, class string, stdin io.Reader, stdout, stderr io.Writer) (int, error)

RunForegroundUnder is RunForeground with RunDetachedUnder's check.

func RuntimeBinary

func RuntimeBinary(path string) string

RuntimeBinary is the binary a registered runtime runs: the path itself, or, when the path is a wrapper script, the first absolute path in it that names an existing file, which is what such a script execs.

func SortedRuntimeNames

func SortedRuntimeNames(table map[string]Runtime) []string

SortedRuntimeNames lists a runtime table's names, sorted, for a message.

Types

type CLI

type CLI struct {
	// Bin is the client binary ("docker" resolved via PATH by default;
	// AGENTRY_DOCKER overrides for odd installs, AGENTRY_PODMAN for podman).
	Bin string
	// Podman says Bin is podman's own CLI.
	Podman bool
	// contains filtered or unexported fields
}

CLI is the real client. It drives the docker CLI, or podman's own (Podman), whose commands take docker's spelling for everything the runner creates and differ only in what they report about the engine.

func New

func New() *CLI

New returns a CLI client for the engine AGENTRY_ENGINE names, or for the one it finds on first use (resolve).

func (*CLI) Available

func (c *CLI) Available(ctx context.Context) error

Available implements Client. It asks the daemon for its version with `docker version`, not `docker info`: info also fills in its client section, which runs every CLI plugin for its metadata before the daemon is asked. A current Docker Desktop ships about thirty, and on Windows that took 2–6 s against about 0.1 s for version, answered or not. That cost would come out of the time a caller allows for an idle engine to wake. Both commands exit non-zero with the daemon's error on stderr when nothing answers; a server version that comes back empty is treated the same way.

For podman, whose CLI runs the engine itself, `podman info` is the check.

func (*CLI) Build

func (c *CLI) Build(ctx context.Context, dir, tag string, buildArgs map[string]string) error

Build implements Client. The docker CLI pointed at podman's socket is given DOCKER_BUILDKIT=0, so it calls the classic build endpoint podman serves instead of starting a BuildKit builder, which podman's API does not have and which would pull an image nobody asked for. podman's own CLI builds natively.

func (*CLI) CheckRuntime

func (c *CLI) CheckRuntime(ctx context.Context, name string) (Runtime, error)

CheckRuntime implements RuntimeChecker.

func (*CLI) ContainerIP

func (c *CLI) ContainerIP(ctx context.Context, name, network string) (string, error)

ContainerIP implements Client from `docker inspect`.

func (*CLI) ContainerRuntime

func (c *CLI) ContainerRuntime(ctx context.Context, name string) (string, error)

ContainerRuntime implements Creator. podman's own CLI names the runtime it created the container with (OCIRuntime); the docker CLI reads the daemon's HostConfig.Runtime, which Docker Engine fills with the name it applied and podman's Docker-compatible API with the constant "oci", whatever it ran: through that route the runtime cannot be read, and the check that reads it refuses the run.

func (*CLI) Create

func (c *CLI) Create(ctx context.Context, r RunSpec) error

Create implements Creator: `docker create` with `run`'s arguments.

func (*CLI) Engine

func (c *CLI) Engine(ctx context.Context) (Engine, error)

Engine implements EngineDescriber. The docker CLI is asked where its current context points (DOCKER_HOST and DOCKER_CONTEXT as it honours them), what the server's first component is called, and the daemon's hostname, kernel and security options; podman's own CLI answers all of it from `podman info`, and its API socket, which the run's docker filter and the gateway need, must answer a ping. The answer is kept for the life of the client.

func (*CLI) ExecStream

func (c *CLI) ExecStream(ctx context.Context, container string, argv []string, stdin io.Reader, stdout io.Writer) (int, error)

ExecStream implements Execer.

func (*CLI) ImageExists

func (c *CLI) ImageExists(ctx context.Context, ref string) (bool, error)

ImageExists implements Client.

func (*CLI) ImageFile

func (c *CLI) ImageFile(ctx context.Context, ref, path string) ([]byte, error)

ImageFile implements Client: `docker create` a container from the image (never started — the exec image has no shell to start with), `docker cp` the path out as a tar stream, `docker rm -fv` the container: -v, since creating it gave each VOLUME the image declares an anonymous volume.

func (*CLI) ImageLabel

func (c *CLI) ImageLabel(ctx context.Context, ref, key string) (string, error)

ImageLabel implements Client.

func (*CLI) Logs

func (c *CLI) Logs(ctx context.Context, name string, tail int) (string, error)

Logs implements Client. Both streams are returned: a container's stderr (where the gateway writes its startup errors) comes out of `docker logs` on stderr, and a diagnostic that dropped it explained nothing.

func (*CLI) NetworkConnect

func (c *CLI) NetworkConnect(ctx context.Context, network, container string) error

NetworkConnect implements Client. podman's default network has a name of its own ("podman" unless its configuration says otherwise), which podman gives in place of docker's.

func (*CLI) NetworkCreate

func (c *CLI) NetworkCreate(ctx context.Context, name string, internal bool, labels map[string]string) error

NetworkCreate implements Client.

func (*CLI) NetworkRemove

func (c *CLI) NetworkRemove(ctx context.Context, name string) error

NetworkRemove implements Client.

func (*CLI) NetworksByLabel

func (c *CLI) NetworksByLabel(ctx context.Context, label string) ([]string, error)

NetworksByLabel implements Client.

func (*CLI) OperatingSystem

func (c *CLI) OperatingSystem(ctx context.Context) (string, error)

OperatingSystem is what the daemon says it runs on (`docker info`'s OperatingSystem): "Docker Desktop" for Docker Desktop, the host's distribution for Docker Engine. A scheduled run that must go on after its person signs out tells the two apart by it.

func (*CLI) PSByLabel

func (c *CLI) PSByLabel(ctx context.Context, label string) ([]string, error)

PSByLabel implements Client.

func (*CLI) PSLabels

func (c *CLI) PSLabels(ctx context.Context, label string, keys []string) ([]Labeled, error)

PSLabels implements Client. Each key is read with docker's own {{.Label "k"}}, one tab-separated line per container, so a value is never split out of a comma-joined label list; the keys and the values this CLI writes carry no tabs or newlines.

func (*CLI) PodmanServiceCommand

func (c *CLI) PodmanServiceCommand(ctx context.Context, runtime, path string) (*exec.Cmd, error)

PodmanServiceCommand implements PodmanServicer for podman's own CLI; the docker CLI, which has no such service, refuses.

func (*CLI) Port

func (c *CLI) Port(ctx context.Context, name string, containerPort int) (int, error)

Port implements Client via `docker port`.

func (*CLI) Pull

func (c *CLI) Pull(ctx context.Context, ref string) error

Pull implements Client. podman is given the reference docker would read (qualifiedRef): its own resolution of a short name may ask which registry to use, and a run has no one to answer.

func (*CLI) RemoveForce

func (c *CLI) RemoveForce(ctx context.Context, name string) error

RemoveForce implements Client.

func (*CLI) RunDetached

func (c *CLI) RunDetached(ctx context.Context, r RunSpec) error

RunDetached implements Client.

func (*CLI) RunForeground

func (c *CLI) RunForeground(ctx context.Context, r RunSpec, stdin io.Reader, stdout, stderr io.Writer) (int, error)

RunForeground implements Client.

func (*CLI) Runtimes

func (c *CLI) Runtimes(ctx context.Context) (map[string]Runtime, error)

Runtimes implements Client from `docker info`: the daemon's runtime table keyed by name. The names are what `--runtime` accepts. podman keeps no table: its answer is its one default runtime.

func (*CLI) ServerArch

func (c *CLI) ServerArch(ctx context.Context) (string, error)

ServerArch implements Client.

podman's CLI runs the engine itself and reports it as the client ({{.Client.OsArch}}, "linux/amd64").

func (*CLI) Start

func (c *CLI) Start(ctx context.Context, name string) error

Start implements Creator.

func (*CLI) StartAttached

func (c *CLI) StartAttached(ctx context.Context, name string, interactive bool, stdin io.Reader, stdout, stderr io.Writer) (int, error)

StartAttached implements Creator: `docker start -a` (and -i for an attached stdin) streams the container's stdio and exits with its code, as `run` does, and a container created with --rm goes as it would have.

func (*CLI) Stop

func (c *CLI) Stop(ctx context.Context, name string, timeoutSeconds int) error

Stop implements Client.

func (*CLI) VolumeCreate

func (c *CLI) VolumeCreate(ctx context.Context, name string, labels map[string]string) error

VolumeCreate implements Client.

func (*CLI) VolumeRemove

func (c *CLI) VolumeRemove(ctx context.Context, name string) error

VolumeRemove implements Client.

func (*CLI) VolumesByLabel

func (c *CLI) VolumesByLabel(ctx context.Context, label string) ([]string, error)

VolumesByLabel implements Client.

type Client

type Client interface {
	// Available errors when no usable docker daemon answers.
	Available(ctx context.Context) error
	// Runtimes is the daemon's runtime table: each registered OCI runtime
	// (runc, runsc, …) by the name a policy's docker.runtime may give,
	// with the binary it runs and the arguments its registration adds.
	Runtimes(ctx context.Context) (map[string]Runtime, error)
	// ContainerIP is a running container's address on one network.
	ContainerIP(ctx context.Context, name, network string) (string, error)
	// ServerArch is the daemon's architecture as Go names it (amd64,
	// arm64): the platform an image built here runs on.
	ServerArch(ctx context.Context) (string, error)
	// ImageExists reports whether ref is present locally.
	ImageExists(ctx context.Context, ref string) (bool, error)
	// ImageLabel is a present image's label key, "" when it has none.
	ImageLabel(ctx context.Context, ref, key string) (string, error)
	// ImageFile reads one file out of an image without running it (a
	// stopped container is created, copied from, removed).
	ImageFile(ctx context.Context, ref, path string) ([]byte, error)
	// Pull pulls ref (first-use install of pinned images).
	Pull(ctx context.Context, ref string) error
	// Build builds dir into tag with the given build args.
	Build(ctx context.Context, dir, tag string, buildArgs map[string]string) error
	// NetworkCreate creates a bridge network; internal networks have no
	// route out.
	NetworkCreate(ctx context.Context, name string, internal bool, labels map[string]string) error
	// NetworkConnect attaches an existing container to another network.
	NetworkConnect(ctx context.Context, network, container string) error
	// NetworkRemove removes a network.
	NetworkRemove(ctx context.Context, name string) error
	// NetworksByLabel lists the names of the networks carrying label
	// ("k=v", or "k" for any value), for the sweep of a dead run's
	// networks whose names its run id alone does not determine.
	NetworksByLabel(ctx context.Context, label string) ([]string, error)
	// VolumeCreate creates a named volume with labels; VolumeRemove
	// removes one (absent is not an error); VolumesByLabel lists the
	// names carrying a label, for the run's teardown sweep.
	VolumeCreate(ctx context.Context, name string, labels map[string]string) error
	VolumeRemove(ctx context.Context, name string) error
	VolumesByLabel(ctx context.Context, label string) ([]string, error)
	// RunDetached starts a container in the background.
	RunDetached(ctx context.Context, r RunSpec) error
	// RunForeground runs a container to completion, streaming stdio, and
	// returns its exit code. A non-zero container exit is NOT an error —
	// the (code, nil) pair is the normal shape; err means docker itself
	// failed.
	RunForeground(ctx context.Context, r RunSpec, stdin io.Reader, stdout, stderr io.Writer) (int, error)
	// Stop gracefully stops a container (SIGTERM, then kill after
	// timeout). Not-found is not an error.
	Stop(ctx context.Context, name string, timeoutSeconds int) error
	// RemoveForce force-removes a container and its anonymous volumes;
	// not-found is not an error.
	RemoveForce(ctx context.Context, name string) error
	// PSByLabel lists container names carrying label (leak sweeps).
	PSByLabel(ctx context.Context, label string) ([]string, error)
	// PSLabels lists every container (running or not) carrying label, each
	// with the values of the label keys asked for ("" where it has none):
	// the startup sweep reads who created a container before removing it.
	PSLabels(ctx context.Context, label string, keys []string) ([]Labeled, error)
	// Logs returns a container's output: the last tail lines, or all of
	// it for LogsAll (gateway diagnostics and startup checks).
	Logs(ctx context.Context, name string, tail int) (string, error)
	// Port returns the host port a container port was published on
	// (RunSpec.Publish), for a host-run harness to reach the run.
	Port(ctx context.Context, name string, containerPort int) (int, error)
}

Client is what the engine talks to.

type Creator

type Creator interface {
	// Create creates r's container without starting it, as `docker
	// create` does: everything RunDetached and RunForeground would pass to
	// `run`, the attached stdin included, so Start and StartAttached find
	// the container ready. r.Name is required.
	Create(ctx context.Context, r RunSpec) error
	// Start starts a created container in the background.
	Start(ctx context.Context, name string) error
	// StartAttached starts a created container with its stdio attached and
	// returns its exit code, as RunForeground does; interactive says stdin
	// is attached.
	StartAttached(ctx context.Context, name string, interactive bool, stdin io.Reader, stdout, stderr io.Writer) (int, error)
	// ContainerRuntime is the OCI runtime the engine created a container
	// with, by the name the engine registers it under: docker's
	// HostConfig.Runtime, podman's OCIRuntime.
	ContainerRuntime(ctx context.Context, name string) (string, error)
}

Creator splits a run into its two halves and reads a container's runtime between them: an optional capability of a Client, asked for with a type assertion as Execer is, so a Client that lacks it still satisfies Client. The CLI client has it, and so does Fake.

type CredentialHelperGap

type CredentialHelperGap struct {
	// Config is the file that names it.
	Config string
	// Helper is the entry's value, Program the binary it names.
	Helper  string
	Program string
	// Store says the entry is credsStore, which covers every registry;
	// otherwise Registry is the credHelpers key it covers.
	Store    bool
	Registry string
}

CredentialHelperGap is a credential helper the docker configuration names and PATH lacks: the docker CLI runs docker-credential-<Helper> for every pull the entry covers and fails the pull when it is not found.

func MissingCredentialHelpers

func MissingCredentialHelpers(path string, lookPath func(string) (string, error)) []CredentialHelperGap

MissingCredentialHelpers reads the docker configuration at path for credsStore and credHelpers entries whose docker-credential-<name> program lookPath cannot find (exec.LookPath when nil). A file that is absent or not JSON names nothing. The gaps come sorted, the store's first, one per helper: a registry entry naming the store's own missing helper adds nothing.

type Engine

type Engine struct {
	// Kind is KindDocker (a server component named "Engine") or KindPodman
	// ("Podman Engine", or podman's own CLI).
	Kind string
	// CLI is the client binary family driven: "docker" or "podman".
	CLI string
	// Version is the daemon's version.
	Version string
	// Endpoint is where the client's requests go, as the client resolves
	// it: unix:///path, npipe://…, tcp://…, ssh://….
	Endpoint string
	// Rootless says the daemon runs as the person, not as root.
	Rootless bool
	// DaemonHost and DaemonKernel are the hostname and kernel release the
	// daemon reports: this machine's for a local daemon, a VM's otherwise.
	DaemonHost   string
	DaemonKernel string
	// OS is what the daemon says it runs on ("Docker Desktop", a
	// distribution's name).
	OS string
}

Engine is what a run needs to know of the container engine behind a client: where the client sends its requests, what answers there, and whether that daemon shares this machine's kernel. A run reads it once and the CLI keeps it for the life of the process.

func DescribeEngine

func DescribeEngine(ctx context.Context, d Client) (Engine, error)

DescribeEngine is d's engine, or the default for a client that cannot say.

func LocalDockerEngine

func LocalDockerEngine() Engine

LocalDockerEngine is Docker Engine on its conventional socket, run by root on this machine.

func (Engine) PersonIDs

func (e Engine) PersonIDs() (uid, gid int, ok bool)

PersonIDs are the uid and gid that, inside a container on e, are the person who runs the CLI: their own on a rootful engine, root's on a rootless one, where the engine maps the person to the container's root and every other id to a subordinate one. A file a container hands to these ids is the person's to remove. ok is false on a host without POSIX ids.

func (Engine) PersonUser

func (e Engine) PersonUser() string

PersonUser is PersonUser for an engine already described: the person's own uid:gid, or root on a rootless engine.

func (Engine) SandboxUnlabelled

func (e Engine) SandboxUnlabelled(runtime string) bool

SandboxUnlabelled says whether a container under runtime on engine e must be created with its SELinux label disabled: on podman on an SELinux host, where gVisor refuses to start a labelled container ("SELinux is not supported"). The runtime's own isolation stands in for the label's; the receipt says so. Docker Engine labels nothing under gVisor itself, and a host without SELinux has no label to disable.

func (Engine) SocketPath

func (e Engine) SocketPath() string

SocketPath is the Unix socket the endpoint names, "" when it names something else.

func (Engine) Summary

func (e Engine) Summary() string

Summary is the engine in one phrase: its kind and version, the CLI when it is not the engine's own, and whether it runs as root.

type EngineDescriber

type EngineDescriber interface {
	Engine(ctx context.Context) (Engine, error)
}

EngineDescriber is the client's account of its engine (Engine): an optional capability asked for with a type assertion, like Execer. A client without it is taken to be Docker Engine on the conventional socket on this machine.

type Execer

type Execer interface {
	// ExecStream runs argv in container as the container's user and
	// returns its exit code. A non-zero exit is not an error; err means
	// docker itself failed. stderr is discarded.
	ExecStream(ctx context.Context, container string, argv []string, stdin io.Reader, stdout io.Writer) (int, error)
}

Execer runs a command in a running container with its stdin and stdout streamed, the way `docker exec -i` does: an optional capability of a Client, asked for with a type assertion so a Client that lacks it (a test's own, another program's) still satisfies Client. The CLI client has it, and so does Fake.

type Fake

type Fake struct {
	Calls []FakeCall

	// AvailableErr fails Available.
	AvailableErr error
	// Exec, when set, answers ExecStream (Execer) for a running
	// container: the test plays the command's side of its stdio.
	Exec func(ctx context.Context, container string, argv []string, stdin io.Reader, stdout io.Writer) (int, error)
	// RuntimeNames is what Runtimes answers when RuntimeTable is nil, each
	// name with an empty registration; nil answers the daemon's usual pair
	// ("io.containerd.runc.v2", "runc").
	RuntimeNames []string
	// RuntimeTable, when set, is what Runtimes answers, each name with
	// its binary and arguments: what a gateway registration is checked
	// against.
	RuntimeTable map[string]Runtime
	// RuntimesErr fails Runtimes.
	RuntimesErr error
	// IPs answers ContainerIP by container name; a name with no entry gets
	// a made-up address, so a test need not script every container.
	IPs map[string]string
	// ExistingImages marks refs ImageExists reports true for.
	ExistingImages map[string]bool
	// Labels answers ImageLabel by ref, then key.
	Labels map[string]map[string]string
	// Arch is what ServerArch answers; "" answers amd64.
	Arch string
	// ImageFiles answers ImageFile by "ref:path"; a missing entry is an error.
	ImageFiles map[string]string
	// BuildArgs records the build args of the last Build of each tag.
	BuildArgs map[string]map[string]string
	// FailPull/FailBuild/FailDetached script failures by ref/name.
	FailPull     map[string]error
	FailBuild    map[string]error
	FailDetached map[string]error
	// Foreground scripts RunForeground behavior keyed by container name
	// prefix; nil behavior = exit 0, no output.
	Foreground map[string]*FakeForeground
	// LogsByName scripts Logs.
	LogsByName map[string]string
	// Ports answers Port by "name:port" or by container name; a published container with
	// no entry gets 41000 + its container port modulo 1000.
	Ports map[string]int
	// PortFailures makes that many Port calls fail before one succeeds.
	PortFailures int
	// Leftover names PSByLabel returns (leak-check tests); LeftoverVolumes
	// what VolumesByLabel returns.
	Leftover        []string
	LeftoverVolumes []string
	// ByLabel, when it has the label, is what PSByLabel answers for it
	// instead of Leftover.
	ByLabel map[string][]string
	// Containers is what PSLabels lists: each is returned when it carries
	// the asked label ("k=v", or "k" for any value), with the asked keys.
	Containers []Labeled
	// Networks is the docker host's networks with their labels:
	// NetworkCreate adds one, NetworkRemove takes it away, and
	// NetworksByLabel lists them as PSLabels lists Containers.
	Networks []Labeled
	// Volumes is the docker host's labelled volumes: VolumeCreate with
	// labels adds one, VolumeRemove takes it away, and VolumesByLabel lists
	// them beside LeftoverVolumes.
	Volumes []Labeled
	// OnDetached, when set, runs with the spec of every detached container
	// as it starts — how a test gives a container side effects, such as
	// the relays a gateway creates.
	OnDetached func(r RunSpec)
	// OnForeground, when set, runs with the spec of every foreground
	// container as it starts — how a test makes something happen once the
	// agent is running, such as a relay the gateway starts late.
	OnForeground func(r RunSpec)
	// OnRemoveForce, when set, runs with the name of every container
	// RemoveForce is given — how a test ends a foreground container that
	// only a removal stops.
	OnRemoveForce func(name string)
	// EngineInfo, when set, is what Engine answers; nil answers
	// LocalDockerEngine. EngineErr fails Engine.
	EngineInfo *Engine
	EngineErr  error
	// DropRuntime makes ContainerRuntime answer DroppedRuntime for every
	// container, whatever its spec asked for: an engine that takes a
	// runtime and does not apply it. "" is the engine's default.
	DropRuntime    bool
	DroppedRuntime string
	// PodmanService, when set, answers PodmanServiceCommand (PodmanServicer)
	// with the command a test wants run as the run's podman API service;
	// nil says this client has none.
	PodmanService func(runtime, socket string) *exec.Cmd
	// contains filtered or unexported fields
}

Fake implements Client.

func (*Fake) Available

func (f *Fake) Available(context.Context) error

Available implements Client.

func (*Fake) Build

func (f *Fake) Build(_ context.Context, dir, tag string, args map[string]string) error

Build implements Client.

func (*Fake) CheckRuntime

func (f *Fake) CheckRuntime(ctx context.Context, name string) (Runtime, error)

CheckRuntime implements RuntimeChecker for Fake, from its table.

func (*Fake) ContainerIP

func (f *Fake) ContainerIP(_ context.Context, name, network string) (string, error)

ContainerIP implements Client from IPs.

func (*Fake) ContainerRuntime

func (f *Fake) ContainerRuntime(_ context.Context, name string) (string, error)

ContainerRuntime implements Creator for Fake: the runtime the created spec asked for, or DroppedRuntime for every container when DropRuntime is set, the way an engine that ignores the request answers.

func (*Fake) Create

func (f *Fake) Create(_ context.Context, r RunSpec) error

Create implements Creator for Fake: recorded as "Create", the spec kept for Start, StartAttached and ContainerRuntime.

func (*Fake) Engine

func (f *Fake) Engine(context.Context) (Engine, error)

Engine implements EngineDescriber. It is not recorded: a run reads it before it touches the daemon, and the call sequences tests assert are the daemon's.

func (*Fake) ExecStream

func (f *Fake) ExecStream(ctx context.Context, container string, argv []string, stdin io.Reader, stdout io.Writer) (int, error)

ExecStream implements Execer: Exec answers it, recorded as "ExecStream:<container>"; with no Exec it reads stdin to its end and exits 0.

func (*Fake) FindRun

func (f *Fake) FindRun(substr string) (RunSpec, bool)

FindRun returns the first Run* or Create call whose name contains substr: a container checked for its runtime is created, then started.

func (*Fake) ImageExists

func (f *Fake) ImageExists(_ context.Context, ref string) (bool, error)

ImageExists implements Client.

func (*Fake) ImageFile

func (f *Fake) ImageFile(_ context.Context, ref, path string) ([]byte, error)

ImageFile implements Client from ImageFiles.

func (*Fake) ImageLabel

func (f *Fake) ImageLabel(_ context.Context, ref, key string) (string, error)

ImageLabel implements Client from Labels.

func (*Fake) Logs

func (f *Fake) Logs(_ context.Context, name string, _ int) (string, error)

Logs implements Client.

func (*Fake) NetworkConnect

func (f *Fake) NetworkConnect(_ context.Context, network, container string) error

NetworkConnect implements Client.

func (*Fake) NetworkCreate

func (f *Fake) NetworkCreate(_ context.Context, name string, internal bool, labels map[string]string) error

NetworkCreate implements Client.

func (*Fake) NetworkRemove

func (f *Fake) NetworkRemove(_ context.Context, name string) error

NetworkRemove implements Client.

func (*Fake) NetworkState

func (f *Fake) NetworkState() []Labeled

NetworkState is a copy of the networks the fake holds now, each with its labels.

func (*Fake) NetworksByLabel

func (f *Fake) NetworksByLabel(_ context.Context, label string) ([]string, error)

NetworksByLabel implements Client.

func (*Fake) Ops

func (f *Fake) Ops() []string

Ops lists recorded operation names in order, "Op:Arg" formatted.

func (*Fake) PSByLabel

func (f *Fake) PSByLabel(_ context.Context, label string) ([]string, error)

PSByLabel implements Client.

func (*Fake) PSLabels

func (f *Fake) PSLabels(_ context.Context, label string, keys []string) ([]Labeled, error)

PSLabels implements Client.

func (*Fake) PodmanServiceCommand

func (f *Fake) PodmanServiceCommand(_ context.Context, runtime, socket string) (*exec.Cmd, error)

PodmanServiceCommand implements PodmanServicer for Fake.

func (*Fake) Port

func (f *Fake) Port(_ context.Context, name string, containerPort int) (int, error)

Port implements Client.

func (*Fake) Pull

func (f *Fake) Pull(_ context.Context, ref string) error

Pull implements Client.

func (*Fake) RemoveForce

func (f *Fake) RemoveForce(_ context.Context, name string) error

RemoveForce implements Client.

func (*Fake) RunDetached

func (f *Fake) RunDetached(_ context.Context, r RunSpec) error

RunDetached implements Client.

func (*Fake) RunForeground

func (f *Fake) RunForeground(ctx context.Context, r RunSpec, stdin io.Reader, stdout, stderr io.Writer) (int, error)

RunForeground implements Client.

func (*Fake) Runtimes

func (f *Fake) Runtimes(context.Context) (map[string]Runtime, error)

Runtimes implements Client from RuntimeTable, else RuntimeNames.

func (*Fake) ServerArch

func (f *Fake) ServerArch(context.Context) (string, error)

ServerArch implements Client from Arch.

func (*Fake) Start

func (f *Fake) Start(_ context.Context, name string) error

Start implements Creator for Fake: recorded as "Start", with OnDetached run for the created spec as RunDetached would.

func (*Fake) StartAttached

func (f *Fake) StartAttached(ctx context.Context, name string, _ bool, stdin io.Reader, stdout, stderr io.Writer) (int, error)

StartAttached implements Creator for Fake: recorded as "StartAttached", then played as RunForeground plays the created spec.

func (*Fake) Stop

func (f *Fake) Stop(_ context.Context, name string, _ int) error

Stop implements Client.

func (*Fake) VolumeCreate

func (f *Fake) VolumeCreate(_ context.Context, name string, labels map[string]string) error

VolumeCreate implements Client. A labelled volume is kept in Volumes.

func (*Fake) VolumeRemove

func (f *Fake) VolumeRemove(_ context.Context, name string) error

VolumeRemove implements Client.

func (*Fake) VolumesByLabel

func (f *Fake) VolumesByLabel(_ context.Context, label string) ([]string, error)

VolumesByLabel implements Client: LeftoverVolumes, and the Volumes that carry the label.

type FakeCall

type FakeCall struct {
	// Op is the method name (e.g. "RunDetached").
	Op string
	// Arg is the primary argument (image ref, network or container name).
	Arg string
	// Run is the RunSpec for Run* ops.
	Run RunSpec
}

FakeCall is one recorded client call.

type FakeForeground

type FakeForeground struct {
	// Stdout is written to the caller's stdout writer, Stderr to its
	// stderr writer.
	Stdout string
	Stderr string
	// WantStdin, when set, asserts what the container received on stdin
	// (recorded into GotStdin for the test to inspect).
	GotStdin string
	// ExitCode is returned.
	ExitCode int
	// Err is returned as a docker-level failure.
	Err error
	// Block, when set, waits for ctx cancellation and then returns
	// (exit 137) — how tests exercise timeout/budget kills.
	Block bool
	// Before, when set, runs with the spec before the scripted result is
	// produced — how tests leave files in a mounted directory the way a
	// real builder would.
	Before func(r RunSpec)
	// Print, when set, runs after Before and its answer is written to the
	// caller's stdout ahead of Stdout: what a container prints of the work
	// Before played.
	Print func(r RunSpec) string
	// Handler, when set, plays the container itself on the attached
	// streams (an interactive harness for session tests); the scripted
	// fields above are ignored.
	Handler func(ctx context.Context, r RunSpec, stdin io.Reader, stdout, stderr io.Writer) (int, error)
}

FakeForeground scripts one foreground container.

type HostSocket

type HostSocket struct {
	Name string
	Path string
}

HostSocket is one place an engine on this machine serves the Docker API over a Unix socket, named for the engine that puts it there.

func HostSockets

func HostSockets() []HostSocket

HostSockets lists where each engine puts its socket on this machine: Docker Engine's own and Docker Desktop's, the VM engines' host sockets on macOS (Colima's and Lima's per profile or instance, OrbStack's, Rancher Desktop's dockerd, each podman machine's), podman's own on Linux. A path is listed whether or not it exists. Windows engines serve named pipes, which the docker CLI's own context reaches, so nothing is listed there.

type Labeled

type Labeled struct {
	Name   string
	Labels map[string]string
}

Labeled is one container PSLabels found, with the label values it read.

type LeftSocket

type LeftSocket struct {
	HostSocket
	Err error
}

LeftSocket is a socket file with nothing answering behind it: the engine that put it there has stopped, or was removed and left it.

func LeftSockets

func LeftSockets(ctx context.Context, sockets []HostSocket) []LeftSocket

LeftSockets pings each socket of sockets that exists as a file and returns those that do not answer the Docker API's /_ping, in order. An absent file is nothing; a socket that answers is an engine, not a leftover. Paths are not repeated.

func (LeftSocket) Message

func (s LeftSocket) Message() string

Message says what the socket is and what to do about it. Rancher Desktop keeps its socket file when it runs its containerd backend, which serves no Docker API, so that one is named from Rancher's own settings rather than taken for a stopped engine.

type Mount

type Mount struct {
	Source   string
	Target   string
	ReadOnly bool
	// Relabel asks docker to give the source an SELinux label the container can
	// read (the `z` option). Set it for directories THIS RUN created and
	// nothing else: relabeling is a write to the host's file labels, so
	// pointing it at a path that belongs to the machine — the docker socket
	// above all — would change what every other container on that host may
	// touch. On a daemon built without SELinux support docker accepts the
	// option and ignores it (the source's label is untouched), so it costs
	// nothing to carry.
	Relabel bool
}

Mount is one bind mount, already placeholder-resolved.

type PodmanServicer

type PodmanServicer interface {
	// PodmanServiceCommand is the command that serves the API on the Unix
	// socket at path with runtime as its default, until stopped; it is not
	// started.
	PodmanServiceCommand(ctx context.Context, runtime, path string) (*exec.Cmd, error)
}

PodmanServicer starts a Docker-compatible API service of podman's own whose default runtime is the one named: an optional capability of a Client that drives podman's CLI. Every container created through such a service's socket lands under that runtime, whatever its create body says, which is how a run's gateway puts the containers it launches under the policy's runtime on podman.

type PortPublish

type PortPublish struct {
	HostIP        string
	HostPort      int
	ContainerPort int
}

PortPublish is one -p mapping.

type RunSpec

type RunSpec struct {
	Name  string
	Image string
	// Argv follows the image (entrypoint args).
	Argv []string
	// Env is passed by NAME through the docker client's environment
	// (`-e NAME` + cmd.Env), never as `-e NAME=value` argv — values (the
	// gateway token, the model key) must not appear in process listings.
	// The exception is a name the docker client reads itself (clientReads:
	// HOME, PATH, USERPROFILE, DOCKER_*): set in the client's environment
	// it would reconfigure the client, so it goes as `-e NAME=value` and
	// must never carry a secret.
	Env map[string]string
	// Mounts are bind mounts.
	Mounts []Mount
	// Volumes are anonymous volumes mounted at these paths, each with its
	// own labels (`--mount type=volume,dst=…,volume-label=k=v`), in place
	// of the unlabelled anonymous volume an image's VOLUME would otherwise
	// get. Like any anonymous volume they go with their
	// container (RemoveForce passes -v); the labels let teardown and the
	// sweeps find one whose container went some other way.
	Volumes []VolumeMount
	// Network and Alias attach the container to the run network.
	Network string
	Alias   string
	// ExtraNetworks are the container's other networks, joined at create rather
	// than by a connect after start: a sandboxed runtime's network stack takes
	// no network connected once it runs (as under gVisor), and docker refuses
	// the default bridge beside a user-defined network at create, so each is
	// user-defined. Alias, if any, is Network's alone.
	ExtraNetworks []string
	// Hostname sets the container's hostname when it must differ from
	// the container name (the gateway looks itself up by hostname).
	Hostname string
	// Labels tag the container for teardown sweeps.
	Labels map[string]string
	// User runs the container's process as this uid:gid (`--user`), for a
	// container that writes into a directory the invoking user owns and
	// must be able to remove afterwards (the MCP server installer).
	// Empty leaves the image's own user.
	User string
	// Runtime names the daemon's OCI runtime for this container
	// (`--runtime`): a policy's docker.runtime, so the container that runs
	// the QuickAgent's code can sit behind gVisor on a host that has it.
	// Empty leaves the daemon's default.
	Runtime string
	// ExtraHosts pins names to addresses in the container's /etc/hosts
	// (`--add-host name:ip`). A sandboxed runtime's network stack does not
	// reach docker's embedded DNS, so the run network's aliases travel
	// this way when a runtime is set.
	ExtraHosts []string
	// Entrypoint replaces the image's entrypoint (`--entrypoint`): for a
	// one-shot that borrows an image for a shell command, such as the
	// session store's ownership step. Empty keeps it.
	Entrypoint string
	// Interactive attaches stdin (foreground runs).
	Interactive bool
	// AutoRemove passes --rm; teardown still force-removes by name in
	// case the client process died before docker could reap.
	AutoRemove bool
	// NoLog keeps no log of the container's output (`--log-driver none`):
	// for a container whose stdout is data its attached caller reads (the
	// MCP server installer's archive). The engine would otherwise also write
	// every byte to the container's log, which json-file does as escaped
	// JSON lines, many times slower than the stream itself.
	NoLog bool
	// Publish exposes container ports on the host (-p): only for a
	// host-run harness, and only on 127.0.0.1 (HostPort 0 = ephemeral).
	Publish []PortPublish
	// DisableSELinuxLabel runs this container with SELinux labelling off
	// (`--security-opt label=disable`). It is for the ONE container that
	// drives the host's docker daemon: an SELinux-enabled daemon confines
	// container processes so they cannot open the docker socket at all, and
	// the alternative — relabeling the socket itself — would hand that
	// access to every container on the machine instead of this one.
	// Every other container in a run stays confined. On a
	// daemon built without SELinux support the option is accepted and does
	// nothing.
	DisableSELinuxLabel bool
	// CapDrop and CapAdd are the container's capabilities (`--cap-drop`,
	// `--cap-add`); NoNewPrivileges sets `--security-opt no-new-privileges`;
	// ReadOnly makes the root filesystem read-only with Tmpfs as its writable
	// scratch; PidsLimit, Memory and CPUs are its resource bounds. Zero values
	// leave docker's defaults.
	CapDrop         []string
	CapAdd          []string
	NoNewPrivileges bool
	// SeccompProfile is a seccomp profile file for the container
	// (`--security-opt seccomp=<file>`): the browser's, which lets
	// Chromium's own sandbox make its namespaces under runc. Empty keeps
	// the daemon's default profile.
	SeccompProfile string
	ReadOnly       bool
	Tmpfs          []string
	PidsLimit      int
	Memory         string
	CPUs           int
}

RunSpec describes one docker run.

func (RunSpec) WithPosture

func (r RunSpec) WithPosture(memory string, cpus, pids int) RunSpec

WithPosture is r with the posture every run container takes: every capability dropped, no privilege gained through a setuid binary, and memory, CPUs and processes bounded. A container that needs one capability back adds it to CapAdd afterwards.

type Runtime

type Runtime struct {
	Path string   `json:"path"`
	Args []string `json:"runtimeArgs"`
}

Runtime is one entry of the daemon's runtime table: the binary it runs and the arguments its registration adds (daemon.json's runtimes).

type RuntimeChecker

type RuntimeChecker interface {
	// CheckRuntime is the registration behind name, or why there is none.
	CheckRuntime(ctx context.Context, name string) (Runtime, error)
}

RuntimeChecker verifies one OCI runtime by the name a policy gives it: an optional capability of a Client, asked for with a type assertion. On podman the name is tried (`podman --runtime <name> info`), since podman's configuration lists every runtime it names, installed or not; on docker the daemon's table is read.

type RuntimeMismatch

type RuntimeMismatch struct {
	// Class is the container's role in the run, in the receipt's words.
	Class string
	// Name is the container, Want the policy's runtime and Got the one the
	// engine created it with.
	Name, Want, Got string
}

RuntimeMismatch is why a run stopped: a container that had to run under the policy's runtime was created under another, and the engine did not apply the runtime it was asked for.

func (*RuntimeMismatch) Error

func (e *RuntimeMismatch) Error() string

type Unreachable added in v0.6.1013

type Unreachable struct {
	// CLI is the client asked: "docker" or "podman".
	CLI string
	// Endpoint is where the client's requests went, as it resolves them
	// (unix:///path, npipe://…, tcp://…), "" when it could not say.
	Endpoint string
	// Engine names what the endpoint belongs to, when the machine's layout
	// says: Docker Desktop, Docker Engine, Colima, OrbStack, Rancher
	// Desktop, Lima, podman, podman machine. "" when it does not.
	Engine string
	// Remedy is how to start it, one clause.
	Remedy string
	// Denied says the engine answers but this user may not use its socket.
	Denied bool
	// Err is the client's own error.
	Err error
}

Unreachable is the error a client returns when its CLI is installed and no engine answers it. Its text is one sentence for a person: which engine this machine seems to have, read from where the client's requests go, and how to start it. The client's own error, with what the command printed, is kept beneath it for a verbose reading.

func (*Unreachable) Detail added in v0.6.1013

func (u *Unreachable) Detail() string

Detail is the client's own error: what the command said.

func (*Unreachable) Error added in v0.6.1013

func (u *Unreachable) Error() string

func (*Unreachable) Problem added in v0.6.1013

func (u *Unreachable) Problem() string

Problem is the sentence's first half: what is wrong, without the remedy.

func (*Unreachable) Unwrap added in v0.6.1013

func (u *Unreachable) Unwrap() error

type VolumeMount

type VolumeMount struct {
	Target string
	Labels map[string]string
}

VolumeMount is an anonymous volume at Target carrying Labels.

Jump to

Keyboard shortcuts

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