docker

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package docker provides a backend that executes code in Docker containers with configurable security profiles and resource limits.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDockerNotAvailable is returned when Docker is not available.
	ErrDockerNotAvailable = errors.New("docker not available")

	// ErrImageNotFound is returned when the execution image is not found.
	ErrImageNotFound = errors.New("docker image not found")

	// ErrContainerFailed is returned when container creation/execution fails.
	ErrContainerFailed = errors.New("container execution failed")

	// ErrClientNotConfigured is returned when no ContainerRunner is configured.
	ErrClientNotConfigured = errors.New("docker client not configured")

	// ErrContainerCreate is returned when container creation fails.
	ErrContainerCreate = errors.New("container creation failed")

	// ErrContainerStart is returned when container start fails.
	ErrContainerStart = errors.New("container start failed")

	// ErrContainerWait is returned when waiting for container completion fails.
	ErrContainerWait = errors.New("container wait failed")

	// ErrImagePull is returned when image pull fails.
	ErrImagePull = errors.New("image pull failed")

	// ErrDaemonUnavailable is returned when the Docker daemon is not reachable.
	ErrDaemonUnavailable = errors.New("docker daemon unavailable")

	// ErrResourceLimit is returned when a resource limit is exceeded.
	ErrResourceLimit = errors.New("resource limit exceeded")

	// ErrSecurityViolation is returned when a security policy is violated.
	ErrSecurityViolation = errors.New("security policy violation")
)

Errors for Docker backend operations.

Functions

This section is empty.

Types

type Backend

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

Backend executes code in Docker containers with security isolation.

func New

func New(cfg Config) *Backend

New creates a new Docker backend with the given configuration.

func (*Backend) Execute

Execute runs code in a Docker container with security isolation.

func (*Backend) Kind

func (b *Backend) Kind() runtime.BackendKind

Kind returns the backend kind identifier.

type ClientError

type ClientError struct {
	// Op is the operation that failed: "create", "start", "wait", "pull".
	Op string

	// Image is the image reference.
	Image string

	// ContainerID is the container ID if available.
	ContainerID string

	// Err is the underlying error.
	Err error
}

ClientError wraps client operation errors with context.

func (*ClientError) Error

func (e *ClientError) Error() string

func (*ClientError) Unwrap

func (e *ClientError) Unwrap() error

type Config

type Config struct {
	// ImageName is the Docker image to use for execution.
	// Default: toolruntime-sandbox:latest
	ImageName string

	// SeccompPath is the path to a custom seccomp profile for hardened mode.
	SeccompPath string

	// Client is the container runner implementation.
	// If nil, Execute() returns ErrClientNotConfigured.
	Client ContainerRunner

	// ImageResolver optionally resolves/pulls images before execution.
	// If nil, images are assumed to exist locally.
	ImageResolver ImageResolver

	// HealthChecker optionally verifies daemon health before execution.
	// If nil, health checks are skipped.
	HealthChecker HealthChecker

	// Logger is an optional logger for backend events.
	Logger Logger
}

Config configures a Docker backend.

type ContainerOptions

type ContainerOptions struct {
	// NetworkDisabled disables network access.
	NetworkDisabled bool

	// ReadOnlyRootfs makes the root filesystem read-only.
	ReadOnlyRootfs bool

	// MemoryLimit is the memory limit in bytes.
	MemoryLimit int64

	// CPUQuota is the CPU quota in microseconds.
	CPUQuota int64

	// PidsLimit is the maximum number of processes.
	PidsLimit int64

	// SeccompProfile is the path to a seccomp profile.
	SeccompProfile string

	// User is the user to run as (non-root).
	User string
}

ContainerOptions represents container configuration for execution.

type ContainerResult

type ContainerResult struct {
	// ExitCode is the container's exit code.
	ExitCode int

	// Stdout contains the container's stdout output.
	Stdout string

	// Stderr contains the container's stderr output.
	Stderr string

	// Duration is the execution time.
	Duration time.Duration
}

ContainerResult captures the output of container execution.

type ContainerRunner

type ContainerRunner interface {
	// Run executes code in a container and returns the result.
	// The container lifecycle (create, start, wait, remove) is atomic.
	//
	// The implementation must:
	//   - Validate the spec before execution
	//   - Respect ctx cancellation
	//   - Respect spec.Timeout if set
	//   - Capture stdout and stderr
	//   - Return the exit code
	//   - Clean up the container on completion or error
	Run(ctx context.Context, spec ContainerSpec) (ContainerResult, error)
}

ContainerRunner is the primary interface for container execution. Implementations may use Docker SDK, containerd, testcontainers, or mocks.

The interface is intentionally minimal following Go best practices: "The bigger the interface, the weaker the abstraction."

Implementations are expected to:

  • Create a container from the spec
  • Start and wait for container completion
  • Capture stdout/stderr
  • Remove the container after execution
  • Respect context cancellation and spec timeout

type ContainerSpec

type ContainerSpec struct {
	// Image is the Docker image reference (required).
	Image string

	// Command is the command to execute.
	Command []string

	// WorkingDir is the working directory inside the container.
	WorkingDir string

	// Env contains environment variables in KEY=value format.
	Env []string

	// Mounts defines volume mounts for the container.
	Mounts []Mount

	// Resources defines resource limits.
	Resources ResourceSpec

	// Security defines security settings.
	Security SecuritySpec

	// Timeout is the maximum execution duration.
	Timeout time.Duration

	// Labels are container labels for tracking.
	Labels map[string]string
}

ContainerSpec defines what to run in a container and how.

func (ContainerSpec) Validate

func (s ContainerSpec) Validate() error

Validate checks ContainerSpec for errors before execution.

type DaemonInfo

type DaemonInfo struct {
	// Version is the daemon version.
	Version string

	// APIVersion is the API version.
	APIVersion string

	// OS is the daemon operating system.
	OS string

	// Architecture is the daemon CPU architecture.
	Architecture string

	// RootDir is the daemon's root directory.
	RootDir string
}

DaemonInfo contains Docker daemon metadata.

type HealthChecker

type HealthChecker interface {
	// Ping checks if the Docker daemon is responsive.
	Ping(ctx context.Context) error

	// Info returns daemon information (version, OS, etc.).
	Info(ctx context.Context) (DaemonInfo, error)
}

HealthChecker verifies Docker daemon availability. This is an optional interface - backends may skip health checks.

type ImageResolver

type ImageResolver interface {
	// Resolve ensures the image is available locally.
	// Returns the resolved image reference (may include digest).
	// If the image doesn't exist locally, it will be pulled.
	Resolve(ctx context.Context, image string) (string, error)
}

ImageResolver checks if an image exists locally and pulls if needed. This is an optional interface - backends may assume images are pre-pulled.

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the interface for logging.

Contract: - Concurrency: implementations must be safe for concurrent use. - Errors: logging must be best-effort and must not panic.

type Mount

type Mount struct {
	// Type specifies the mount type: "bind", "volume", or "tmpfs".
	Type MountType

	// Source is the host path (bind) or volume name (volume).
	// Ignored for tmpfs mounts.
	Source string

	// Target is the path inside the container.
	Target string

	// ReadOnly mounts the volume as read-only.
	ReadOnly bool

	// Consistency is the mount consistency mode: "consistent", "cached", "delegated".
	// Only relevant for bind mounts on macOS.
	Consistency string
}

Mount defines a volume mount for a container.

func (Mount) Validate

func (m Mount) Validate() error

Validate checks Mount for required fields.

type MountType

type MountType string

MountType defines the type of volume mount.

const (
	// MountTypeBind mounts a host path into the container.
	MountTypeBind MountType = "bind"

	// MountTypeVolume mounts a Docker volume.
	MountTypeVolume MountType = "volume"

	// MountTypeTmpfs mounts a tmpfs (in-memory) filesystem.
	MountTypeTmpfs MountType = "tmpfs"
)

type ResourceSpec

type ResourceSpec struct {
	// MemoryBytes is the memory limit in bytes.
	// Zero means unlimited.
	MemoryBytes int64

	// CPUQuota is the CPU quota in microseconds per 100ms period.
	// Zero means unlimited.
	CPUQuota int64

	// PidsLimit is the maximum number of processes.
	// Zero means unlimited.
	PidsLimit int64

	// DiskBytes is the disk limit in bytes.
	// Zero means unlimited. Not all runtimes support this.
	DiskBytes int64
}

ResourceSpec defines container resource limits.

func (ResourceSpec) Validate

func (r ResourceSpec) Validate() error

Validate checks ResourceSpec for invalid values.

type SecuritySpec

type SecuritySpec struct {
	// User is the user to run as (e.g., "nobody:nogroup").
	User string

	// ReadOnlyRootfs mounts the root filesystem as read-only.
	ReadOnlyRootfs bool

	// NetworkMode is the network mode: "none", "bridge", "host".
	// "host" is not allowed in sandbox contexts.
	NetworkMode string

	// SeccompProfile is the path to a seccomp profile.
	// Empty uses the runtime's default profile.
	SeccompProfile string

	// Privileged grants extended privileges to the container.
	// Must always be false in sandbox contexts.
	Privileged bool
}

SecuritySpec defines container security settings.

func (SecuritySpec) Validate

func (s SecuritySpec) Validate() error

Validate checks SecuritySpec for policy violations.

type SpecBuilder

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

SpecBuilder constructs ContainerSpec with validation.

func NewSpecBuilder

func NewSpecBuilder(image string) *SpecBuilder

NewSpecBuilder creates a builder for ContainerSpec.

func (*SpecBuilder) Build

func (b *SpecBuilder) Build() (ContainerSpec, error)

Build validates and returns the ContainerSpec.

func (*SpecBuilder) MustBuild

func (b *SpecBuilder) MustBuild() ContainerSpec

MustBuild validates and returns the ContainerSpec, panicking on error. Use only in tests or when the spec is known to be valid.

func (*SpecBuilder) WithBindMount

func (b *SpecBuilder) WithBindMount(source, target string, readOnly bool) *SpecBuilder

WithBindMount adds a bind mount from host to container.

func (*SpecBuilder) WithCPU

func (b *SpecBuilder) WithCPU(quota int64) *SpecBuilder

WithCPU sets the CPU quota in microseconds.

func (*SpecBuilder) WithCommand

func (b *SpecBuilder) WithCommand(cmd ...string) *SpecBuilder

WithCommand sets the command to execute.

func (*SpecBuilder) WithEnv

func (b *SpecBuilder) WithEnv(key, value string) *SpecBuilder

WithEnv adds an environment variable.

func (*SpecBuilder) WithEnvs

func (b *SpecBuilder) WithEnvs(envs []string) *SpecBuilder

WithEnvs adds multiple environment variables from a slice.

func (*SpecBuilder) WithLabel

func (b *SpecBuilder) WithLabel(key, value string) *SpecBuilder

WithLabel adds a container label.

func (*SpecBuilder) WithLabels

func (b *SpecBuilder) WithLabels(labels map[string]string) *SpecBuilder

WithLabels merges labels into the spec.

func (*SpecBuilder) WithMemory

func (b *SpecBuilder) WithMemory(bytes int64) *SpecBuilder

WithMemory sets the memory limit in bytes.

func (*SpecBuilder) WithMount

func (b *SpecBuilder) WithMount(m Mount) *SpecBuilder

WithMount adds a volume mount.

func (*SpecBuilder) WithNetworkMode

func (b *SpecBuilder) WithNetworkMode(mode string) *SpecBuilder

WithNetworkMode sets the network mode.

func (*SpecBuilder) WithNoNetwork

func (b *SpecBuilder) WithNoNetwork() *SpecBuilder

WithNoNetwork disables network access.

func (*SpecBuilder) WithPidsLimit

func (b *SpecBuilder) WithPidsLimit(limit int64) *SpecBuilder

WithPidsLimit sets the maximum number of processes.

func (*SpecBuilder) WithReadOnlyRootfs

func (b *SpecBuilder) WithReadOnlyRootfs(readOnly bool) *SpecBuilder

WithReadOnlyRootfs sets the root filesystem to read-only.

func (*SpecBuilder) WithResources

func (b *SpecBuilder) WithResources(r ResourceSpec) *SpecBuilder

WithResources sets the resource limits.

func (*SpecBuilder) WithSeccompProfile

func (b *SpecBuilder) WithSeccompProfile(path string) *SpecBuilder

WithSeccompProfile sets the seccomp profile path.

func (*SpecBuilder) WithSecurity

func (b *SpecBuilder) WithSecurity(s SecuritySpec) *SpecBuilder

WithSecurity sets the security specification.

func (*SpecBuilder) WithTimeout

func (b *SpecBuilder) WithTimeout(d time.Duration) *SpecBuilder

WithTimeout sets the execution timeout.

func (*SpecBuilder) WithTmpfs

func (b *SpecBuilder) WithTmpfs(target string) *SpecBuilder

WithTmpfs adds a tmpfs mount at the given target.

func (*SpecBuilder) WithUser

func (b *SpecBuilder) WithUser(user string) *SpecBuilder

WithUser sets the user to run as.

func (*SpecBuilder) WithWorkingDir

func (b *SpecBuilder) WithWorkingDir(dir string) *SpecBuilder

WithWorkingDir sets the working directory inside the container.

type StreamEvent

type StreamEvent struct {
	// Type identifies the event type.
	Type StreamEventType

	// Data contains the event payload (stdout/stderr bytes).
	Data []byte

	// ExitCode is set when Type is StreamEventExit.
	ExitCode int

	// Error is set when Type is StreamEventError.
	Error error
}

StreamEvent represents a streaming output event from container execution.

type StreamEventType

type StreamEventType string

StreamEventType identifies the type of streaming event.

const (
	// StreamEventStdout indicates stdout data.
	StreamEventStdout StreamEventType = "stdout"

	// StreamEventStderr indicates stderr data.
	StreamEventStderr StreamEventType = "stderr"

	// StreamEventExit indicates container exit.
	StreamEventExit StreamEventType = "exit"

	// StreamEventError indicates an error occurred.
	StreamEventError StreamEventType = "error"
)

type StreamRunner

type StreamRunner interface {
	ContainerRunner

	// RunStream executes and streams stdout/stderr as events.
	// The returned channel is closed when execution completes.
	// Callers should drain the channel to receive the exit event.
	RunStream(ctx context.Context, spec ContainerSpec) (<-chan StreamEvent, error)
}

StreamRunner provides streaming execution for long-running containers. This is an optional extension to ContainerRunner.

Jump to

Keyboard shortcuts

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