Documentation
¶
Overview ¶
Package container provides a runtime-agnostic container integration layer for Gopherstack. It supports Docker and Podman (any OCI-compatible runtime) via a single env var switch: CONTAINER_RUNTIME=docker|podman|auto.
The Runtime interface abstracts image management and container lifecycle operations (create/start/stop/remove), volume mounts, and a simple warm-container pool with configurable idle timeout.
Index ¶
- Constants
- Variables
- func AwaitWait(ctx context.Context, res dockercontainer.WaitResult) (dockercontainer.WaitResponse, error)
- func BindHostFor(advertiseHost string) string
- func CreateAndStartRetry(ctx context.Context, rt Starter, prepare func() (Spec, error), release func()) (string, error)
- func IsPortConflict(err error) bool
- func ManagedLabels(service, resource string) map[string]string
- func ParsePortSpec(spec string) (netip.Addr, string, string, error)
- func PortSpec(bindHost, hostPort, containerPort string) string
- func ResolveOCIRuntime(ctx context.Context, rt Runtime, candidates ...string) (string, error)
- func ResourceLabels(service, resource string) map[string]string
- func ServiceLabels(service string) map[string]string
- func SetOrphans(o *Orphans)
- func SplitContainerRef(ref string) (string, string, bool)
- func SweepOrphans(ctx context.Context) int
- type APIClient
- type Archive
- type ArchiveDeliverer
- type Config
- type DockerRuntime
- func (r *DockerRuntime) AcquireWarm(ctx context.Context, spec Spec) (*PooledContainer, error)
- func (r *DockerRuntime) Close() error
- func (r *DockerRuntime) ConnectNetwork(ctx context.Context, networkID, containerID string) error
- func (r *DockerRuntime) CreateAndStart(ctx context.Context, spec Spec) (string, error)
- func (r *DockerRuntime) CreateNetwork(ctx context.Context, name string) (string, error)
- func (r *DockerRuntime) CreateVolume(ctx context.Context, name string, labels map[string]string) error
- func (r *DockerRuntime) Exec(ctx context.Context, containerID string, cmd []string) (ExecResult, error)
- func (r *DockerRuntime) ExecEnv(ctx context.Context, containerID string, cmd, env []string) (ExecResult, error)
- func (r *DockerRuntime) ExecStdin(ctx context.Context, containerID string, cmd []string, stdin io.Reader, ...) (int, error)
- func (r *DockerRuntime) ExecStream(ctx context.Context, containerID string, cmd []string, out io.Writer) (int, error)
- func (r *DockerRuntime) HasImage(ctx context.Context, imageRef string) (bool, error)
- func (r *DockerRuntime) ImageDigest(ctx context.Context, ref string) (string, error)
- func (r *DockerRuntime) ListManaged(ctx context.Context) ([]ManagedContainer, error)
- func (r *DockerRuntime) ListUnusedVolumes(ctx context.Context, label string, olderThan time.Duration) ([]string, error)
- func (r *DockerRuntime) OCIRuntimes(ctx context.Context) ([]string, error)
- func (r *DockerRuntime) Ping(ctx context.Context) error
- func (r *DockerRuntime) PullImage(ctx context.Context, imageRef string) error
- func (r *DockerRuntime) PullImageWithCredentials(ctx context.Context, imageRef, username, password string) error
- func (r *DockerRuntime) ReadLogs(ctx context.Context, containerID, tail string, follow bool, ...) error
- func (r *DockerRuntime) ReapIdleContainers(ctx context.Context)
- func (r *DockerRuntime) ReleaseContainer(containerID string) error
- func (r *DockerRuntime) RemoveNetwork(ctx context.Context, networkID string) error
- func (r *DockerRuntime) RemoveVolume(ctx context.Context, name string) error
- func (r *DockerRuntime) StartContainer(ctx context.Context, containerID string) error
- func (r *DockerRuntime) StartReaper(ctx context.Context, interval time.Duration)
- func (r *DockerRuntime) Stats(ctx context.Context, containerID string) (Stats, error)
- func (r *DockerRuntime) StopAndRemove(ctx context.Context, containerID string) error
- func (r *DockerRuntime) StopAndRemoveWithin(ctx context.Context, containerID string, grace time.Duration) (bool, error)
- func (r *DockerRuntime) StopContainer(ctx context.Context, containerID string) error
- func (r *DockerRuntime) StreamLogs(ctx context.Context, containerID string, stdout, stderr io.Writer) error
- func (r *DockerRuntime) TagAndPush(ctx context.Context, source, target string) (string, error)
- func (r *DockerRuntime) WaitExit(ctx context.Context, containerID string) (int, error)
- type EnvExecer
- type ExecAPIClient
- type ExecEnvAPIClient
- type ExecRequest
- type ExecResult
- type ExecStdinAPIClient
- type ExecStreamAPIClient
- type Execer
- type ExitWaiter
- type GracefulStopper
- type Identity
- type ImageDigester
- type ImagePusher
- type Injection
- type KubernetesConfig
- type KubernetesRuntime
- func (r *KubernetesRuntime) AcquireWarm(context.Context, Spec) (*PooledContainer, error)
- func (r *KubernetesRuntime) Close() error
- func (r *KubernetesRuntime) CreateAndStart(ctx context.Context, spec Spec) (string, error)
- func (r *KubernetesRuntime) DeletePod(ctx context.Context, name string, withSecret bool) error
- func (r *KubernetesRuntime) DeliversArchives() bool
- func (r *KubernetesRuntime) Exec(context.Context, string, []string) (ExecResult, error)
- func (r *KubernetesRuntime) ExecInteractive(ctx context.Context, pod, containerName string, command []string, ...) (PodShell, error)
- func (r *KubernetesRuntime) FollowPod(ctx context.Context, name string, fn func(pod *corev1.Pod, gone bool) bool) error
- func (r *KubernetesRuntime) GetPod(ctx context.Context, name string) (*corev1.Pod, error)
- func (r *KubernetesRuntime) HasImage(context.Context, string) (bool, error)
- func (r *KubernetesRuntime) LaunchPod(ctx context.Context, l PodLaunch) (*corev1.Pod, error)
- func (r *KubernetesRuntime) ListManaged(ctx context.Context) ([]ManagedContainer, error)
- func (r *KubernetesRuntime) Namespace() string
- func (r *KubernetesRuntime) Ping(ctx context.Context) error
- func (r *KubernetesRuntime) PullImage(context.Context, string) error
- func (r *KubernetesRuntime) ReadLogs(ctx context.Context, containerID, tail string, follow bool, ...) error
- func (r *KubernetesRuntime) ReapIdleContainers(context.Context)
- func (r *KubernetesRuntime) ReleaseContainer(string) error
- func (r *KubernetesRuntime) StartContainer(context.Context, string) error
- func (r *KubernetesRuntime) StartReaper(context.Context, time.Duration)
- func (r *KubernetesRuntime) StopAndRemove(ctx context.Context, containerID string) error
- func (r *KubernetesRuntime) StopContainer(context.Context, string) error
- func (r *KubernetesRuntime) StreamLogs(ctx context.Context, containerID string, stdout, stderr io.Writer) error
- func (r *KubernetesRuntime) StreamPodLogs(ctx context.Context, pod, containerName string, w io.Writer) error
- type ListAPIClient
- type LogReader
- type LogStreamer
- type LogsAPIClient
- type ManagedContainer
- type ManagedLister
- type NetworkAPIClient
- type NetworkRuntime
- type OCIRuntimeAPIClient
- type OCIRuntimeLister
- type Orphans
- type PodExecutor
- type PodFailedError
- type PodLaunch
- type PodShell
- type PooledContainer
- type PushAPIClient
- type Runtime
- type RuntimeName
- type Spec
- type Starter
- type Stats
- type StatsAPIClient
- type StatsReader
- type StdinExecer
- type StreamExecer
- type TermSize
- type VolumeAPIClient
- type VolumeRuntime
- type WaitAPIClient
Constants ¶
const ( // LabelManaged marks a container as started by gopherstack. LabelManaged = "gopherstack.managed" // LabelService names the service that owns the container. LabelService = "gopherstack.service" // LabelOwner is the instance identity: stable per data dir when persistence is on, fresh per run otherwise. LabelOwner = "gopherstack.owner" // LabelResource is the owning service's key for the resource; only labelled containers can be adopted. LabelResource = "gopherstack.resource" // LabelPID is "pid:starttime" of the launching process. LabelPID = "gopherstack.pid" // LabelEphemeral is "true" when the owner id is per-run (persistence off). LabelEphemeral = "gopherstack.ephemeral" )
const ( // EnvInjectDNS is a comma-separated DNS server list given to every spawned container. EnvInjectDNS = "GOPHERSTACK_CONTAINER_DNS" // EnvInjectCAFile is a host CA PEM mounted into every spawned container and exported as CA bundle vars. EnvInjectCAFile = "GOPHERSTACK_CONTAINER_CA_FILE" // InjectedCAPath is where the CA lands inside containers. InjectedCAPath = "/etc/gopherstack/ca.pem" )
const ( // EnvK8sKubeconfig selects a kubeconfig file; unset means in-cluster config when running in a Pod. EnvK8sKubeconfig = "CONTAINER_K8S_KUBECONFIG" // EnvK8sNamespace is the namespace Pods are created in; defaults to the Pod's own namespace. EnvK8sNamespace = "CONTAINER_K8S_NAMESPACE" // EnvK8sAdvertiseHost is the address function Pods use to reach this process (usually its Pod IP). EnvK8sAdvertiseHost = "CONTAINER_K8S_ADVERTISE_HOST" // EnvK8sCodePort is the TCP port the archive server listens on. EnvK8sCodePort = "CONTAINER_K8S_CODE_PORT" // EnvK8sFetchImage is the image of the initContainer that downloads and unpacks archives. EnvK8sFetchImage = "CONTAINER_K8S_FETCH_IMAGE" )
const AllInterfacesHost = "0.0.0.0"
AllInterfacesHost binds a published port on every host interface.
const LoopbackHost = "127.0.0.1"
LoopbackHost is the default bind address for engine-published ports.
const PortRetries = 5
PortRetries bounds CreateAndStartRetry attempts.
Variables ¶
var ErrArchivesUnsupported = errors.New("container archives are not supported by this runtime")
ErrArchivesUnsupported is returned by runtimes that cannot deliver Spec.Archives.
var ErrContainerNotFound = errors.New("container not found")
ErrContainerNotFound is returned when a requested container does not exist in the pool.
var ErrExecNoConfig = errors.New("pods/exec needs a cluster connection or a PodExecutor")
ErrExecNoConfig is returned when pods/exec is requested on a runtime built from an injected client without an Executor.
var ErrExecUnsupported = errors.New("container exec is not supported by this runtime client")
ErrExecUnsupported is returned by Exec when the underlying client cannot run commands in a container.
var ErrInvalidPort = errors.New("invalid port mapping")
ErrInvalidPort is returned when a Spec.Ports entry is not a valid [IP:]HOST:CONTAINER mapping.
var ErrK8sUnsupported = errors.New("operation is not supported by the kubernetes runtime")
ErrK8sUnsupported is returned for operations a Pod cannot offer.
var ErrListUnsupported = errors.New("container listing is not supported by this runtime client")
ErrListUnsupported is returned when the runtime client cannot list containers.
var ErrLogsUnsupported = errors.New("container logs are not supported by this runtime client")
ErrLogsUnsupported is returned by StreamLogs when the underlying client cannot read container logs.
var ErrNetworkUnsupported = errors.New("container networks are not supported by this runtime client")
ErrNetworkUnsupported is returned when the underlying client cannot manage networks.
var ErrNoAdvertiseHost = errors.New("archive delivery needs " + EnvK8sAdvertiseHost)
ErrNoAdvertiseHost is returned when archives are requested but pods have no address to fetch them from.
var ErrOCIRuntimeMissing = errors.New("OCI runtime is not registered with the container daemon")
ErrOCIRuntimeMissing is returned when a requested OCI runtime is not registered with the daemon.
var ErrOCIRuntimeUnverifiable = errors.New("cannot list the container daemon's OCI runtimes")
ErrOCIRuntimeUnverifiable is returned when the daemon's registered runtimes cannot be listed.
var ErrPodFailed = errors.New("pod failed to start")
ErrPodFailed is returned when a Pod cannot reach Running.
var ErrPoolExhausted = errors.New("container pool exhausted")
ErrPoolExhausted is returned when no warm container is available and the pool is full.
var ErrPushUnsupported = errors.New("image push is not supported by this runtime client")
ErrPushUnsupported is returned by TagAndPush when the underlying client cannot tag and push images.
var ErrSpecUnsupported = errors.New("container spec field is not supported by the kubernetes runtime")
ErrSpecUnsupported is returned for Spec fields a Pod cannot honour.
var ErrStatsUnsupported = errors.New("container stats are not supported by this runtime client")
ErrStatsUnsupported is returned when the runtime client cannot report container stats.
ErrUnavailable is returned when the container runtime is not available on the host.
var ErrUnknownRuntime = errors.New("unknown container runtime")
ErrUnknownRuntime is returned when an unrecognised runtime name is provided.
var ErrUnsafeArchive = errors.New("archive has an unsafe entry name")
ErrUnsafeArchive is returned for a zip with absolute or parent-escaping entry names.
var ErrVolumeUnsupported = errors.New("container volumes are not supported by this runtime client")
ErrVolumeUnsupported is returned when the underlying client cannot manage volumes.
var ErrWaitFailed = errors.New("container wait failed")
ErrWaitFailed wraps an error the daemon reported while waiting.
var ErrWaitUnsupported = errors.New("container wait is not supported by this runtime client")
ErrWaitUnsupported is returned by WaitExit when the underlying client cannot wait on a container.
var ErrWatchClosed = errors.New("pod watch closed")
ErrWatchClosed is returned when a Pod watch ends before the awaited transition.
Functions ¶
func AwaitWait ¶
func AwaitWait(ctx context.Context, res dockercontainer.WaitResult) (dockercontainer.WaitResponse, error)
AwaitWait blocks for the first of res.Result, res.Error or ctx cancellation. Moby's resultC is unbuffered and its sender never selects on ctx, so on early return a drainer receives from res to let that goroutine exit: it either sends the result or, once ctx is cancelled, fails the body read into buffered errC.
func BindHostFor ¶
BindHostFor picks the host IP to publish ports on: loopback unless the operator advertised a non-loopback host, in which case all interfaces.
func CreateAndStartRetry ¶
func CreateAndStartRetry( ctx context.Context, rt Starter, prepare func() (Spec, error), release func(), ) (string, error)
CreateAndStartRetry starts the spec returned by prepare. On a host-port bind conflict it calls release, then prepare again for fresh ports, up to PortRetries attempts. release is also not called on success; the caller owns the ports of the container it got back.
func IsPortConflict ¶
IsPortConflict reports whether err is a runtime host-port bind failure.
func ManagedLabels ¶
ManagedLabels are the labels for a container started outside DockerRuntime: this process's identity plus the service labels, with the resource key when resource is non-empty (only then can a restart adopt it).
func ParsePortSpec ¶
ParsePortSpec splits "[IP:]HOST:CONTAINER"; an absent IP yields the IPv4 unspecified address.
func ResolveOCIRuntime ¶
ResolveOCIRuntime returns the first candidate registered with rt's daemon, or an error naming them all.
func ResourceLabels ¶
ResourceLabels labels a container so a restarted gopherstack can match it to resource (the service's own key).
func ServiceLabels ¶
ServiceLabels names the owning service without a resource key: the container is never adopted, and a restarted gopherstack removes it at startup before the service relaunches.
func SetOrphans ¶
func SetOrphans(o *Orphans)
SetOrphans installs the process-wide registry services claim from.
func SplitContainerRef ¶
SplitContainerRef splits a "pod/container" reference.
func SweepOrphans ¶
SweepOrphans sweeps the process-wide registry.
Types ¶
type APIClient ¶
type APIClient interface {
ImagePull(ctx context.Context, refStr string, options image.PullOptions) (io.ReadCloser, error)
ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error)
ContainerCreate(
ctx context.Context,
cfg *dockercontainer.Config,
hostConfig *dockercontainer.HostConfig,
networkingConfig any,
platform any,
containerName string,
) (dockercontainer.CreateResponse, error)
ContainerStart(ctx context.Context, containerID string, options dockercontainer.StartOptions) error
ContainerStop(ctx context.Context, containerID string, options dockercontainer.StopOptions) error
ContainerRemove(ctx context.Context, containerID string, options dockercontainer.RemoveOptions) error
Ping(ctx context.Context) (any, error)
Close() error
}
APIClient is a subset of the Docker/Podman SDK client interface used by DockerRuntime. It is defined as an interface to enable testing without a real container daemon.
type Archive ¶
Archive is a zip delivered to Dest inside the container; runtimes without bind mounts unpack it for the caller.
type ArchiveDeliverer ¶
type ArchiveDeliverer interface {
DeliversArchives() bool
}
ArchiveDeliverer is implemented by runtimes that deliver Spec.Archives and have no host bind mounts.
type Config ¶
type Config struct {
Logger *slog.Logger
// Injection overrides the env-derived DNS/CA injection for spawned containers.
Injection *Injection
// Kubernetes configures RuntimeKubernetes; unset fields come from the environment.
Kubernetes *KubernetesConfig
Runtime RuntimeName
PoolSize int
IdleTimeout time.Duration
}
Config holds configuration for the container runtime layer.
type DockerRuntime ¶
type DockerRuntime struct {
// contains filtered or unexported fields
}
DockerRuntime implements Runtime using the Docker daemon.
func NewDockerRuntimeWithAPI ¶
func NewDockerRuntimeWithAPI(api APIClient, cfg Config) *DockerRuntime
NewDockerRuntimeWithAPI creates a DockerRuntime with an injected APIClient. This is primarily intended for testing; production code should use NewRuntime.
func (*DockerRuntime) AcquireWarm ¶
func (r *DockerRuntime) AcquireWarm(ctx context.Context, spec Spec) (*PooledContainer, error)
AcquireWarm returns a warm container from the pool for the given image. If no warm container is available, a new one is created (up to PoolSize). The caller must call ReleaseContainer when done.
Note: PoolSize is a soft limit. When multiple goroutines call AcquireWarm concurrently, the pool may temporarily exceed PoolSize by the number of concurrent callers that see no idle container and concurrently create new ones.
func (*DockerRuntime) Close ¶
func (r *DockerRuntime) Close() error
Close releases resources held by the Docker client.
func (*DockerRuntime) ConnectNetwork ¶
func (r *DockerRuntime) ConnectNetwork(ctx context.Context, networkID, containerID string) error
ConnectNetwork attaches a running container to the network.
func (*DockerRuntime) CreateAndStart ¶
CreateAndStart creates a new container from spec and starts it. Returns the container ID.
func (*DockerRuntime) CreateNetwork ¶
CreateNetwork creates a bridge network and returns its ID.
func (*DockerRuntime) CreateVolume ¶
func (r *DockerRuntime) CreateVolume(ctx context.Context, name string, labels map[string]string) error
CreateVolume creates a labelled named volume; an existing one is reused.
func (*DockerRuntime) Exec ¶
func (r *DockerRuntime) Exec(ctx context.Context, containerID string, cmd []string) (ExecResult, error)
Exec runs cmd inside a running container and waits for it to finish.
func (*DockerRuntime) ExecEnv ¶
func (r *DockerRuntime) ExecEnv(ctx context.Context, containerID string, cmd, env []string) (ExecResult, error)
ExecEnv runs cmd like Exec with env (KEY=VALUE entries) set on the process instead of in its argv.
func (*DockerRuntime) ExecStdin ¶
func (r *DockerRuntime) ExecStdin( ctx context.Context, containerID string, cmd []string, stdin io.Reader, out io.Writer, rows, cols uint, ) (int, error)
ExecStdin runs cmd like ExecStream with stdin relayed to the process; a non-zero rows and cols allocate a terminal.
func (*DockerRuntime) ExecStream ¶
func (r *DockerRuntime) ExecStream(ctx context.Context, containerID string, cmd []string, out io.Writer) (int, error)
ExecStream runs cmd like Exec but writes stdout and stderr to out as the command produces them.
func (*DockerRuntime) HasImage ¶
HasImage reports whether the given image reference is already present locally.
func (*DockerRuntime) ImageDigest ¶
ImageDigest returns the digest of the local image ref.
func (*DockerRuntime) ListManaged ¶
func (r *DockerRuntime) ListManaged(ctx context.Context) ([]ManagedContainer, error)
ListManaged lists the containers carrying LabelManaged, running or not.
func (*DockerRuntime) ListUnusedVolumes ¶
func (r *DockerRuntime) ListUnusedVolumes( ctx context.Context, label string, olderThan time.Duration, ) ([]string, error)
ListUnusedVolumes lists the volumes carrying label that no container references and that are older than olderThan, so a volume a concurrent launch has just created is left alone.
func (*DockerRuntime) OCIRuntimes ¶
func (r *DockerRuntime) OCIRuntimes(ctx context.Context) ([]string, error)
OCIRuntimes returns the OCI runtime names registered with the daemon.
func (*DockerRuntime) Ping ¶
func (r *DockerRuntime) Ping(ctx context.Context) error
Ping checks whether the Docker daemon is reachable.
func (*DockerRuntime) PullImage ¶
func (r *DockerRuntime) PullImage(ctx context.Context, imageRef string) error
PullImage pulls the specified image from the registry.
func (*DockerRuntime) PullImageWithCredentials ¶
func (r *DockerRuntime) PullImageWithCredentials(ctx context.Context, imageRef, username, password string) error
PullImageWithCredentials pulls imageRef authenticating to the registry as username/password.
func (*DockerRuntime) ReadLogs ¶
func (r *DockerRuntime) ReadLogs( ctx context.Context, containerID, tail string, follow bool, stdout, stderr io.Writer, ) error
ReadLogs reads the container's logs, demultiplexing stdout and stderr into the writers.
func (*DockerRuntime) ReapIdleContainers ¶
func (r *DockerRuntime) ReapIdleContainers(ctx context.Context)
ReapIdleContainers stops and removes containers that have been idle longer than IdleTimeout.
func (*DockerRuntime) ReleaseContainer ¶
func (r *DockerRuntime) ReleaseContainer(containerID string) error
ReleaseContainer marks a pooled container as idle. If the container is not in the pool, ErrContainerNotFound is returned.
func (*DockerRuntime) RemoveNetwork ¶
func (r *DockerRuntime) RemoveNetwork(ctx context.Context, networkID string) error
RemoveNetwork deletes the network.
func (*DockerRuntime) RemoveVolume ¶
func (r *DockerRuntime) RemoveVolume(ctx context.Context, name string) error
RemoveVolume force-removes a named volume; a missing volume is not an error.
func (*DockerRuntime) StartContainer ¶
func (r *DockerRuntime) StartContainer(ctx context.Context, containerID string) error
StartContainer starts a previously stopped container.
func (*DockerRuntime) StartReaper ¶
func (r *DockerRuntime) StartReaper(ctx context.Context, interval time.Duration)
StartReaper launches a background goroutine that periodically reaps idle containers. It stops when ctx is cancelled.
func (*DockerRuntime) StopAndRemove ¶
func (r *DockerRuntime) StopAndRemove(ctx context.Context, containerID string) error
StopAndRemove stops and removes a container.
func (*DockerRuntime) StopAndRemoveWithin ¶
func (r *DockerRuntime) StopAndRemoveWithin( ctx context.Context, containerID string, grace time.Duration, ) (bool, error)
StopAndRemoveWithin stops the container after a SIGTERM grace period and removes it.
func (*DockerRuntime) StopContainer ¶
func (r *DockerRuntime) StopContainer(ctx context.Context, containerID string) error
StopContainer stops a container without removing it, keeping its published ports and data.
func (*DockerRuntime) StreamLogs ¶
func (r *DockerRuntime) StreamLogs(ctx context.Context, containerID string, stdout, stderr io.Writer) error
StreamLogs follows the container's logs, demultiplexing stdout and stderr into the writers.
func (*DockerRuntime) TagAndPush ¶
TagAndPush tags the local image source as target and pushes it.
type EnvExecer ¶
type EnvExecer interface {
ExecEnv(ctx context.Context, containerID string, cmd, env []string) (ExecResult, error)
}
EnvExecer is implemented by runtimes that can set environment variables on an exec process.
type ExecAPIClient ¶
type ExecAPIClient interface {
ContainerExec(
ctx context.Context,
containerID string,
cmd []string,
) (stdout, stderr []byte, exitCode int, err error)
}
ExecAPIClient is implemented by clients that can run commands inside a container.
type ExecEnvAPIClient ¶
type ExecEnvAPIClient interface {
ContainerExecEnv(
ctx context.Context,
containerID string,
cmd, env []string,
) (stdout, stderr []byte, exitCode int, err error)
}
ExecEnvAPIClient is implemented by clients that can run a command with extra environment variables.
type ExecRequest ¶
type ExecRequest struct {
Stdin io.Reader
Stdout io.Writer
Resize <-chan TermSize
Pod string
Container string
Command []string
}
ExecRequest is one pods/exec stream with a TTY: stdout and stderr share Stdout.
type ExecResult ¶
type ExecResult struct {
// Stdout and Stderr hold the demultiplexed output streams.
Stdout string
Stderr string
// ExitCode is the command's exit status.
ExitCode int
}
ExecResult is the outcome of a command run inside a container.
func ExecWithEnv ¶
func ExecWithEnv(ctx context.Context, x Execer, containerID string, cmd, env []string) (ExecResult, error)
ExecWithEnv runs cmd with env (KEY=VALUE entries) set on the process, keeping secrets out of argv. It never falls back to argv: a runtime without EnvExecer yields ErrExecUnsupported.
type ExecStdinAPIClient ¶
type ExecStdinAPIClient interface {
ContainerExecStdin(
ctx context.Context,
containerID string,
cmd []string,
stdin io.Reader,
out io.Writer,
rows, cols uint,
) (int, error)
}
ExecStdinAPIClient is implemented by clients that can run a command with standard input attached.
type ExecStreamAPIClient ¶
type ExecStreamAPIClient interface {
ContainerExecStream(
ctx context.Context,
containerID string,
cmd []string,
stdout, stderr io.Writer,
) (int, error)
}
ExecStreamAPIClient is implemented by clients that can stream a command's output while it runs.
type Execer ¶
type Execer interface {
Exec(ctx context.Context, containerID string, cmd []string) (ExecResult, error)
}
Execer runs a command in a container.
type ExitWaiter ¶
type ExitWaiter interface {
// WaitExit blocks until the container stops and returns its exit code.
WaitExit(ctx context.Context, containerID string) (int, error)
}
ExitWaiter is implemented by runtimes that can report a container's exit status.
type GracefulStopper ¶
type GracefulStopper interface {
// StopAndRemoveWithin sends SIGTERM, waits up to grace for the process to exit, then kills and removes the
// container. killed reports that the grace period ran out.
StopAndRemoveWithin(ctx context.Context, containerID string, grace time.Duration) (killed bool, err error)
}
GracefulStopper is implemented by runtimes that can stop a container with a caller-chosen SIGTERM grace period.
type Identity ¶
Identity is the per-process instance identity stamped onto launched containers.
func CurrentIdentity ¶
func CurrentIdentity() Identity
CurrentIdentity returns the process identity, creating an ephemeral one on first use.
func SetEphemeralOwner ¶
func SetEphemeralOwner() Identity
SetEphemeralOwner gives the process a fresh owner id, so no earlier run's containers are ever adopted.
func SetPersistentOwner ¶
SetPersistentOwner derives a stable owner id from the persistence data dir.
type ImageDigester ¶
ImageDigester is implemented by runtimes that can report the content digest ("sha256:...") of a local image.
type ImagePusher ¶
type ImagePusher interface {
// TagAndPush tags the local image source as target, pushes target, and returns the pushed digest when known.
TagAndPush(ctx context.Context, source, target string) (string, error)
}
ImagePusher is implemented by runtimes that can publish a local image to a registry.
type Injection ¶
Injection points spawned containers at the embedded DNS and trusts the gopherstack CA, so SDKs inside them reach real AWS endpoint names transparently.
func InjectionFromEnv ¶
func InjectionFromEnv() *Injection
InjectionFromEnv reads EnvInjectDNS and EnvInjectCAFile; nil when neither is set.
type KubernetesConfig ¶
type KubernetesConfig struct {
Client kubernetes.Interface
CodeListener net.Listener
Executor PodExecutor
Kubeconfig string
Namespace string
AdvertiseHost string
FetchImage string
CodePort int
StartTimeout time.Duration
}
KubernetesConfig configures RuntimeKubernetes. Zero values fall back to the environment.
type KubernetesRuntime ¶
type KubernetesRuntime struct {
// contains filtered or unexported fields
}
KubernetesRuntime runs containers as Pods; the container ID is the Pod name.
func (*KubernetesRuntime) AcquireWarm ¶
func (r *KubernetesRuntime) AcquireWarm(context.Context, Spec) (*PooledContainer, error)
AcquireWarm is unsupported: Pods are not pooled.
func (*KubernetesRuntime) Close ¶
func (r *KubernetesRuntime) Close() error
Close stops the archive server.
func (*KubernetesRuntime) CreateAndStart ¶
CreateAndStart creates the Pod and waits, by watch, until it is running.
func (*KubernetesRuntime) DeletePod ¶
DeletePod deletes the Pod, giving its containers their terminationGracePeriodSeconds, and waits until it is gone. withSecret also deletes the Secret LaunchPod created. A missing Pod or Secret is not an error.
func (*KubernetesRuntime) DeliversArchives ¶
func (r *KubernetesRuntime) DeliversArchives() bool
DeliversArchives reports that Spec.Archives are unpacked by the runtime.
func (*KubernetesRuntime) Exec ¶
func (r *KubernetesRuntime) Exec(context.Context, string, []string) (ExecResult, error)
Exec is unsupported; the chart grants no pods/exec.
func (*KubernetesRuntime) ExecInteractive ¶
func (r *KubernetesRuntime) ExecInteractive( ctx context.Context, pod, containerName string, command []string, cols, rows uint, ) (PodShell, error)
ExecInteractive runs command in a Pod container with a TTY. Closing the shell ends the command.
func (*KubernetesRuntime) FollowPod ¶
func (r *KubernetesRuntime) FollowPod( ctx context.Context, name string, fn func(pod *corev1.Pod, gone bool) bool, ) error
FollowPod calls fn with the Pod's current state, then with every change, until fn returns true, the Pod is deleted (fn then sees gone) or ctx ends. A watch that closes is re-established and the Pod re-read.
func (*KubernetesRuntime) HasImage ¶
HasImage reports true: whether the image is present is the kubelet's concern, so callers never pre-pull.
func (*KubernetesRuntime) LaunchPod ¶
LaunchPod creates the Pod (and its Secret) and waits, by watch, until it is running or has run. A failed launch removes both. The returned Pod is the last observed state.
func (*KubernetesRuntime) ListManaged ¶
func (r *KubernetesRuntime) ListManaged(ctx context.Context) ([]ManagedContainer, error)
ListManaged lists the Pods carrying LabelManaged; labels are read back from annotations, which keep values (such as pid:start) that Kubernetes label syntax rejects.
func (*KubernetesRuntime) Namespace ¶
func (r *KubernetesRuntime) Namespace() string
Namespace is the namespace Pods are created in.
func (*KubernetesRuntime) Ping ¶
func (r *KubernetesRuntime) Ping(ctx context.Context) error
Ping lists one managed Pod, which also proves the RBAC the runtime needs.
func (*KubernetesRuntime) PullImage ¶
func (r *KubernetesRuntime) PullImage(context.Context, string) error
PullImage is a no-op: the kubelet pulls the image when the Pod is scheduled.
func (*KubernetesRuntime) ReadLogs ¶
func (r *KubernetesRuntime) ReadLogs( ctx context.Context, containerID, tail string, follow bool, stdout, _ io.Writer, ) error
ReadLogs reads the Pod's logs; Pods merge stdout and stderr, so everything goes to stdout.
func (*KubernetesRuntime) ReapIdleContainers ¶
func (r *KubernetesRuntime) ReapIdleContainers(context.Context)
ReapIdleContainers does nothing: there is no pool to reap.
func (*KubernetesRuntime) ReleaseContainer ¶
func (r *KubernetesRuntime) ReleaseContainer(string) error
ReleaseContainer is unsupported: Pods are not pooled.
func (*KubernetesRuntime) StartContainer ¶
func (r *KubernetesRuntime) StartContainer(context.Context, string) error
StartContainer is unsupported: a Pod cannot be stopped and restarted in place.
func (*KubernetesRuntime) StartReaper ¶
func (r *KubernetesRuntime) StartReaper(context.Context, time.Duration)
StartReaper does nothing: there is no pool to reap.
func (*KubernetesRuntime) StopAndRemove ¶
func (r *KubernetesRuntime) StopAndRemove(ctx context.Context, containerID string) error
StopAndRemove deletes the Pod and waits, by watch, until it is gone; a missing Pod is not an error.
func (*KubernetesRuntime) StopContainer ¶
func (r *KubernetesRuntime) StopContainer(context.Context, string) error
StopContainer is unsupported: a Pod cannot be stopped and restarted in place.
func (*KubernetesRuntime) StreamLogs ¶
func (r *KubernetesRuntime) StreamLogs(ctx context.Context, containerID string, stdout, stderr io.Writer) error
StreamLogs follows the Pod's output; Pods merge stdout and stderr, so everything goes to stdout.
func (*KubernetesRuntime) StreamPodLogs ¶
func (r *KubernetesRuntime) StreamPodLogs(ctx context.Context, pod, containerName string, w io.Writer) error
StreamPodLogs follows one container's output into w until the container ends or ctx is cancelled.
type ListAPIClient ¶
type ListAPIClient interface {
ContainerListByLabel(ctx context.Context, label string) ([]ManagedContainer, error)
}
ListAPIClient is implemented by clients that can list containers by label.
type LogReader ¶
type LogReader interface {
// ReadLogs writes the last tail lines (all when tail is empty) to the writers; follow keeps streaming.
ReadLogs(ctx context.Context, containerID, tail string, follow bool, stdout, stderr io.Writer) error
}
LogReader is implemented by runtimes that can read a container's recent logs, optionally following them.
type LogStreamer ¶
type LogStreamer interface {
// StreamLogs writes the container's stdout and stderr to the given writers as they are produced.
// It blocks until the container is removed or stops, or ctx ends.
StreamLogs(ctx context.Context, containerID string, stdout, stderr io.Writer) error
}
LogStreamer is implemented by runtimes that can follow a container's stdout and stderr.
type LogsAPIClient ¶
type LogsAPIClient interface {
ContainerLogs(ctx context.Context, containerID string, options dockercontainer.LogsOptions) (io.ReadCloser, error)
}
LogsAPIClient is implemented by clients that can read a container's logs.
type ManagedContainer ¶
type ManagedContainer struct {
Labels map[string]string
// Ports maps container port to published host port.
Ports map[int]int
ID string
Name string
Running bool
}
ManagedContainer is a container carrying LabelManaged.
func ClaimOrphan ¶
func ClaimOrphan(service, resource string) (ManagedContainer, bool)
ClaimOrphan claims from the process-wide registry; false when nothing is held.
type ManagedLister ¶
type ManagedLister interface {
ListManaged(ctx context.Context) ([]ManagedContainer, error)
StopAndRemove(ctx context.Context, containerID string) error
}
ManagedLister is implemented by runtimes that can list gopherstack-managed containers.
type NetworkAPIClient ¶
type NetworkAPIClient interface {
NetworkCreate(ctx context.Context, name string) (string, error)
NetworkConnect(ctx context.Context, networkID, containerID string) error
NetworkRemove(ctx context.Context, networkID string) error
}
NetworkAPIClient is implemented by clients that can manage user-defined networks.
type NetworkRuntime ¶
type NetworkRuntime interface {
// CreateNetwork creates a bridge network and returns its ID.
CreateNetwork(ctx context.Context, name string) (string, error)
// ConnectNetwork attaches a running container to the network.
ConnectNetwork(ctx context.Context, networkID, containerID string) error
// RemoveNetwork deletes the network.
RemoveNetwork(ctx context.Context, networkID string) error
}
NetworkRuntime is implemented by runtimes that can manage user-defined container networks.
type OCIRuntimeAPIClient ¶
OCIRuntimeAPIClient is implemented by clients that can list the daemon's registered OCI runtimes.
type OCIRuntimeLister ¶
OCIRuntimeLister is implemented by runtimes that can list the daemon's registered OCI runtimes.
type Orphans ¶
type Orphans struct {
// contains filtered or unexported fields
}
Orphans holds the previous run's resource-labelled containers until their services adopt them.
func Reconcile ¶
func Reconcile(ctx context.Context, rt ManagedLister, id Identity, log *slog.Logger) (*Orphans, error)
Reconcile lists managed containers and removes the ones that are provably dead leftovers of this instance:
- this owner's containers without a LabelResource are removed now unless this very process launched them (they are live: tests and embedders run several instances in one process);
- ones whose launcher process is gone and has no resource to adopt for are removed now;
- another owner's containers are removed only when they are ephemeral and their launcher process is dead;
- this owner's resource-labelled containers (launcher dead or this very process) are held for Claim;
- everything else, including this owner's containers whose launcher is still alive elsewhere, is untouched.
type PodExecutor ¶
type PodExecutor interface {
StreamExec(ctx context.Context, req ExecRequest) error
}
PodExecutor streams a command in a Pod container until it ends or ctx is cancelled.
type PodFailedError ¶
PodFailedError is returned when a Pod cannot reach a running state. Reason is the Kubernetes waiting or termination reason (ErrImagePull, ImagePullBackOff, Error, ...).
func (*PodFailedError) Error ¶
func (f *PodFailedError) Error() string
func (*PodFailedError) Is ¶
func (f *PodFailedError) Is(target error) bool
Is reports ErrPodFailed so callers can match every launch failure with errors.Is.
type PodLaunch ¶
type PodLaunch struct {
// Labels are added to the managed identity labels; values Kubernetes rejects as labels land in annotations.
Labels map[string]string
// Secret, when non-empty, becomes a Secret named after the Pod that the PodSpec references and the Pod owns.
Secret map[string][]byte
Name string
Spec corev1.PodSpec
}
PodLaunch describes a multi-container Pod started as one unit, for callers (ECS tasks) that map their own container model onto a PodSpec.
type PooledContainer ¶
type PooledContainer struct {
// LastUsed is the timestamp of the last time this container was used.
LastUsed time.Time
// ID is the container ID.
ID string
// Image is the image the container was started from.
Image string
// InUse indicates whether the container is currently handling an invocation.
InUse bool
}
PooledContainer tracks a container managed by the warm pool.
type PushAPIClient ¶
type PushAPIClient interface {
ImageTag(ctx context.Context, source, target string) error
ImagePush(ctx context.Context, ref string) (string, error)
}
PushAPIClient is implemented by clients that can tag and push images.
type Runtime ¶
type Runtime interface {
// Ping checks whether the container daemon is reachable.
Ping(ctx context.Context) error
// PullImage pulls the specified image from the registry.
PullImage(ctx context.Context, imageRef string) error
// HasImage reports whether the given image reference is already present locally.
HasImage(ctx context.Context, imageRef string) (bool, error)
// CreateAndStart creates a new container from spec and starts it.
// Returns the container ID.
CreateAndStart(ctx context.Context, spec Spec) (string, error)
// StopAndRemove stops and removes a container.
StopAndRemove(ctx context.Context, containerID string) error
// StopContainer stops a container without removing it, keeping its filesystem and published ports.
StopContainer(ctx context.Context, containerID string) error
// StartContainer starts a container previously stopped by StopContainer.
StartContainer(ctx context.Context, containerID string) error
// Exec runs cmd inside a running container and waits for it to finish.
// A non-zero exit status is reported in the result, not as an error.
Exec(ctx context.Context, containerID string, cmd []string) (ExecResult, error)
// AcquireWarm returns a warm container from the pool for the given image.
AcquireWarm(ctx context.Context, spec Spec) (*PooledContainer, error)
// ReleaseContainer marks a pooled container as idle.
ReleaseContainer(containerID string) error
// ReapIdleContainers stops and removes containers idle longer than IdleTimeout.
ReapIdleContainers(ctx context.Context)
// StartReaper launches a background goroutine that periodically reaps idle containers.
StartReaper(ctx context.Context, interval time.Duration)
// Close releases resources held by the runtime client.
Close() error
}
Runtime is the container-runtime abstraction used throughout Gopherstack. Both DockerRuntime and PodmanRuntime implement this interface.
func NewRuntime ¶
NewRuntime creates a Runtime using the configured (or auto-detected) container runtime.
The runtime is selected in the following order:
- cfg.Runtime (if non-empty)
- CONTAINER_RUNTIME environment variable
- Defaults to RuntimeDocker
RuntimeAuto probes the Docker socket first, then the Podman socket. Returns ErrUnavailable if the selected runtime is not reachable.
type RuntimeName ¶
type RuntimeName string
RuntimeName identifies which container runtime to use.
const ( // RuntimeDocker selects the Docker daemon. RuntimeDocker RuntimeName = "docker" // RuntimePodman selects the Podman daemon via its Docker-compatible socket. RuntimePodman RuntimeName = "podman" // RuntimeAuto auto-detects the available runtime by probing sockets. RuntimeAuto RuntimeName = "auto" // RuntimeKubernetes runs containers as Pods through the Kubernetes API. RuntimeKubernetes RuntimeName = "kubernetes" )
type Spec ¶
type Spec struct {
Labels map[string]string
// StopTimeoutSecs is the grace period given on stop; nil keeps the runtime default.
StopTimeoutSecs *int
// Archives are unpacked read-only at their Dest before the container starts.
Archives []Archive
Image string
Name string
Network string
WorkingDir string
User string
Platform string
OCIRuntime string
Cmd []string
Mounts []string
Env []string
Entrypoint []string
Ports []string
Tmpfs []string
ExtraHosts []string
DNS []string
GroupAdd []string
CapAdd []string
CapDrop []string
SecurityOpt []string
MemoryBytes int64
// MemoryReservationBytes is the soft memory limit; CPUShares the relative CPU weight (1024 per core).
MemoryReservationBytes int64
NanoCPUs int64
// ReadOnlyRootfs mounts the container's root filesystem read-only.
ReadOnlyRootfs bool
Privileged bool
Unmanaged bool
}
Spec holds the specification for creating a container.
type Stats ¶
type Stats struct {
// CPUTimeNanos is the cumulative CPU time the container has consumed.
CPUTimeNanos uint64
// MemoryBytes is the memory in use, excluding reclaimable page cache.
MemoryBytes uint64
// MemoryPeakBytes is the peak memory the runtime reports, or zero when it does not report one.
MemoryPeakBytes uint64
}
Stats is one sample of a container's resource usage.
type StatsAPIClient ¶
type StatsAPIClient interface {
ContainerStats(ctx context.Context, containerID string) (io.ReadCloser, error)
}
StatsAPIClient is implemented by clients that can sample a container's resource usage.
type StatsReader ¶
StatsReader is implemented by runtimes that can sample a container's resource usage.
type StdinExecer ¶
type StdinExecer interface {
ExecStdin(
ctx context.Context, containerID string, cmd []string, stdin io.Reader, out io.Writer, rows, cols uint,
) (int, error)
}
StdinExecer is implemented by runtimes that can relay standard input to a command; a non-zero rows and cols allocate a terminal of that size whose output is one raw stream.
type StreamExecer ¶
type StreamExecer interface {
// ExecStream runs cmd, writing combined stdout and stderr to out as produced; it returns the exit status.
ExecStream(ctx context.Context, containerID string, cmd []string, out io.Writer) (int, error)
}
StreamExecer is implemented by runtimes that can stream a command's output while it runs.
type TermSize ¶
type TermSize struct{ Cols, Rows uint }
TermSize is a terminal size in character cells.
type VolumeAPIClient ¶
type VolumeAPIClient interface {
VolumeCreate(ctx context.Context, name string, labels map[string]string) error
VolumeRemove(ctx context.Context, name string) error
VolumeListUnused(ctx context.Context, label string) (map[string]time.Time, error)
}
VolumeAPIClient is implemented by clients that can manage named volumes.
type VolumeRuntime ¶
type VolumeRuntime interface {
// CreateVolume creates a labelled named volume; an existing one is reused.
CreateVolume(ctx context.Context, name string, labels map[string]string) error
// RemoveVolume deletes the volume; a missing one is not an error.
RemoveVolume(ctx context.Context, name string) error
// ListUnusedVolumes lists the volumes carrying label (key or key=value) that no container references and that
// are older than olderThan.
ListUnusedVolumes(ctx context.Context, label string, olderThan time.Duration) ([]string, error)
}
VolumeRuntime is implemented by runtimes that can manage named volumes.
type WaitAPIClient ¶
type WaitAPIClient interface {
ContainerWait(
ctx context.Context,
containerID string,
options dockercontainer.WaitOptions,
) dockercontainer.WaitResult
}
WaitAPIClient is implemented by clients that can wait for a container to stop.