gvisor

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTimeout      = 120 * time.Second
	DefaultMemoryMB     = 512
	DefaultMaxPIDs      = 1024
	DefaultMaxOutput    = 10 * 1024 * 1024 // 10 MB
	MaxContainerNameLen = 64
)

Constants

Variables

View Source
var ErrManagerClosed = errors.New("gvisor manager is closed")

ErrManagerClosed is returned by Run() after the manager has been closed.

Functions

func BuildSpec

func BuildSpec(opts ContainerOptions) *ocispec.Spec

BuildSpec constructs an OCI runtime spec from ContainerOptions.

func ValidateResources

func ValidateResources(res ResourceSpec) error

ValidateResources checks that resource limits are sensible.

Types

type CgroupV2Entry

type CgroupV2Entry struct {
	File  string // e.g., "cpu.max"
	Value string // e.g., "200000 100000"
}

CgroupV2Entries returns the cgroup v2 filesystem entries for the given resource spec. This is used for testing and documentation — the actual cgroup setup is done by runsc via the OCI spec.

func ToCgroupV2Entries

func ToCgroupV2Entries(res ResourceSpec) []CgroupV2Entry

ToCgroupV2Entries converts a ResourceSpec to cgroup v2 file entries.

type ContainerOptions

type ContainerOptions struct {
	// Command is the command and arguments to execute.
	Command []string

	// WorkDir is the working directory inside the container.
	// Must be an absolute path within the rootfs.
	WorkDir string

	// Env is the environment variables for the process.
	// If nil, a minimal default environment is used.
	Env map[string]string

	// RootFS is the host path to use as the container's root filesystem.
	// Typically a ZFS dataset mountpoint.
	RootFS string

	// Resources specifies CPU, memory, PID, and timeout limits.
	Resources ResourceSpec

	// Network controls the container's network access.
	// Default: NetworkNone (no network).
	Network NetworkMode

	// Stdin provides input to the container's stdin.
	// If nil, stdin is /dev/null.
	Stdin io.Reader

	// StdoutWriter receives stdout chunks while the command is running.
	// Optional; captured output is still returned in ContainerResult.Stdout.
	StdoutWriter io.Writer

	// StderrWriter receives stderr chunks while the command is running.
	// Optional; captured output is still returned in ContainerResult.Stderr.
	StderrWriter io.Writer

	// User specifies the UID:GID to run the process as inside the container.
	// Default: 0:0 (root).
	User *UserSpec

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

	// ExtraMounts adds additional bind mounts or tmpfs mounts.
	ExtraMounts []Mount
}

ContainerOptions configures a single container execution.

func (ContainerOptions) Validate

func (o ContainerOptions) Validate() error

Validate checks that the options are valid for container creation.

type ContainerResult

type ContainerResult struct {
	ContainerID     string
	ExitCode        int
	Stdout          []byte
	Stderr          []byte
	StdoutTruncated bool
	StderrTruncated bool
	Duration        time.Duration
	BootDuration    time.Duration
	Status          ContainerStatus
	OOMKilled       bool
	PeakMemoryBytes int64
}

ContainerResult holds the outcome of a container execution.

type ContainerStatus

type ContainerStatus string

ContainerStatus indicates how the container exited.

const (
	StatusExited    ContainerStatus = "exited"
	StatusTimedOut  ContainerStatus = "timed_out"
	StatusOOMKilled ContainerStatus = "oom_killed"
	StatusKilled    ContainerStatus = "killed"
	StatusError     ContainerStatus = "error"
)

type GVisorManager

type GVisorManager interface {
	// Run executes a command in a gVisor container with the given resource limits.
	// Returns ContainerResult on successful execution (even if the command
	// exits non-zero). Returns error only for infrastructure failures.
	Run(ctx context.Context, opts ContainerOptions) (*ContainerResult, error)

	// CleanupStale finds and removes any containers that are no longer tracked
	// by the manager (e.g., from a previous crash). Safe to call periodically.
	CleanupStale(ctx context.Context) (int, error)

	// ActiveContainers returns the number of currently running containers.
	ActiveContainers() int

	// Close shuts down the manager. Idempotent and safe for concurrent callers.
	// Marks manager closed immediately; subsequent Run() returns ErrManagerClosed.
	Close() error
}

GVisorManager manages gVisor container lifecycle for Tier 2 tool execution. Each Run() call creates a fresh container, executes the command, captures output, and destroys the container. Thread-safe for concurrent use.

type Manager

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

Manager implements GVisorManager.

func NewManager

func NewManager(config ManagerConfig) (*Manager, error)

NewManager creates a new GVisorManager. It validates the configuration and verifies that runsc is available.

func (*Manager) ActiveContainers

func (m *Manager) ActiveContainers() int

ActiveContainers returns the number of currently running containers.

func (*Manager) CleanupStale

func (m *Manager) CleanupStale(ctx context.Context) (int, error)

CleanupStale finds containers in runsc's state directory that aren't tracked by the manager and removes them. This handles containers leaked by a previous crash of the manager process.

func (*Manager) Close

func (m *Manager) Close() error

Close shuts down the manager. Idempotent and safe for concurrent callers. Marks manager closed immediately; subsequent Run() returns ErrManagerClosed. Cancels in-flight runs, waits up to 5s grace for exit, then force-deletes.

func (*Manager) Run

Run executes a command in a gVisor container with the given resource limits. Container is created, command runs, output is captured, and container is destroyed — all within this call.

type ManagerConfig

type ManagerConfig struct {
	RunscPath               string
	BundleBaseDir           string
	RunscRoot               string
	Platform                string
	MaxConcurrentContainers int
	DefaultNetwork          NetworkMode
	DefaultResources        ResourceSpec
	Logger                  *slog.Logger
	EnableMetrics           bool
}

ManagerConfig configures the GVisorManager.

type Mount

type Mount struct {
	Source      string
	Destination string
	Type        string
	ReadOnly    bool
	Options     []string
}

Mount defines an additional filesystem mount inside the container.

type NetworkMode

type NetworkMode string

NetworkMode controls container network access.

const (
	NetworkNone    NetworkMode = "none"
	NetworkSandbox NetworkMode = "sandbox"
	NetworkHost    NetworkMode = "host"
)

type ResourceSpec

type ResourceSpec struct {
	// CPUs is the number of CPU cores to allocate.
	// 0 means no limit (use all available CPUs).
	CPUs float64

	// MemoryMB is the memory limit in megabytes.
	// 0 means no limit.
	MemoryMB int

	// MaxPIDs is the maximum number of processes.
	// 0 means default (1024).
	MaxPIDs int

	// Timeout is the maximum wall-clock execution time.
	// Enforced via context deadline. 0 means no timeout.
	Timeout time.Duration

	// MaxOutputBytes limits stdout and stderr capture size.
	// 0 means default (10 MB).
	MaxOutputBytes int64
}

ResourceSpec defines resource limits for a container.

type UserSpec

type UserSpec struct {
	UID uint32
	GID uint32
}

UserSpec specifies the user identity inside the container.

Jump to

Keyboard shortcuts

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