Documentation
¶
Overview ¶
Package api provides the internal implementation for the public cc API. It wraps the internal infrastructure to provide a user-friendly interface.
Index ¶
- Variables
- func BuildDockerfileRuntimeConfig(dockerfileContent []byte, opts ...DockerfileOption) (*dockerfile.RuntimeConfig, error)
- func EnsureExecutableIsSigned() error
- func NewDirBuildContext(dir string) (*dockerfile.DirBuildContext, error)
- func SupportsHypervisor() error
- type CacheDir
- type Cmd
- type DockerfileBuildContext
- type DockerfileOption
- type DockerfileRuntimeConfig
- type DownloadProgress
- type Error
- type Exec
- type FS
- type FSLayerOp
- type File
- type FilesystemSnapshot
- type FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) Build(ctx context.Context) (FilesystemSnapshot, error)
- func (f *FilesystemSnapshotFactory) Copy(src, dst string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) CopyReader(r io.Reader, dst string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) Env(env ...string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) Exclude(patterns ...string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) From(imageRef string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) Run(cmd ...string) *FilesystemSnapshotFactory
- func (f *FilesystemSnapshotFactory) SetBuildOptions(opts ...Option)
- func (f *FilesystemSnapshotFactory) WorkDir(dir string) *FilesystemSnapshotFactory
- type FilesystemSnapshotOption
- type GPU
- type Helper
- type ImageConfig
- type Instance
- type InstanceSource
- type Net
- type OCIClient
- type OCIPullOption
- type OCISource
- type Option
- type ProgressCallback
- type PullPolicy
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotRunning = errors.New("instance not running") ErrAlreadyClosed = errors.New("instance already closed") ErrTimeout = errors.New("operation timed out") // This can happen when: // - Running on a platform without hypervisor support // - Missing permissions (e.g., macOS entitlements, Linux /dev/kvm access) // - Running in a VM or container without nested virtualization // // Use errors.Is(err, cc.ErrHypervisorUnavailable) to check and skip tests in CI. ErrHypervisorUnavailable = errors.New("hypervisor unavailable") )
Common sentinel errors.
Functions ¶
func BuildDockerfileRuntimeConfig ¶
func BuildDockerfileRuntimeConfig(dockerfileContent []byte, opts ...DockerfileOption) (*dockerfile.RuntimeConfig, error)
BuildDockerfileRuntimeConfig parses a Dockerfile and returns the runtime configuration (CMD, ENTRYPOINT, USER, etc.) without building the image.
func EnsureExecutableIsSigned ¶
func EnsureExecutableIsSigned() error
EnsureExecutableIsSigned is a no-op on non-Darwin platforms. On macOS, this signs the executable with the hypervisor entitlement and re-execs if necessary.
func NewDirBuildContext ¶
func NewDirBuildContext(dir string) (*dockerfile.DirBuildContext, error)
NewDirBuildContext creates a new directory-based build context.
func SupportsHypervisor ¶
func SupportsHypervisor() error
SupportsHypervisor checks if the hypervisor is available on this system. Returns nil if available, or an error describing why not. Use this for early startup checks to show a friendly error message.
Example:
if err := cc.SupportsHypervisor(); err != nil {
log.Fatal("Hypervisor unavailable:", err)
}
Types ¶
type CacheDir ¶
type CacheDir interface {
// Path returns the resolved cache directory path.
Path() string
// OCIPath returns the path for OCI image cache.
OCIPath() string
// QEMUPath returns the path for QEMU emulation binaries cache.
QEMUPath() string
// SnapshotPath returns the path for filesystem snapshot cache.
SnapshotPath() string
}
CacheDir represents a cache directory configuration. It provides a unified way to configure cache directories for both OCIClient and Instance, ensuring they share the same cache location.
func NewCacheDir ¶
NewCacheDir creates a cache directory config. If path is empty, uses the platform-specific default cache directory.
type Cmd ¶
type Cmd interface {
// Run runs the command.
Run() error
// Start starts the command.
Start() error
// Wait waits for the command to complete.
Wait() error
// Output runs the command and returns its stdout.
Output() ([]byte, error)
// CombinedOutput runs the command and returns its stdout and stderr.
CombinedOutput() ([]byte, error)
// StdinPipe returns a pipe that can be used to write to the command's stdin.
StdinPipe() (io.WriteCloser, error)
// StdoutPipe returns a pipe that can be used to read the command's stdout.
StdoutPipe() (io.ReadCloser, error)
// StderrPipe returns a pipe that can be used to read the command's stderr.
StderrPipe() (io.ReadCloser, error)
// SetStdin sets the command's stdin.
SetStdin(r io.Reader) Cmd
// SetStdout sets the command's stdout.
SetStdout(w io.Writer) Cmd
// SetStderr sets the command's stderr.
SetStderr(w io.Writer) Cmd
// SetDir sets the command's working directory.
SetDir(dir string) Cmd
// SetUser sets the user to run the command as.
SetUser(user string) Cmd
// SetEnv sets a single environment variable (like os.Setenv).
SetEnv(key, value string) Cmd
// GetEnv returns the value of an environment variable (like os.Getenv).
GetEnv(key string) string
// Environ returns a copy of the command's environment variables.
Environ() []string
// ExitCode returns the command's exit code.
ExitCode() int
}
Cmd represents a command ready to be run in the guest.
type DockerfileBuildContext ¶
type DockerfileBuildContext = dockerfile.BuildContext
DockerfileBuildContext is an alias for dockerfile.BuildContext.
type DockerfileOption ¶
type DockerfileOption interface {
IsDockerfileOption()
}
DockerfileOption configures Dockerfile building.
func WithBuildArg ¶
func WithBuildArg(key, value string) DockerfileOption
WithBuildArg sets a build argument (ARG instruction).
func WithBuildContext ¶
func WithBuildContext(ctx dockerfile.BuildContext) DockerfileOption
WithBuildContext sets the build context for COPY/ADD operations.
func WithBuildContextDir ¶
func WithBuildContextDir(dir string) DockerfileOption
WithBuildContextDir creates a build context from a directory path.
func WithDockerfileCacheDir ¶
func WithDockerfileCacheDir(dir string) DockerfileOption
WithDockerfileCacheDir sets the cache directory for filesystem snapshots.
type DockerfileRuntimeConfig ¶
type DockerfileRuntimeConfig = dockerfile.RuntimeConfig
DockerfileRuntimeConfig is an alias for dockerfile.RuntimeConfig.
type DownloadProgress ¶
type DownloadProgress struct {
Current int64 // Bytes downloaded so far
Total int64 // Total bytes to download (-1 if unknown)
Filename string // Name/path being downloaded
// Blob count tracking
BlobIndex int // Index of current blob (0-based)
BlobCount int // Total number of blobs to download
// Speed and ETA tracking
BytesPerSecond float64 // Current download speed in bytes per second
ETA time.Duration // Estimated time remaining (-1 if unknown)
}
DownloadProgress represents the current state of a download. This mirrors the oci.DownloadProgress type for the public API.
type Exec ¶
type Exec interface {
// Command creates a new command.
Command(name string, args ...string) Cmd
// CommandContext creates a new command with the given context.
CommandContext(ctx context.Context, name string, args ...string) Cmd
// EntrypointCommand returns a command preconfigured with the container's
// entrypoint. If args are provided, they replace the image's default CMD.
// If no args are provided, the image's CMD is appended to ENTRYPOINT.
// If neither ENTRYPOINT nor CMD are set, defaults to /bin/sh.
EntrypointCommand(args ...string) Cmd
// EntrypointCommandContext is like EntrypointCommand but accepts a context.
EntrypointCommandContext(ctx context.Context, args ...string) Cmd
// Exec replaces the init process with the specified command (like unix.Exec).
// This is a terminal operation - the command becomes PID 1 and there is
// no parent process waiting. When the command exits, the VM terminates.
Exec(name string, args ...string) error
// ExecContext is like Exec but accepts a context.
ExecContext(ctx context.Context, name string, args ...string) error
}
Exec provides process execution on a guest.
type FS ¶
type FS interface {
// WithContext returns a new FS with the given context.
WithContext(ctx context.Context) FS
// Open opens the named file for reading.
Open(name string) (File, error)
// Create creates or truncates the named file.
Create(name string) (File, error)
// OpenFile opens the named file with the given flags and permissions.
OpenFile(name string, flag int, perm fs.FileMode) (File, error)
// ReadFile reads the named file and returns its contents.
ReadFile(name string) ([]byte, error)
// WriteFile writes the given data to the named file.
WriteFile(name string, data []byte, perm fs.FileMode) error
// Stat returns the FileInfo for the named file.
Stat(name string) (fs.FileInfo, error)
// Lstat returns the FileInfo for the named file.
Lstat(name string) (fs.FileInfo, error)
// Remove removes the named file.
Remove(name string) error
// RemoveAll removes the named file and all its children.
RemoveAll(path string) error
// Mkdir creates the named directory.
Mkdir(name string, perm fs.FileMode) error
// MkdirAll creates the named directory and all its parents.
MkdirAll(path string, perm fs.FileMode) error
// Rename renames the named file.
Rename(oldpath, newpath string) error
// Symlink creates a new symlink.
Symlink(oldname, newname string) error
// Readlink reads the contents of the named symlink.
Readlink(name string) (string, error)
// ReadDir reads the named directory and returns its contents.
ReadDir(name string) ([]fs.DirEntry, error)
// Chmod changes the mode of the named file.
Chmod(name string, mode fs.FileMode) error
// Chown changes the owner and group of the named file.
Chown(name string, uid, gid int) error
// Chtimes changes the access and modification times of the named file.
Chtimes(name string, atime, mtime time.Time) error
// SnapshotFilesystem creates a snapshot of the current filesystem state.
// The snapshot uses COW semantics and can be used as an InstanceSource.
SnapshotFilesystem(opts ...FilesystemSnapshotOption) (FilesystemSnapshot, error)
}
FS provides filesystem operations on a guest.
type FSLayerOp ¶
type FSLayerOp interface {
// CacheKey returns a deterministic key for this operation.
CacheKey() string
// Apply executes the operation on a running instance.
Apply(ctx context.Context, inst Instance) error
}
FSLayerOp represents an operation in the filesystem snapshot factory.
type File ¶
type File interface {
io.Reader
io.Writer
io.Closer
io.Seeker
io.ReaderAt
io.WriterAt
// Stat returns the FileInfo for the named file.
Stat() (fs.FileInfo, error)
// Sync flushes the file to disk.
Sync() error
// Truncate truncates the file to the given size.
Truncate(size int64) error
// Name returns the name of the file.
Name() string
}
File represents an open file in a guest filesystem.
type FilesystemSnapshot ¶
type FilesystemSnapshot interface {
InstanceSource
// CacheKey returns a unique key for this snapshot derived from its
// operation chain. Used for caching and deduplication.
CacheKey() string
// Parent returns the parent snapshot, or nil if this is a base snapshot.
Parent() FilesystemSnapshot
// Close releases resources held by the snapshot.
Close() error
}
FilesystemSnapshot represents a snapshot of a filesystem that can be used as an InstanceSource. It provides COW (copy-on-write) semantics and can be persisted and restored.
Note: Named FilesystemSnapshot (not Snapshot) to reserve Snapshot for future full VM snapshots (memory + devices + filesystem).
func BuildDockerfileSource ¶
func BuildDockerfileSource(ctx context.Context, dockerfileContent []byte, client OCIClient, opts ...DockerfileOption) (FilesystemSnapshot, error)
BuildDockerfileSource builds an InstanceSource from Dockerfile content. It parses the Dockerfile, converts instructions to filesystem operations, and executes them to produce a cached filesystem snapshot.
type FilesystemSnapshotFactory ¶
type FilesystemSnapshotFactory struct {
// contains filtered or unexported fields
}
FilesystemSnapshotFactory builds filesystem snapshots using Dockerfile-like operations.
func NewFilesystemSnapshotFactory ¶
func NewFilesystemSnapshotFactory(client OCIClient, cacheDir string) *FilesystemSnapshotFactory
NewFilesystemSnapshotFactory creates a new factory for building filesystem snapshots.
func (*FilesystemSnapshotFactory) Build ¶
func (f *FilesystemSnapshotFactory) Build(ctx context.Context) (FilesystemSnapshot, error)
Build executes all operations and returns the final filesystem snapshot. It checks the cache for existing snapshots and only executes necessary operations.
func (*FilesystemSnapshotFactory) Copy ¶
func (f *FilesystemSnapshotFactory) Copy(src, dst string) *FilesystemSnapshotFactory
Copy adds a file copy operation from host to guest.
func (*FilesystemSnapshotFactory) CopyReader ¶
func (f *FilesystemSnapshotFactory) CopyReader(r io.Reader, dst string) *FilesystemSnapshotFactory
CopyReader adds a copy operation from an io.Reader to a guest path.
func (*FilesystemSnapshotFactory) Env ¶
func (f *FilesystemSnapshotFactory) Env(env ...string) *FilesystemSnapshotFactory
Env sets environment variables for subsequent Run operations.
func (*FilesystemSnapshotFactory) Exclude ¶
func (f *FilesystemSnapshotFactory) Exclude(patterns ...string) *FilesystemSnapshotFactory
Exclude adds path patterns to exclude from snapshots.
func (*FilesystemSnapshotFactory) From ¶
func (f *FilesystemSnapshotFactory) From(imageRef string) *FilesystemSnapshotFactory
From sets the base image for the snapshot. This must be called first or the chain will fail at build time.
func (*FilesystemSnapshotFactory) Run ¶
func (f *FilesystemSnapshotFactory) Run(cmd ...string) *FilesystemSnapshotFactory
Run adds a command execution operation.
func (*FilesystemSnapshotFactory) SetBuildOptions ¶
func (f *FilesystemSnapshotFactory) SetBuildOptions(opts ...Option)
func (*FilesystemSnapshotFactory) WorkDir ¶
func (f *FilesystemSnapshotFactory) WorkDir(dir string) *FilesystemSnapshotFactory
WorkDir sets the working directory for subsequent Run operations.
type FilesystemSnapshotOption ¶
type FilesystemSnapshotOption interface {
IsFilesystemSnapshotOption()
}
FilesystemSnapshotOption configures a filesystem snapshot operation.
func WithCacheDir ¶
func WithCacheDir(dir string) FilesystemSnapshotOption
WithCacheDir specifies the directory where snapshot layers are stored.
func WithCachePrefix ¶
func WithCachePrefix(prefix string) FilesystemSnapshotOption
WithCachePrefix specifies a prefix for the cache key. This can be used to namespace snapshots.
func WithExcludes ¶
func WithExcludes(patterns ...string) FilesystemSnapshotOption
WithExcludes specifies path patterns to exclude from the snapshot. Patterns use glob-style matching (*, ?, []).
type GPU ¶
type GPU interface {
// SetWindow connects the GPU to a window for rendering.
// The window parameter must be a window.Window from the gowin package.
// Must be called before Poll/Render/Swap.
SetWindow(w any)
// Poll processes window events and forwards input to the guest.
// Returns false if the window was closed.
// Must be called from the main thread.
Poll() bool
// Render renders the current framebuffer to the window.
// Must be called from the main thread.
Render()
// Swap swaps the window buffers.
// Must be called from the main thread.
Swap()
// GetFramebuffer returns the current framebuffer pixels.
// Returns pixels in BGRA format, dimensions, and whether data is valid.
GetFramebuffer() (pixels []byte, width, height uint32, ok bool)
}
GPU provides access to guest display and input devices. When GPU is enabled, the caller is responsible for running the display loop on the main thread using Poll(), Render(), and Swap().
The SetWindow method accepts a window.Window from the gowin package. This is typed as any to avoid exposing internal types in the public API.
type Helper ¶
type Helper interface {
// Pull pulls an OCI image and returns a virtual InstanceSource.
Pull(ctx context.Context, ref string, opts ...OCIPullOption) (InstanceSource, error)
// New creates and starts a new Instance from the given source.
New(source InstanceSource, opts ...Option) (Instance, error)
// Close shuts down the helper connection and process.
Close() error
}
Helper manages a connection to a cc-helper process.
func SpawnHelper ¶
SpawnHelper starts a new cc-helper process and returns a Helper for creating and managing VM instances through it.
type ImageConfig ¶
type ImageConfig struct {
Architecture string // "amd64", "arm64", etc.
Env []string // Environment variables (KEY=VALUE format)
WorkingDir string // Working directory for commands
Entrypoint []string // Container entrypoint
Cmd []string // Container CMD
User string // User specification (e.g., "1000:1000")
Labels map[string]string // OCI labels
}
ImageConfig contains OCI image configuration metadata. This provides access to container runtime settings like environment, entrypoint, and working directory.
func SourceConfig ¶
func SourceConfig(source InstanceSource) *ImageConfig
SourceConfig returns the ImageConfig for a source, or nil if unavailable. This is a convenience function that performs a type assertion to OCISource.
func (*ImageConfig) Command ¶
func (c *ImageConfig) Command(overrideCmd []string) []string
Command returns the combined command to run, merging Entrypoint and Cmd. If overrideCmd is provided, it replaces the default Cmd. Returns the full command suitable for execution.
type Instance ¶
type Instance interface {
FS
Exec
Net
// Close closes the instance.
Close() error
// Wait waits for the instance to complete.
Wait() error
// ID returns the instance's ID.
ID() string
// Done returns a channel that receives an error when the VM exits.
// The channel is closed after the error is sent.
// This allows non-blocking monitoring of VM termination.
Done() <-chan error
// SetConsoleSize updates the virtio-console size so the guest sees
// the correct terminal dimensions. This is a best-effort operation
// (no-op if console is unavailable).
SetConsoleSize(cols, rows int)
// SetNetworkEnabled enables or disables internet access for the VM.
// When disabled, the VM can still communicate with the host netstack
// but cannot reach external networks.
SetNetworkEnabled(enabled bool)
// GPU returns the GPU interface if GPU is enabled, nil otherwise.
// When non-nil, the caller must run the display loop on the main thread.
GPU() GPU
}
Instance represents a running virtual machine.
type InstanceSource ¶
type InstanceSource interface {
IsInstanceSource()
}
InstanceSource is the source for creating a new Instance.
type Net ¶
type Net interface {
// Dial dials the given network and address.
Dial(network, address string) (net.Conn, error)
// DialContext dials the given network and address with the given context.
DialContext(ctx context.Context, network, address string) (net.Conn, error)
// Listen listens for incoming connections on the given network and address.
Listen(network, address string) (net.Listener, error)
// ListenPacket listens for incoming packets on the given network and address.
ListenPacket(network, address string) (net.PacketConn, error)
// Expose exposes a guest network listener on the given host network and address.
Expose(guestNetwork, guestAddress string, host net.Listener) (io.Closer, error)
// Forward forwards a guest network listener to the given host network and address.
Forward(guest net.Listener, hostNetwork, hostAddress string) (io.Closer, error)
}
Net provides network operations on a guest.
type OCIClient ¶
type OCIClient interface {
// Pull pulls the given image and returns an InstanceSource.
Pull(ctx context.Context, imageRef string, opts ...OCIPullOption) (InstanceSource, error)
// LoadFromDir loads a prebaked image from a directory containing
// config.json and layer files (*.idx/*.contents).
LoadFromDir(dir string, opts ...OCIPullOption) (InstanceSource, error)
// LoadFromTar loads an OCI image from a tarball (docker save format).
LoadFromTar(tarPath string, opts ...OCIPullOption) (InstanceSource, error)
// ExportToDir exports an InstanceSource to a directory as prebaked
// config.json and layer files. Only works with OCI-based sources.
ExportToDir(source InstanceSource, dir string) error
// CacheDir returns the cache directory used by this client.
CacheDir() string
}
OCIClient pulls OCI images and converts them to InstanceSources.
func NewOCIClient ¶
NewOCIClient creates a new OCI client for pulling images. Uses the default cache directory (platform-specific user config directory).
func NewOCIClientWithCache ¶
NewOCIClientWithCache creates a new OCI client using the provided CacheDir. This ensures the OCI client uses the same cache location as other components.
type OCIPullOption ¶
type OCIPullOption interface {
IsOCIPullOption()
}
OCIPullOption configures an OCI pull operation.
type OCISource ¶
type OCISource interface {
InstanceSource
Config() *ImageConfig
}
OCISource extends InstanceSource with OCI-specific metadata. Use type assertion or SourceConfig() to access the ImageConfig.
type ProgressCallback ¶
type ProgressCallback func(progress DownloadProgress)
ProgressCallback is called periodically during downloads.
type PullPolicy ¶
type PullPolicy int
PullPolicy determines when images are fetched from the registry.
const ( PullIfNotPresent PullPolicy = iota PullAlways PullNever )