truenas

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package truenas implements the sandbox.Sandbox interface using TrueNAS Incus containers via the WebSocket API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Virt       truenas.VirtServiceAPI
	Snapshot   truenas.SnapshotServiceAPI
	Interface  truenas.InterfaceServiceAPI
	Network    truenas.NetworkServiceAPI
	Filesystem truenas.FilesystemServiceAPI
	Cron       truenas.CronServiceAPI
	// contains filtered or unexported fields
}

Client wraps a truenas-go WebSocket client and its typed services.

func (*Client) Close

func (c *Client) Close() error

func (*Client) ContainerDataset

func (c *Client) ContainerDataset(ctx context.Context, name string) (string, error)

ContainerDataset returns the ZFS dataset path for a container by name.

func (*Client) CreateInstance

func (c *Client) CreateInstance(ctx context.Context, opts CreateInstanceOpts) (*truenas.VirtInstance, error)

CreateInstance creates an Incus container via the Virt service.

func (*Client) DefaultNIC

func (c *Client) DefaultNIC(ctx context.Context) (*NICOpts, error)

DefaultNIC discovers the host's gateway interface and returns NIC options suitable for container creation.

func (*Client) ListInstances

func (c *Client) ListInstances(ctx context.Context) ([]truenas.VirtInstance, error)

ListInstances queries all Incus instances with the px- prefix.

func (*Client) ListSnapshots

func (c *Client) ListSnapshots(ctx context.Context, dataset string) ([]truenas.Snapshot, error)

ListSnapshots queries snapshots for the given ZFS dataset.

func (*Client) Provision

func (c *Client) Provision(ctx context.Context, name string, opts ProvisionOpts) error

Provision writes SSH keys, rc.local for openssh-server install, dev tools setup, and optional DNS/env config into a running container's rootfs via file_receive.

func (*Client) ReplaceContainerRootfs

func (c *Client) ReplaceContainerRootfs(ctx context.Context, containerName, snapshotID string) error

ReplaceContainerRootfs destroys the container's ZFS dataset and clones the checkpoint snapshot in its place. The container must be stopped.

func (*Client) SnapshotRollback

func (c *Client) SnapshotRollback(ctx context.Context, snapshotID string) error

SnapshotRollback rolls back to the given snapshot ID (dataset@name).

func (*Client) StopInstanceIfRunning added in v0.6.0

func (c *Client) StopInstanceIfRunning(ctx context.Context, name string, opts truenas.StopVirtInstanceOpts) error

StopInstanceIfRunning stops the named instance only if its current status is RUNNING. No-ops on any other status (STOPPED, FROZEN, etc.) so callers don't need to know the prior state. Returns nil if the instance can't be found — callers in cleanup paths shouldn't error on a missing target.

func (*Client) WriteAuthorizedKey

func (c *Client) WriteAuthorizedKey(ctx context.Context, name, sshPubKey string) error

WriteAuthorizedKey writes an SSH public key to a running container's authorized_keys files (root and pixel user) via the TrueNAS file_receive API.

func (*Client) WriteContainerFile

func (c *Client) WriteContainerFile(ctx context.Context, name, path string, content []byte, mode fs.FileMode) error

WriteContainerFile writes a file into a running container's rootfs via the TrueNAS filesystem API (no SSH required).

type CreateInstanceOpts

type CreateInstanceOpts struct {
	Name      string
	Image     string
	CPU       string
	Memory    int64 // bytes
	Autostart bool
	NIC       *NICOpts
}

CreateInstanceOpts contains options for creating a container.

type NICOpts

type NICOpts struct {
	NICType string // "MACVLAN" or "BRIDGED"
	Parent  string // host interface (e.g. "eno1")
}

NICOpts describes a NIC device to attach during container creation.

type ProvisionOpts

type ProvisionOpts struct {
	SSHPubKey       string
	DNS             []string          // nameservers (e.g. ["1.1.1.1", "8.8.8.8"])
	Env             map[string]string // environment variables to inject into /etc/environment
	EnvForwardKeys  []string          // env var names for sshd AcceptEnv restriction
	DevTools        bool              // whether to install dev tools (mise, claude-code, codex, opencode)
	Egress          string            // "unrestricted", "agent", or "allowlist"
	EgressAllow     []string          // custom domains (merged into agent, standalone for allowlist)
	ProvisionScript string            // zmx provision script content (written to /usr/local/bin/pixels-provision.sh)
	Log             io.Writer         // optional; verbose progress output
}

ProvisionOpts contains options for provisioning a container.

type TrueNAS

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

TrueNAS implements sandbox.Sandbox using the TrueNAS WebSocket API for container lifecycle, SSH for execution, and the local cache for fast lookups.

func New

func New(cfg map[string]string) (*TrueNAS, error)

New creates a TrueNAS sandbox backend from a flat config map.

func NewForTest

func NewForTest(client *Client, ssh sshRunner, cfg map[string]string) (*TrueNAS, error)

NewForTest creates a TrueNAS backend with injected dependencies for testing.

func (*TrueNAS) AllowDomain

func (t *TrueNAS) AllowDomain(ctx context.Context, name, domain string) error

AllowDomain adds a domain to the egress allowlist and re-resolves.

func (*TrueNAS) Capabilities

func (t *TrueNAS) Capabilities() sandbox.Capabilities

Capabilities advertises that TrueNAS supports all optional features.

func (*TrueNAS) CloneFrom

func (t *TrueNAS) CloneFrom(ctx context.Context, source, label, newName string) error

CloneFrom clones a source container's snapshot into a new container. CloneFrom creates newName as an independent copy of source@label.

func (*TrueNAS) Close

func (t *TrueNAS) Close() error

Close closes the underlying TrueNAS WebSocket connection.

func (*TrueNAS) Console

func (t *TrueNAS) Console(ctx context.Context, name string, opts sandbox.ConsoleOpts) error

Console attaches an interactive console session.

func (*TrueNAS) Create

func (t *TrueNAS) Create(ctx context.Context, opts sandbox.CreateOpts) (*sandbox.Instance, error)

Create creates a new container instance with the full provisioning flow: NIC resolution, instance creation, provisioning, restart, IP poll, SSH wait. When opts.Bare is true, only the instance is created (no provisioning or SSH wait).

func (*TrueNAS) CreateSnapshot

func (t *TrueNAS) CreateSnapshot(ctx context.Context, name, label string) error

CreateSnapshot creates a ZFS snapshot for the named instance.

func (*TrueNAS) Delete

func (t *TrueNAS) Delete(ctx context.Context, name string) error

Delete stops (if running) and deletes an instance with retry. Returns an error wrapping sandbox.ErrNotFound if the instance is already gone, so callers can distinguish "already absent" from real failures.

func (*TrueNAS) DeleteFile added in v0.6.0

func (t *TrueNAS) DeleteFile(ctx context.Context, name, p string) error

DeleteFile removes a single file. Use `exec rm -rf` for recursive deletes.

func (*TrueNAS) DeleteSnapshot

func (t *TrueNAS) DeleteSnapshot(ctx context.Context, name, label string) error

DeleteSnapshot deletes a ZFS snapshot by label.

func (*TrueNAS) DenyDomain

func (t *TrueNAS) DenyDomain(ctx context.Context, name, domain string) error

DenyDomain removes a domain from the egress allowlist and re-resolves.

func (*TrueNAS) Get

func (t *TrueNAS) Get(ctx context.Context, name string) (*sandbox.Instance, error)

Get returns a single instance by bare name.

func (*TrueNAS) GetPolicy

func (t *TrueNAS) GetPolicy(ctx context.Context, name string) (*sandbox.Policy, error)

GetPolicy returns the current egress policy for an instance.

func (*TrueNAS) List

func (t *TrueNAS) List(ctx context.Context) ([]sandbox.Instance, error)

List returns all px- prefixed instances with the prefix stripped.

func (*TrueNAS) ListFiles added in v0.6.0

func (t *TrueNAS) ListFiles(ctx context.Context, name, p string, recursive bool) ([]sandbox.FileEntry, error)

ListFiles uses `find -printf '%p\t%s\t%m\t%y\n'` to enumerate entries. Non-recursive uses -maxdepth 1.

func (*TrueNAS) ListSnapshots

func (t *TrueNAS) ListSnapshots(ctx context.Context, name string) ([]sandbox.Snapshot, error)

ListSnapshots returns all snapshots for the named instance.

func (*TrueNAS) Output

func (t *TrueNAS) Output(ctx context.Context, name string, cmd []string) ([]byte, error)

Output executes a command and returns its combined stdout.

func (*TrueNAS) ReadFile added in v0.6.0

func (t *TrueNAS) ReadFile(ctx context.Context, name, p string, maxBytes int64) ([]byte, bool, error)

ReadFile reads the file (or first maxBytes) into memory. If maxBytes>0 and the file is larger, returns truncated=true.

func (*TrueNAS) Ready

func (t *TrueNAS) Ready(ctx context.Context, name string, timeout time.Duration) error

Ready waits until the instance is RUNNING with a routable IP and reachable via SSH. The full timeout covers both IP appearance (cloned containers boot DHCP slowly — ~15-60s) and SSH bring-up.

If key auth fails, it pushes the current machine's SSH public key via the TrueNAS file API.

func (*TrueNAS) RestoreSnapshot

func (t *TrueNAS) RestoreSnapshot(ctx context.Context, name, label string) error

RestoreSnapshot rolls back to the given snapshot: stop, rollback, start, poll IP, SSH wait.

func (*TrueNAS) Run

func (t *TrueNAS) Run(ctx context.Context, name string, opts sandbox.ExecOpts) (int, error)

Run executes a command inside a sandbox instance. If ExecOpts provides custom Stdin/Stdout/Stderr, it builds a custom exec.Cmd using ssh.Args(). Otherwise it delegates to ssh.Exec.

func (*TrueNAS) SetEgressMode

func (t *TrueNAS) SetEgressMode(ctx context.Context, name string, mode sandbox.EgressMode) error

SetEgressMode sets the egress filtering mode for a container.

For "unrestricted": flushes nftables, removes egress files, restores blanket sudoers.

For "agent"/"allowlist": writes nftables config, domains/cidrs, resolve script, safe-apt wrapper, restricted sudoers via the TrueNAS API, then SSHes in to install nftables and resolve domains.

func (*TrueNAS) Start

func (t *TrueNAS) Start(ctx context.Context, name string) error

Start starts a stopped instance.

func (*TrueNAS) Stop

func (t *TrueNAS) Stop(ctx context.Context, name string) error

Stop stops a running instance. No-ops if the instance is already stopped.

func (*TrueNAS) WriteFile added in v0.6.0

func (t *TrueNAS) WriteFile(ctx context.Context, name, path string, content []byte, mode os.FileMode, uid, gid int) error

WriteFile writes content to a file inside the container via the TrueNAS filesystem API (no SSH required) so uploads work even before SSH provisioning has set up authorized_keys (e.g. during BuildBase).

The TrueNAS filesystem API writes as root. When uid/gid are non-negative, the file is chowned to uid:gid via SSH-as-root after the write so callers (notably the MCP layer) can produce files owned by the configured exec user. uid<0 or gid<0 leaves the file root-owned, matching the historical BuildBase behaviour.

Jump to

Keyboard shortcuts

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