Documentation
¶
Overview ¶
Package runtime is the container runtime driver (Section 3.1): a small client for the Docker Engine API, which Docker Engine and Podman (its Docker-compatible socket) both serve. It creates, labels, starts, stops and reclaims the node and PostgreSQL containers the emulator runs, plus the networks and volumes they use.
Index ¶
- Constants
- Variables
- func CPUSetProblem(in Info, goos string) (problem, fix string)
- func InContainer() bool
- func IsAddressInUse(err error) bool
- func IsAlreadyExists(err error) bool
- func Locate() (*Client, Detection, error)
- func MayBeContainerized(setting string, markers bool) bool
- type AliasDecision
- type Attachment
- type Client
- func (c *Client) AddrHolder(ctx context.Context, network, ip string) (Container, bool, error)
- func (c *Client) ArchiveFrom(ctx context.Context, id, p string, w io.Writer) error
- func (c *Client) ArchiveTo(ctx context.Context, id, dir string, r io.Reader) error
- func (c *Client) AttachMember(ctx context.Context, network string, reserved bool) error
- func (c *Client) AttachSelf(ctx context.Context, network string) error
- func (c *Client) Connect(ctx context.Context, network, container, ip string, aliases ...string) error
- func (c *Client) CopyFrom(ctx context.Context, id, file string) ([]byte, error)
- func (c *Client) CopyTo(ctx context.Context, id, dir string, files []File) error
- func (c *Client) CreateContainer(ctx context.Context, s ContainerSpec) (string, error)
- func (c *Client) CreateNetwork(ctx context.Context, s NetworkSpec) (string, error)
- func (c *Client) CreateVolume(ctx context.Context, name string, labels map[string]string) error
- func (c *Client) Disconnect(ctx context.Context, network, container string) error
- func (c *Client) Disrupted(ctx context.Context, cts []Container) []string
- func (c *Client) EnsureImage(ctx context.Context, ref string, offline bool) error
- func (c *Client) Exec(ctx context.Context, id string, cmd []string, stdin []byte) (ExecResult, error)
- func (c *Client) FollowLogs(ctx context.Context, id string) (io.ReadCloser, error)
- func (c *Client) ForgetStart(id string)
- func (c *Client) ImageExists(ctx context.Context, ref string) (bool, error)
- func (c *Client) ImageFile(ctx context.Context, ref, platform, file string) ([]byte, error)
- func (c *Client) Info(ctx context.Context) (Info, error)
- func (c *Client) InspectContainer(ctx context.Context, id string) (Container, error)
- func (c *Client) InspectNetwork(ctx context.Context, name string) (Network, error)
- func (c *Client) ListContainers(ctx context.Context, labels map[string]string) ([]Container, error)
- func (c *Client) ListNetworks(ctx context.Context, labels map[string]string) ([]Network, error)
- func (c *Client) ListVolumes(ctx context.Context, labels map[string]string) ([]string, error)
- func (c *Client) Logs(ctx context.Context, id string, tail int) (string, error)
- func (c *Client) NetworkAddrs(ctx context.Context, network string) (map[string]bool, error)
- func (c *Client) PauseContainer(ctx context.Context, id string) error
- func (c *Client) RemoveContainer(ctx context.Context, id string, force bool) error
- func (c *Client) RemoveNetwork(ctx context.Context, name string) error
- func (c *Client) RemoveVolume(ctx context.Context, name string) error
- func (c *Client) RestartContainer(ctx context.Context, id string, timeout time.Duration) error
- func (c *Client) SaveImages(ctx context.Context, refs []string, w io.Writer) error
- func (c *Client) Self() string
- func (c *Client) SelfFound() bool
- func (c *Client) SelfIP(ctx context.Context, network string) (string, error)
- func (c *Client) SelfPorts(ctx context.Context) (map[int]string, error)
- func (c *Client) SetMember(container string, joined func(n Network, in bool))
- func (c *Client) SetMemberAddr(addr func(network string) string)
- func (c *Client) SetReserved(reserved func() []string)
- func (c *Client) StartContainer(ctx context.Context, id string) error
- func (c *Client) StopContainer(ctx context.Context, id string, timeout time.Duration) error
- func (c *Client) UnpauseContainer(ctx context.Context, id string) error
- func (c *Client) Volumes(ctx context.Context, labels map[string]string) ([]Volume, error)
- func (c *Client) WaitContainer(ctx context.Context, id string) (int, error)
- type Container
- type ContainerSpec
- type ContainerizedDecision
- type ContainerizedFacts
- type Detection
- type ExecResult
- type File
- type Info
- type Manager
- func (m *Manager) AgentBinary(ctx context.Context) (string, error)
- func (m *Manager) Cleanup(ctx context.Context, all bool) error
- func (m *Manager) Connect(ctx context.Context, network, container, ip string, aliases ...string) error
- func (m *Manager) CreateContainer(ctx context.Context, s ContainerSpec) (string, error)
- func (m *Manager) Labels(service, resource, role string) map[string]string
- func (m *Manager) LogTail(ctx context.Context, ct Container, n int) string
- func (m *Manager) Name(parts ...string) string
- func (m *Manager) Reclaim(ctx context.Context) error
- func (m *Manager) WaitRunning(ctx context.Context, id string) error
- type Mount
- type Network
- type NetworkSpec
- type Port
- type VMDecision
- type Volume
Constants ¶
const ( LabelInstance = "gcpemu.instance" // instance ID LabelService = "gcpemu.service" // owning service, e.g. "sql" LabelResource = "gcpemu.resource" // owning resource name LabelRole = "gcpemu.role" // e.g. "server", "node", "nat" LabelDir = "gcpemu.dir" // absolute data dir of the instance // LabelHostLB is on a GKE cluster's server container that runs // without servicelb, and says why: HostLBRelay, HostLBTranslated or // HostLBVM. `gcpemu doctor` reads it (ADR 0012). LabelHostLB = "gcpemu.hostlb" )
Labels applied to everything the emulator creates.
const ( HostLBRelay = "vm-relay" HostLBTranslated = "translated" HostLBVM = "vm-runtime" )
LabelHostLB values.
const ContainerizedEnv = "GCPEMU_CONTAINERIZED"
ContainerizedEnv names the setting: "auto" (the default), "true" or "false".
const LoopbackAliasesEnv = "GCPEMU_LOOPBACK_ALIASES"
LoopbackAliasesEnv names the setting for loopback aliases: "auto" (the default), "true" or "false".
const RoleVPC = "vpc"
RoleVPC is the LabelRole of a VPC container network (a subnetwork's or a private services access allocation's), whose second-to-last address the NAT egress proxy holds.
const SelfEnv = "GCPEMU_SELF_CONTAINER"
SelfEnv names the emulator's own container explicitly.
const VMRuntimeEnv = "GCPEMU_VM_RUNTIME"
VMRuntimeEnv names the setting: "auto" (the default), "true" or "false".
Variables ¶
var ErrNotFound = errors.New("runtime: not found")
ErrNotFound is returned when a container, network, volume or image is absent.
var ErrWindowsContainers = errors.New("this runtime serves Windows containers; switch Docker Desktop to Linux containers")
ErrWindowsContainers is why a runtime serving Windows containers, not Linux ones, cannot be used.
Functions ¶
func CPUSetProblem ¶ added in v0.12.0
CPUSetProblem says why GKE nodes cannot start on a runtime whose containers lack the cpuset cgroup controller (Info.NoCPUSet), and the fix for a host of goos (#632): a rootful Podman machine, or cpuset delegated to the user on rootless Linux. Both are "" when the runtime has the controller or did not say. On Linux a Podman runtime may still be a machine, gcpemu running in a container on it, so both fixes are given.
func InContainer ¶ added in v0.6.0
func InContainer() bool
InContainer reports, without asking the runtime, whether the emulator may run in a container: GCPEMU_SELF_CONTAINER is set, or the container marker files exist.
func IsAddressInUse ¶ added in v0.12.0
IsAddressInUse reports a start refused because an address is taken. The runtime says "Address already in use" both for a container's fixed address on a network and for a published host port.
func IsAlreadyExists ¶ added in v0.10.0
IsAlreadyExists reports a runtime conflict (HTTP 409 or "already exists"), such as creating a network whose name is taken.
func Locate ¶ added in v0.6.0
Locate finds a runtime. It tries $DOCKER_HOST, then the Docker context ($DOCKER_CONTEXT, else currentContext in config.json), then a fixed list of endpoints: sockets (Docker Desktop, OrbStack, Colima, Podman machine, Linux), or on Windows named pipes (Docker Desktop, Docker Engine, Podman machine). An explicit choice ($DOCKER_HOST, or a context other than "default") that does not respond, or serves Windows containers, is an error naming it, so gcpemu and `docker` agree. A listed endpoint serving Windows containers is skipped.
func MayBeContainerized ¶ added in v0.10.0
MayBeContainerized reports whether the Instance may be a Containerized Instance, given setting and the marker files: only then does asking the runtime matter.
Types ¶
type AliasDecision ¶ added in v0.9.0
AliasDecision says whether a Containerized Instance on a VM runtime publishes Cloud SQL instances on 127.0.0.2-127.0.0.254, or only on 127.0.0.1, and why (ADR 0012).
func DecideLoopbackAliases ¶ added in v0.9.0
func DecideLoopbackAliases(setting string, info Info) AliasDecision
DecideLoopbackAliases chooses for a Containerized Instance on a VM runtime, whose container can't see the host's loopback aliases: as setting says ("true", "false"), or otherwise yes only on Docker Desktop, which refuses a binding on a missing alias. OrbStack and Colima accept it and never forward it, so the address would time out.
func (AliasDecision) String ¶ added in v0.9.0
func (d AliasDecision) String() string
String says "yes" or "no", with the reason.
type Attachment ¶
Attachment connects the container to a network at creation.
type Client ¶
type Client struct {
// Endpoint is the socket, pipe or URL in use.
Endpoint string
// contains filtered or unexported fields
}
Client talks to a Docker-compatible Engine API endpoint.
func New ¶
New returns a client for endpoint ("unix:///path", "tcp://host:port" or, on Windows, "npipe:////./pipe/name").
func (*Client) AddrHolder ¶ added in v0.12.0
AddrHolder returns the container holding ip on network, attached with it or created with it as its fixed address (the runtime does not hold that until the container starts), and whether there is one. Only ID, Name and Labels are set.
func (*Client) ArchiveFrom ¶ added in v0.6.0
ArchiveFrom writes p (a file or a whole directory) inside the container to w as a tar stream whose entries are named under p's base name.
func (*Client) ArchiveTo ¶ added in v0.6.0
ArchiveTo extracts the tar stream r into dir inside the container (which may be created but not started), volumes mounted there included.
func (*Client) AttachMember ¶ added in v0.6.0
AttachMember connects the member container (SetMember) to network; it is a no-op without a member and when already connected. With reserved, it takes the subnet's second-to-last address as AttachSelf does. Without, it takes its pinned address (SetMemberAddr), or else the highest free address below the second-to-last one: on a VPC subnetwork the second-to-last address is the NAT egress proxy's, and compute hands out addresses from the bottom, possibly before their containers start, and none that a container holds (#146).
func (*Client) AttachSelf ¶ added in v0.3.0
AttachSelf connects the emulator's container to network; it is a no-op on the host and when already connected. It takes the subnet's second-to-last address, but not on a VPC container network (attach).
func (*Client) Connect ¶
func (c *Client) Connect(ctx context.Context, network, container, ip string, aliases ...string) error
Connect attaches a container to a network with an optional static IP.
func (*Client) CopyTo ¶
CopyTo writes files into dir inside the container (which may be created but not started).
func (*Client) CreateContainer ¶
CreateContainer creates (but does not start) a container.
func (*Client) CreateNetwork ¶
CreateNetwork creates a bridge network and returns its ID. Inside a container the emulator joins it (AttachSelf), and so does the member container (SetMember).
func (*Client) CreateVolume ¶
CreateVolume creates (or returns the existing) named volume.
func (*Client) Disconnect ¶
Disconnect detaches a container from a network.
func (*Client) Disrupted ¶ added in v0.7.0
Disrupted returns, as "name (exited)" or "name (restarted)", the containers among cts that the client started and that have since stopped or been started again by something else, such as a restart of the runtime daemon (#318). They lost what was set up after the start. Each candidate is inspected again, since the client may have started, stopped or removed it after cts was listed.
func (*Client) EnsureImage ¶
EnsureImage pulls ref unless it is already present.
func (*Client) Exec ¶
func (c *Client) Exec(ctx context.Context, id string, cmd []string, stdin []byte) (ExecResult, error)
Exec runs cmd in a running container and waits for it.
func (*Client) FollowLogs ¶ added in v0.9.0
FollowLogs streams a container's combined output from its start until it stops. Closing the stream, or ctx ending, stops following.
func (*Client) ForgetStart ¶ added in v0.13.0
ForgetStart drops the record of starting container id, so that Disrupted no longer reports it: for a container whose exit its owner saw and handles, by starting it again.
func (*Client) ImageExists ¶
ImageExists reports whether ref is present locally.
func (*Client) ImageFile ¶ added in v0.6.0
ImageFile pulls ref for platform ("linux/arm64") and returns the contents of file in it, read from a container that is created but never started (agent.Images).
func (*Client) InspectContainer ¶
InspectContainer returns container state.
func (*Client) InspectNetwork ¶
InspectNetwork returns a network by name or ID.
func (*Client) ListContainers ¶
ListContainers returns all containers (running or not) carrying all labels.
func (*Client) ListNetworks ¶
ListNetworks returns networks carrying all the given labels.
func (*Client) ListVolumes ¶
ListVolumes returns names of volumes carrying all the given labels.
func (*Client) NetworkAddrs ¶ added in v0.4.0
NetworkAddrs returns the IPv4 addresses held on a network: those of attached containers and those that created (not yet started) containers asked for.
func (*Client) PauseContainer ¶ added in v0.6.0
PauseContainer freezes a running container's processes.
func (*Client) RemoveContainer ¶
RemoveContainer deletes a container (with anonymous volumes); a missing container is not an error.
func (*Client) RemoveNetwork ¶
RemoveNetwork deletes a network; a missing network is not an error.
func (*Client) RemoveVolume ¶
RemoveVolume deletes a volume; a missing volume is not an error.
func (*Client) RestartContainer ¶
RestartContainer restarts a container.
func (*Client) SaveImages ¶
SaveImages writes a `docker save`-format tarball of the given local images to w (GKE preloads node images from the host cache with it).
func (*Client) Self ¶ added in v0.3.0
Self returns the emulator's own container ID, or "" when it runs on the host (or on the host network).
func (*Client) SelfFound ¶ added in v0.10.0
SelfFound reports whether the runtime found the emulator's own container, on the host's network or not. On the host, or in a container it can't find, Self is "" too (#502).
func (*Client) SelfIP ¶ added in v0.3.0
SelfIP returns the emulator's address on network ("" on the host).
func (*Client) SelfPorts ¶ added in v0.6.0
SelfPorts maps each TCP port the emulator's own container publishes to the host address it is published at (127.0.0.1 for the wildcard), or is nil on the host. On a VM runtime these are the only container ports the host reaches (ADR 0012).
func (*Client) SetMember ¶ added in v0.6.0
SetMember makes container join every network the client creates from now on, as the emulator's own container does, and leave each network before it is removed. joined is called with true after each join and with false before each removal. The VM relay (ADR 0005) is the member; "" ends membership.
func (*Client) SetMemberAddr ¶ added in v0.7.0
SetMemberAddr has the member container take, on each network it joins without reserved, the address addr returns for that network while it is free, and else chooses as without a pin; "" leaves the choice to AttachMember. The VM relay holds the Host address of a VPC container network this way, which must not move when the relay or the Instance restarts (ADR 0014).
func (*Client) SetReserved ¶ added in v0.12.0
SetReserved has AttachSelf and AttachMember skip the addresses reserved returns: those stored resources record and ask for again when their containers are recreated (Manager.Reserved), such as a Cloud SQL instance's Public IP (ADR 0035).
func (*Client) StartContainer ¶
StartContainer starts a created or stopped container.
func (*Client) StopContainer ¶
StopContainer stops a container, killing it after timeout.
func (*Client) UnpauseContainer ¶ added in v0.6.0
UnpauseContainer resumes a paused container.
type Container ¶
type Container struct {
ID string
Name string
Image string
Labels map[string]string
Running bool
Status string // created, running, exited, ...
// StartedAt is the runtime's time of the last start, RFC 3339.
StartedAt string
// ExitCode of the last run.
ExitCode int
// IPs maps network name to IPv4 address.
IPs map[string]string
// Ports maps "5432/tcp" to the published host address.
Ports map[string]string
// Cmd is the command the container was created with.
Cmd []string
}
Container is an inspected container.
type ContainerSpec ¶
type ContainerSpec struct {
Name string
Image string
Entrypoint []string
Cmd []string
Env []string
Labels map[string]string
Hostname string
Privileged bool
CapAdd []string
Sysctls map[string]string
// Networks: the first is used at create time, the rest are connected
// before start.
Networks []Attachment
// HostNetwork runs the container in the runtime's host network
// namespace, which on a VM runtime is the VM's, not the host's. It
// takes no Networks or Ports.
HostNetwork bool
Ports []Port
Mounts []Mount
// Tmpfs maps paths to mount options.
Tmpfs map[string]string
// CgroupnsHost runs in the host cgroup namespace (needed by some
// nested-container setups).
CgroupnsHost bool
// Memory limit in bytes (0 = unlimited).
Memory int64
// WorkingDir is the directory the command runs in; "" keeps the
// image's.
WorkingDir string
// Init runs a tiny init as PID 1 to reap zombies.
Init bool
// Platform picks the image variant ("linux/arm64"); "" lets the
// runtime choose.
Platform string
// DNS are the resolvers of the container's names that its network's
// do not resolve.
DNS []string
// ExtraHosts are "name:ip" lines added to the container's /etc/hosts.
ExtraHosts []string
// LogDriver is the container's log driver; "" keeps the runtime's
// default (but see Manager.CreateContainer).
LogDriver string
// LogOpts are LogDriver's options; they apply only with a LogDriver.
LogOpts map[string]string
}
ContainerSpec describes a container to create.
type ContainerizedDecision ¶ added in v0.10.0
type ContainerizedDecision struct {
On bool
// Guess, when not "", says that the marker files alone decided, under
// auto with no answer from the runtime, and why.
Guess string
// Conflict, when not "", says how --containerized disagrees with the
// runtime, which wins.
Conflict string
}
ContainerizedDecision is whether the Instance is a Containerized Instance.
func DecideContainerized ¶ added in v0.10.0
func DecideContainerized(f ContainerizedFacts) ContainerizedDecision
DecideContainerized decides from f.
type ContainerizedFacts ¶ added in v0.10.0
type ContainerizedFacts struct {
// Setting is --containerized.
Setting string
// Markers is InContainer.
Markers bool
// Runtime: the runtime was reached.
Runtime bool
// Found: it found the emulator's own container (SelfFound), Self
// being "" on the host's network.
Found bool
Self string
}
ContainerizedFacts is what DecideContainerized decides from.
type Detection ¶ added in v0.6.0
type Detection struct {
// Endpoint is the chosen socket or URL.
Endpoint string
// Source names what chose it: "$DOCKER_HOST", "Docker context \"x\""
// (from $DOCKER_CONTEXT or config.json), "socket list" or, on Windows,
// "named pipe list".
Source string
// Found lists the well-known runtime endpoints present on this host,
// chosen or not.
Found []string
// Skipped lists the endpoints in Found that answered but serve Windows
// containers, which gcpemu cannot use.
Skipped []string
}
Detection says which runtime endpoint detection picked and why.
type ExecResult ¶
ExecResult is the outcome of Exec.
type File ¶
type File struct {
Name string // path relative to the destination directory
Mode int64
Data []byte
// Path, if set, is read from the local filesystem instead of Data.
Path string
}
File is a file to copy into a container.
type Info ¶
type Info struct {
Name string // "docker" or "podman"
Version string
Arch string // GOARCH-style
Rootless bool
// OS is the runtime's operating system ("Docker Desktop", "OrbStack",
// "Ubuntu 24.04 LTS" for Colima) and Kernel its kernel version: on a
// VM runtime, the VM's.
OS string
Kernel string
// OSType is the kind of containers the runtime serves: "linux", or
// "windows" for Docker Engine in Windows containers mode; "" if /info
// did not answer.
OSType string
// NoCPUSet reports containers lack the cpuset cgroup controller, as on
// a rootless Podman machine, whose systemd delegates only cpu, io,
// memory and pids (#632). k3s, and so every GKE node, needs it. A
// Podman's /libpod/info controller list decides (#805); otherwise
// /info's "CPUSet": false. False when neither said.
NoCPUSet bool
}
Info describes the connected runtime.
type Manager ¶
type Manager struct {
*Client
Info Info
InstanceID string
Instance string
// Dir is the instance's absolute data dir, recorded on every object
// (LabelDir) so that an Abandoned Instance ID can be told apart.
Dir string
Offline bool
// Ephemeral instances also delete volumes and networks on cleanup.
Ephemeral bool
Log *slog.Logger
// Reserved, when set, returns the addresses that stored resources have
// recorded and ask for again when their containers are recreated (a
// Cloud SQL instance's public IP). See CreateContainer.
Reserved func() []string
// Agent finds the linux gcpemu binary for Managed containers; nil
// resolves without the cache or the published image (AgentBinary).
Agent *agent.Resolver
// VM says whether a Containerized Instance is on a VM runtime, whose
// host reaches it only through its published ports (ADR 0012).
VM VMDecision
// LoopbackAliases says whether, on a VM runtime, Cloud SQL instances
// may publish their ports on 127.0.0.2-127.0.0.254 (ADR 0012).
LoopbackAliases AliasDecision
// contains filtered or unexported fields
}
Manager scopes runtime objects to one emulator instance: it names and labels them, and reclaims orphans left by a crashed run (FR-CORE-006).
func (*Manager) AgentBinary ¶ added in v0.6.0
AgentBinary returns the path of a static linux gcpemu binary for the runtime's architecture, to copy into Managed containers.
func (*Manager) Cleanup ¶
Cleanup removes all of the instance's containers and the probe networks of failed pinned creates; with all=true also its networks and volumes.
func (*Manager) Connect ¶ added in v0.12.0
func (m *Manager) Connect(ctx context.Context, network, container, ip string, aliases ...string) error
Connect connects container to network like Client.Connect, except that without a fixed address, on a network whose subnet holds a Reserved address, it takes an address as CreateContainer picks one.
func (*Manager) CreateContainer ¶ added in v0.4.0
CreateContainer creates a container like Client.CreateContainer, except that an attachment without a fixed address, on a network whose subnet holds a Reserved address, gets the lowest free address outside the reserved set. The runtime would otherwise hand out a reserved address whose container is not running yet, e.g. after a restart (withPicks). On Podman, a container without a LogDriver gets readable logs (readableLogs).
func (*Manager) LogTail ¶ added in v0.12.0
LogTail returns the last n lines of container ct's output. If the runtime cannot read them, it returns the error instead and, on Podman, how to read them from the journal, where the journald log driver keeps them even after the container is removed.
type Mount ¶
type Mount struct {
Type string // "volume", "bind" or "tmpfs"
Source string
Target string
ReadOnly bool
}
Mount is a volume, bind or tmpfs mount.
type Network ¶
type Network struct {
ID string
Name string
Subnet string
Gateway string
Internal bool
Labels map[string]string
// Bridge is the host interface name, when the runtime reports it.
Bridge string
}
Network is an inspected network.
type NetworkSpec ¶
type NetworkSpec struct {
Name string
Subnet string // CIDR
Gateway string // optional; defaults to the first host address
Internal bool // no external connectivity
Labels map[string]string
// MTU sets com.docker.network.driver.mtu when non-zero.
MTU int
// Options are extra driver options (e.g. com.docker.network.bridge.*).
Options map[string]string
// Pin, without a Subnet, creates the network on the subnet the runtime
// picks, but as a configured one: before Docker 29, containers can ask
// for a fixed address only on networks created with a subnet.
Pin bool
}
NetworkSpec describes a bridge network.
type Port ¶
type Port struct {
HostIP string
HostPort int // 0 = runtime picks
ContainerPort int
Proto string // "tcp" (default) or "udp"
}
Port publishes a container port on the host.
type VMDecision ¶ added in v0.6.0
VMDecision says whether a Containerized Instance treats its runtime as a VM runtime, and why.
func DecideVM ¶ added in v0.6.0
func DecideVM(setting string, inContainer bool, info Info) VMDecision
DecideVM chooses for an Instance: never on the host, where the VM relay (ADR 0005) covers VM runtimes; otherwise as setting says ("true", "false"), or for "auto" and "" by the runtime's operating system and kernel, which name Docker Desktop and OrbStack.
func (VMDecision) String ¶ added in v0.6.0
func (d VMDecision) String() string
String says "yes" or "no", with the reason.