compute

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: Apache-2.0, MIT Imports: 17 Imported by: 0

Documentation

Overview

Package compute orchestrates disposable Incus sandboxes.

Index

Constants

View Source
const (
	// WaitUntilRunning means the guest has reached Running or Ready.
	WaitUntilRunning = "running"
	// WaitUntilAgent means the Incus agent can serve exec and files.
	WaitUntilAgent = "agent"
	// WaitUntilNetwork means at least one NIC has a non-link address.
	WaitUntilNetwork = "network"
	// WaitUntilDesktop means the Driver answers in the guest graphical session.
	WaitUntilDesktop = "desktop"
	// WaitUntilStopped means the guest has reached Stopped.
	WaitUntilStopped = "stopped"
)
View Source
const (

	// BaselineEgressMgmt is the immutable egress drop toward the management VLAN.
	BaselineEgressMgmt = "baseline-egress-mgmt"
	// BaselineEgressOOB is the immutable egress drop toward the OOB VLAN.
	BaselineEgressOOB = "baseline-egress-oob"
)

Variables

View Source
var (
	// ErrNotFound is the adapter sentinel for a missing Incus resource.
	ErrNotFound = errors.New("not found")

	// ErrUnavailable is the adapter sentinel for an unreachable backend.
	ErrUnavailable = errors.New("backend unavailable")
)

Functions

This section is empty.

Types

type ACLRule

type ACLRule struct {
	// ID is the agent-facing rule identifier returned by AddACLRule.
	ID string
	// Direction is ingress or egress.
	Direction string
	// Action is allow, drop, or reject.
	Action string
	// Protocol is tcp, udp, icmp, or empty for any.
	Protocol string
	// Src is an optional CIDR or address.
	Src string
	// Dst is an optional CIDR or address.
	Dst string
	// Port is an optional destination port or range.
	Port string
}

ACLRule is one agent-facing network ACL entry.

type Backend

type Backend interface {
	CreateSandbox(context.Context, Sandbox) error
	ListSandboxes(context.Context) ([]Sandbox, error)
	GetSandbox(context.Context, string) (Sandbox, error)
	ExtendSandbox(context.Context, string, time.Time) (Sandbox, error)
	DeleteSandbox(context.Context, string) error
	BeginCreateInstance(context.Context, CreateInstance) (PendingInstance, error)
	ListInstances(context.Context, string) ([]Instance, error)
	GetInstance(context.Context, Ref) (Instance, error)
	DeleteInstance(context.Context, Ref) error
	Exec(context.Context, ExecRequest, io.Writer, io.Writer) (int64, error)
	OpenExec(context.Context, ExecRequest) (io.ReadWriteCloser, error)
	ListNetworks(context.Context, string) ([]Network, error)
	CreateNetwork(context.Context, string, Network) (Network, error)
	AttachNIC(context.Context, Ref, string, string, string, string) (NIC, error)
	GetNetwork(context.Context, string, string) (Network, error)
	DeleteNetwork(context.Context, string, string) error
	DetachNIC(context.Context, Ref, string) error
	PeerNetworks(context.Context, string, string, string) error
	AddACLRule(context.Context, string, string, ACLRule) (ACLRule, error)
	RemoveACLRule(context.Context, string, string, string) error
	CreateForward(context.Context, string, string, Ref, int64, int64, string) (Forward, error)
	InstanceForward(context.Context, Ref, int64, string) (Forward, error)
	StartInstance(context.Context, Ref, bool) (Instance, error)
	StopInstance(context.Context, Ref, bool) (Instance, error)
	RestartInstance(context.Context, Ref, bool) (Instance, error)
	WaitInstance(context.Context, WaitRequest) (WaitResult, error)
	ReadFile(context.Context, FileReadRequest) (FileReadResult, error)
	ReadBinaryFile(context.Context, Ref, string) (io.ReadCloser, error)
	DeleteFile(context.Context, Ref, string) error
	WriteFile(context.Context, FileWriteRequest) (FileWriteResult, error)
	CreateSnapshot(context.Context, Ref, string) error
	RestoreSnapshot(context.Context, Ref, string) error
	DeleteSnapshot(context.Context, Ref, string) error
	ListSnapshots(context.Context, Ref) ([]Snapshot, error)
	PublishInstance(context.Context, Ref, string) (string, error)
	GetSandboxImage(context.Context, string, string) (CatalogImage, error)
}

Backend is the Incus consumer seam used by Service; it contains only slice-one calls. The adapter imports these value types; compute does not import the adapter.

type Catalog

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

Catalog is an immutable curated image list loaded from Phase 1 YAML.

func LoadCatalog

func LoadCatalog(path string) (*Catalog, error)

LoadCatalog reads a strict schema_version=1 catalog YAML file.

func NewCatalog

func NewCatalog(images []CatalogImage) (*Catalog, error)

NewCatalog validates and freezes a catalog from already parsed entries.

func (*Catalog) Images

func (c *Catalog) Images() []CatalogImage

Images returns a copy of every catalog entry.

func (*Catalog) Lookup

func (c *Catalog) Lookup(name string) (CatalogImage, bool)

Lookup returns a copy of the named catalog entry.

type CatalogImage

type CatalogImage struct {
	// Name is the catalog lookup key.
	Name string
	// OS is the operating system family.
	OS string
	// Version is the guest operating system version.
	Version string
	// Platform identifies the backend.
	Platform string
	// Kind is the default guest kind.
	Kind string
	// Kinds lists supported guest kinds.
	Kinds []string
	// Desktop marks images with desktop tooling.
	Desktop bool
	// Description is optional catalog guidance.
	Description string
	// Reference is the immutable imgoci release or upstream remote alias.
	Reference string
	// Alias names a qualified cluster-local image in the image-build project.
	Alias string
	// Fingerprint is derived during reconciliation, not an image build identity.
	Fingerprint string
	// CPUs is the default CPU count.
	CPUs int64
	// MemoryMB is the default memory limit in MiB.
	MemoryMB int64
	// DiskGB is the default root disk limit in GiB.
	DiskGB int64
}

CatalogImage is an immutable curated image entry.

type CreateInstance

type CreateInstance struct {
	// Ref identifies the new guest.
	Ref Ref
	// Image supplies the reconciled catalog source.
	Image CatalogImage
	// Kind selects a supported guest kind.
	Kind string
	// Network is default, none, or an agent-facing network name.
	Network string
	// Host optionally pins the sandbox's configured member.
	Host string
	// CPUs is the requested CPU count.
	CPUs int64
	// MemoryMB is the memory limit in MiB.
	MemoryMB int64
	// DiskGB is the root disk limit in GiB.
	DiskGB int64
	// Start requests a running rather than stopped guest.
	Start bool
}

CreateInstance specifies a guest after catalog defaults have been resolved.

type ExecRequest

type ExecRequest struct {
	// Ref identifies the guest.
	Ref Ref
	// Argv is a native argument vector; shell callers use sh -c or cmd.exe /c.
	Argv []string
	// User is a Linux numeric UID; Windows exec uses the agent service identity.
	User string
	// Cwd is the optional absolute guest working directory.
	Cwd string
	// Env contains parsed KEY=VALUE entries.
	Env map[string]string
	// Stdin is the bounded input string.
	Stdin string
	// Timeout is the exec-only budget; request cancellation still wins.
	Timeout time.Duration
}

ExecRequest is a bounded guest shell invocation.

type ExecResult

type ExecResult struct {
	// ExitCode is the guest process exit status, or -1 on timeout.
	ExitCode int64
	// Stdout contains at most 64 KiB of standard output.
	Stdout string
	// Stderr contains at most 64 KiB of standard error.
	Stderr string
	// StdoutTruncated reports discarded standard output bytes.
	StdoutTruncated bool
	// StderrTruncated reports discarded standard error bytes.
	StderrTruncated bool
	// TimedOut reports an exec-only deadline, not caller cancellation.
	TimedOut bool
}

ExecResult separates process exit from exec-only timeout.

type FileReadRequest

type FileReadRequest struct {
	// Ref identifies the guest.
	Ref Ref
	// Path is an absolute guest path.
	Path string
	// MaxBytes is the read cap; zero selects 64 KiB.
	MaxBytes int64
}

FileReadRequest is a bounded guest file read.

type FileReadResult

type FileReadResult struct {
	// Content contains at most MaxBytes of file data.
	Content string
	// Truncated reports discarded trailing bytes.
	Truncated bool
}

FileReadResult is truncated text content.

type FileWriteRequest

type FileWriteRequest struct {
	// Ref identifies the guest.
	Ref Ref
	// Path is an absolute guest path.
	Path string
	// Content is the exact text to write.
	Content string
	// Mode is an optional octal mode such as 0644.
	Mode string
}

FileWriteRequest is a bounded guest file write.

type FileWriteResult

type FileWriteResult struct {
	// Bytes is the number of content bytes written.
	Bytes int64
}

FileWriteResult reports how many bytes were written.

type Forward

type Forward struct {
	// Address is the listen address on the uplink range.
	Address string
	// Port is the listen port.
	Port int64
	// Protocol is tcp or udp.
	Protocol string
	// Network is the agent-facing network name.
	Network string
	// Instance is the target instance name.
	Instance string
}

Forward is a listen address allocated from the uplink OVN range.

type Impairment

type Impairment struct {
	// LatencyMS is added delay in milliseconds.
	LatencyMS int64
	// JitterMS is delay variation and requires LatencyMS.
	JitterMS int64
	// LossPercent is packet loss percent.
	LossPercent float64
	// RateMbit is a rate limit in Mbit/s.
	RateMbit int64
	// Clear removes existing impairment on the NIC.
	Clear bool
}

Impairment is in-guest tc netem configuration for one NIC.

type Instance

type Instance struct {
	// Ref identifies the instance.
	Ref Ref
	// Image is the catalog name used to create the guest.
	Image string
	// OS is the guest operating system recorded by Incus image metadata.
	OS string
	// Kind is container or vm.
	Kind string
	// Host is the actual member.
	Host string
	// Status is the observed Incus state.
	Status string
	// CPUs is the configured CPU count.
	CPUs int64
	// MemoryMB is the configured memory in MiB.
	MemoryMB int64
	// DiskGB is the root disk limit in GiB.
	DiskGB int64
	// Desktop marks desktop-capable images.
	Desktop bool
	// NICs contains observed network devices.
	NICs []NIC
	// Snapshots contains guest snapshot names.
	Snapshots []string
}

Instance describes observed guest state.

type NIC

type NIC struct {
	// Name is the configured device name used by network operations.
	Name string
	// GuestName is the observed OS interface name, which may differ on VMs.
	GuestName string
	// Network is the metadata-resolved agent-facing network name.
	Network string
	// MAC is the observed hardware address.
	MAC string
	// Addresses contains observed guest IP addresses.
	Addresses []string
}

NIC describes an attached interface using agent-facing network names.

type Network

type Network struct {
	// Name is the agent-facing network name.
	Name string
	// PhysicalName is the opaque Incus bridge identifier, never exposed in DTOs.
	PhysicalName string
	// Project is the Incus project containing the managed network.
	Project string
	// Kind is bridge or ovn.
	Kind string
	// CIDR is the configured network prefix.
	CIDR string
	// Gateway is the bridge gateway address, if any.
	Gateway string
	// Host identifies the sandbox's member-local L2 domain.
	Host string
	// DHCP enables address assignment.
	DHCP bool
	// NAT enables outbound translation.
	NAT bool
	// DNS enables DNS service.
	DNS bool
}

Network holds logical identity separately from the physical bridge name.

type Options

type Options struct {
	// Host is the member used to pin bridge-backed sandboxes.
	Host string
	// DefaultTTL is used when create or extend omits a TTL. Zero selects 240 minutes.
	DefaultTTL time.Duration
	// MaxTTL is the upper bound for create and extend. Zero selects 1440 minutes.
	MaxTTL time.Duration
	// DefaultNetworkKind selects ovn or bridge for new sandboxes. Empty selects ovn.
	DefaultNetworkKind string
	// Logger receives operational logs. Nil selects a no-op logger.
	Logger *slog.Logger
	// OnSandboxExpired purges transient artifacts once a sandbox is expired.
	OnSandboxExpired func(string)
	// OnReap expires transient artifacts before each backend reaper scan.
	OnReap func()
	// DesktopReady probes the guest session after Incus agent readiness.
	DesktopReady func(context.Context, Ref) (bool, error)
}

Options configures a compute Service.

type PendingInstance

type PendingInstance interface {
	Wait(context.Context) (Instance, error)
}

PendingInstance represents an accepted create, whose wait does not hold the mutation gate.

type Ref

type Ref struct {
	// Sandbox is the agent-facing sandbox name.
	Sandbox string
	// Name is the instance name within the project.
	Name string
}

Ref identifies an instance within a sandbox.

type Sandbox

type Sandbox struct {
	// Name is the agent-facing lifecycle unit.
	Name string
	// Platform identifies the compute backend.
	Platform string
	// Subject records the creator without enforcing ownership policy.
	Subject string
	// Host is the member shared by this sandbox's bridge-backed instances.
	Host string
	// NetworkKind records the default fabric; empty denotes a legacy bridge sandbox.
	NetworkKind string
	// CreatedAt is the original creation time.
	CreatedAt time.Time
	// ExpiresAt is the persisted reaper deadline.
	ExpiresAt time.Time
}

Sandbox is persistent project metadata discovered from Incus.

type Service

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

Service orchestrates sandboxes against a Backend and an immutable catalog.

func New

func New(backend Backend, catalog *Catalog, opts Options) (*Service, error)

New constructs a Service. Bridge defaults require Host; zero TTLs select the documented defaults.

func (*Service) AddACLRule

func (s *Service) AddACLRule(ctx context.Context, sandbox, network string, rule ACLRule) (ACLRule, error)

AddACLRule appends a network-scoped rule without allowing baseline overrides.

func (*Service) AttachNIC

func (s *Service) AttachNIC(ctx context.Context, ref Ref, network, nic, ip, mac string) (NIC, error)

AttachNIC attaches an instance to a metadata-resolved network.

func (*Service) CatalogImage

func (s *Service) CatalogImage(name string) (CatalogImage, error)

CatalogImage returns the named catalog entry.

func (*Service) CreateForward

func (s *Service) CreateForward(
	ctx context.Context,
	sandbox, network string,
	ref Ref,
	port, listenPort int64,
	protocol string,
) (Forward, error)

CreateForward exposes an instance port on a reused or newly allocated uplink address.

func (*Service) CreateInstance

func (s *Service) CreateInstance(ctx context.Context, req CreateInstance) (Instance, error)

CreateInstance accepts the guest under the sandbox gate, then waits without holding it.

func (*Service) CreateNetwork

func (s *Service) CreateNetwork(ctx context.Context, sandbox string, network Network) (Network, error)

CreateNetwork creates an additional agent-facing network in a live sandbox.

func (*Service) CreateSandbox

func (s *Service) CreateSandbox(ctx context.Context, name string, ttl time.Duration, subject string) (Sandbox, error)

CreateSandbox creates a sandbox project, generating an adjective-noun name when name is empty.

func (*Service) CreateSnapshot

func (s *Service) CreateSnapshot(ctx context.Context, ref Ref, snapshot string) error

CreateSnapshot creates a named instance snapshot.

func (*Service) DeleteFile

func (s *Service) DeleteFile(ctx context.Context, ref Ref, path string) error

DeleteFile removes a guest file for an internal consumer. Missing files retain os.ErrNotExist. Live sandbox expiry is checked.

func (*Service) DeleteInstance

func (s *Service) DeleteInstance(ctx context.Context, ref Ref) error

DeleteInstance removes a guest under the sandbox gate.

func (*Service) DeleteNetwork

func (s *Service) DeleteNetwork(ctx context.Context, sandbox, name string) error

DeleteNetwork deletes a network that has no attached NICs.

func (*Service) DeleteSandbox

func (s *Service) DeleteSandbox(ctx context.Context, name string) error

DeleteSandbox marks expiry as now, then deletes; a partial failure is retried by the reaper.

func (*Service) DeleteSnapshot

func (s *Service) DeleteSnapshot(ctx context.Context, ref Ref, snapshot string) error

DeleteSnapshot deletes a named instance snapshot.

func (*Service) DetachNIC

func (s *Service) DetachNIC(ctx context.Context, ref Ref, nic string) error

DetachNIC removes a NIC under the sandbox gate.

func (*Service) Exec

func (s *Service) Exec(ctx context.Context, req ExecRequest) (ExecResult, error)

Exec runs a bounded command without holding the mutation gate.

func (*Service) ExecJSON

func (s *Service) ExecJSON(ctx context.Context, req ExecRequest) (ExecResult, error)

ExecJSON runs a guest argv with a 4 MiB output bound and rejects truncation. It uses the same draining, deadline, and cancellation path as Exec.

func (*Service) ExtendSandbox

func (s *Service) ExtendSandbox(ctx context.Context, name string, ttl time.Duration) (Sandbox, error)

ExtendSandbox writes expires_at = now + ttl after re-reading expiry under the gate.

func (*Service) GetInstance

func (s *Service) GetInstance(ctx context.Context, ref Ref) (Instance, error)

GetInstance returns one guest, mapping misses to an agent-facing not-found error.

func (*Service) GetNetwork

func (s *Service) GetNetwork(ctx context.Context, sandbox, name string) (Network, error)

GetNetwork returns one agent-facing network.

func (*Service) GetSandbox

func (s *Service) GetSandbox(ctx context.Context, name string) (Sandbox, []Instance, []Network, error)

GetSandbox returns the sandbox together with its instances and networks.

func (*Service) ImpairNIC

func (s *Service) ImpairNIC(ctx context.Context, ref Ref, nic string, impairment Impairment) error

ImpairNIC applies Linux-only tc netem settings inside a guest. It is not gated.

func (*Service) InstanceForward

func (s *Service) InstanceForward(ctx context.Context, ref Ref, targetPort int64, protocol string) (Forward, error)

InstanceForward finds an existing scalar port forward to a guest. An empty Address means no matching forward; this method never exposes a port.

func (*Service) ListImages

func (s *Service) ListImages(osName string, desktop *bool, platform string) []CatalogImage

ListImages returns catalog entries matching the optional filters.

func (*Service) ListInstances

func (s *Service) ListInstances(ctx context.Context, sandbox string) ([]Instance, error)

ListInstances returns guests in the named sandbox.

func (*Service) ListNetworks

func (s *Service) ListNetworks(ctx context.Context, sandbox string) ([]Network, error)

ListNetworks returns agent-facing networks in a sandbox.

func (*Service) ListSandboxes

func (s *Service) ListSandboxes(ctx context.Context) ([]Sandbox, error)

ListSandboxes returns every owned sandbox discovered from the backend.

func (*Service) ListSnapshots

func (s *Service) ListSnapshots(ctx context.Context, ref Ref) ([]Snapshot, error)

ListSnapshots returns snapshots for one guest.

func (*Service) OpenExec

func (s *Service) OpenExec(ctx context.Context, req ExecRequest) (io.ReadWriteCloser, error)

OpenExec starts a guest command and returns attached stdin/stdout. The caller must Close the stream. The start context does not bound a successful stream; Close and process death do. Live sandbox expiry is checked at open.

func (*Service) PeerNetworks

func (s *Service) PeerNetworks(ctx context.Context, sandbox, network, peer string) error

PeerNetworks routes between two OVN networks in a sandbox.

func (*Service) PublishInstance

func (s *Service) PublishInstance(ctx context.Context, ref Ref, image string) (string, error)

PublishInstance publishes a sandbox-scoped image from a guest.

func (*Service) ReadBinaryFile

func (s *Service) ReadBinaryFile(ctx context.Context, ref Ref, path string) (io.ReadCloser, time.Time, error)

ReadBinaryFile opens a guest file for bounded streaming by an internal consumer. Missing files retain os.ErrNotExist so optional screenshots need no text parsing. The returned expiry is the live sandbox timestamp from the same check, so callers can publish without a second control-plane round trip.

func (*Service) ReadFile

func (s *Service) ReadFile(ctx context.Context, req FileReadRequest) (FileReadResult, error)

ReadFile returns a bounded guest file.

func (*Service) Reap

func (s *Service) Reap(ctx context.Context) error

Reap deletes expired sandboxes. A failed delete leaves the project in place for the next scan.

func (*Service) RemoveACLRule

func (s *Service) RemoveACLRule(ctx context.Context, sandbox, network, rule string) error

RemoveACLRule deletes an agent ACL rule; baseline IDs are not removable.

func (*Service) ResolveImage

func (s *Service) ResolveImage(ctx context.Context, sandbox, name string) (CatalogImage, error)

ResolveImage returns a curated catalog entry or a sandbox-published image.

func (*Service) RestartInstance

func (s *Service) RestartInstance(ctx context.Context, ref Ref, force bool) (Instance, error)

RestartInstance restarts a guest and blocks until it is running.

func (*Service) RestoreSnapshot

func (s *Service) RestoreSnapshot(ctx context.Context, ref Ref, snapshot string) error

RestoreSnapshot restores a guest from a snapshot.

func (*Service) RunReaper

func (s *Service) RunReaper(ctx context.Context) error

RunReaper deletes expired sandboxes at startup and every 30 seconds until ctx ends.

func (*Service) SandboxExpiry

func (s *Service) SandboxExpiry(ctx context.Context, name string) (time.Time, error)

SandboxExpiry reads live metadata without taking the control-plane mutation gate.

func (*Service) StartInstance

func (s *Service) StartInstance(ctx context.Context, ref Ref, force bool) (Instance, error)

StartInstance starts a guest and blocks until it is running.

func (*Service) StopInstance

func (s *Service) StopInstance(ctx context.Context, ref Ref, force bool) (Instance, error)

StopInstance stops a guest and blocks until it is stopped.

func (*Service) WaitInstance

func (s *Service) WaitInstance(ctx context.Context, req WaitRequest) (WaitResult, error)

WaitInstance polls until a readiness stage or the wait budget expires.

func (*Service) WriteFile

func (s *Service) WriteFile(ctx context.Context, req FileWriteRequest) (FileWriteResult, error)

WriteFile writes a bounded guest file.

type Snapshot

type Snapshot struct {
	// Name is the agent-facing snapshot name.
	Name string
	// CreatedAt is the snapshot creation time.
	CreatedAt time.Time
}

Snapshot is a named instance snapshot.

type WaitRequest

type WaitRequest struct {
	// Ref identifies the guest.
	Ref Ref
	// Until is running, agent, network, desktop, or stopped.
	Until string
	// Timeout is the wait-only budget; request cancellation still wins.
	Timeout time.Duration
}

WaitRequest is a bounded readiness poll.

type WaitResult

type WaitResult struct {
	// Status is the observed Incus state.
	Status string
	// Elapsed is time spent waiting.
	Elapsed time.Duration
}

WaitResult is the observed state after a wait.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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