1. Introduction to srv
srv is a self-hosted control-plane service for creating Firecracker microVMs over SSH on a Tailscale tailnet.
It exposes an SSH command surface on one Linux host and manages Firecracker microVMs behind it. You create, inspect, stop, start, resize, back up, and delete VMs the same way you would run a remote command — through ssh srv <command>.
ssh srv new demo# demo created — state: provisioning# inspect: ssh srv inspect demo# connect: ssh root@demo
1.1 Where srv fits
srv is useful for both short-lived sandboxes and persistent isolated services.
- Throwaway debug VMs — spin up an isolated environment, break things, and delete it without affecting the host
- Remote Amp runners and sandboxed agent VMs — run normal web- and mobile-controlled Amp threads in dedicated cgroup-limited microVMs with private Tailscale TCP/UDP access and scoped provider API proxies
- Dev/test environments — fast reflink-based clones from a single base image, with backup/restore for instant reset
- Isolated workloads — run services in separate microVMs with per-VM networking, auth, and resource limits
All VMs get a full Linux system with systemd, a real kernel, and their own Tailscale identity. Where containers are not enough — package managers, services that need root, bespoke networking configurations, predictable boot and teardown — srv gives you real isolated machines in seconds.
1.2 Conceptual architecture
Tailscale tailnet │ ┌─────┴─────┐ │ tsnet │ (joins tailnet as "srv") │ :22/tcp │ (SSH API surface) └─────┬─────┘ │ ┌─────────────┼─────────────┐ │ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │ VM: demo │ │ VM: ci │ │ VM: test │ │ /30 net │ │ /30 net │ │ /30 net │ │ cgroup │ │ cgroup │ │ cgroup │ │ TAP + NAT │ │ TAP + NAT │ │ TAP + NAT │ └─────────────┘ └─────────────┘ └─────────────┘
Key components:
- tsnet — joins the tailnet as
srvand exposes the control API on tailnet TCP port 22 - gliderlabs/ssh — handles
execrequests and rejects shell sessions - SQLite — stores instances, events, command audits, and authorization decisions
- Reflinks — clone the base rootfs for fast per-instance writable disks
- Network helper — root-only process owns TAP creation, iptables MASQUERADE, and FORWARD rules
- VM runner — root-owned process invokes Firecracker through the official jailer, drops to
srv-vm:srv, and places each VM into its own cgroup v2 leaf - MMDS — one-off Tailscale auth keys are injected through Firecracker metadata so guests self-bootstrap
- Provider gateways — per-instance HTTP proxies on the guest's gateway IP forward to LLM providers with host keys
- HTTP integrations — admin-defined host-side HTTP proxies inject headers or auth for selected guests without storing raw secrets inside the VM
1.3 Where you can run it
srv runs on Linux with the following requirements:
- Linux host with cgroup v2 and
/dev/kvm - IPv4 forwarding enabled (
net.ipv4.ip_forward=1) SRV_DATA_DIRas a btrfs subvolume root, all base rootfs images on the same btrfs filesystem, andbtrfs-progsinstalleduser_subvol_rm_allowedfor unprivileged deletion of service-owned subvolumes; Orb runtime and jail directories in the same subvolume- Tailscale installed and working on the host
- Tailscale OAuth client credentials with permission to mint auth keys for guest tags
ip,iptables,cp,e2fsck, andresize2fsavailable on the host- Official static Firecracker and jailer release pair
1.4 Next steps
2. Amp runners on srv
Run Amp threads in dedicated, self-hosted Firecracker microVMs without giving up Amp's remote experience.
This page describes the CLI runner plugin, not the native Orb integration. For Amp-managed pause/wake on srv, see Self-hosted Amp orbs. Comparisons below refer to Amp-hosted orbs; self-hosted providers can have different lifecycle capabilities.
Each New isolated thread action creates a VM with a fresh repository clone, its own resource limits and Tailscale identity, and a dedicated Amp runner. The resulting thread is still a normal Amp thread: open it from the web or your phone, review its conversation and changes, and use its remote terminal while srv provides the machine underneath.
2.1 One action creates the whole environment
Run srv Runner: New isolated thread from Amp's command palette. The plugin turns a task into a ready remote thread:
Task + mode + size │ ▼┌─────────────────────┐│ Dedicated srv VM ││ Firecracker + cgroup│└──────────┬──────────┘ │ clone + .agents/setup │ workstation profile ▼┌─────────────────────┐│ Dedicated Amp runner││ persistent systemd │└──────────┬──────────┘ │ ▼┌─────────────────────┐│ Normal Amp thread ││ web · mobile · diff ││ remote terminal │└─────────────────────┘
The clone comes from the current branch on origin. Local uncommitted and untracked files stay on the workstation.
2.2 Keep the Amp thread experience
srv replaces the executor, not Amp's thread and control plane. The plugin starts amp --no-tui with a stable runner ID and --remote-control-terminal, so a thread running in the VM retains:
- Remote control from ampcode.com on desktop or mobile
- The normal Amp thread URL, conversation, visibility, and changes UI
- A web-accessible terminal while the runner is online
- Amp project and thread workflows that apply to CLI runner threads
- The ability for Amp plugins and agents to target the live runner for more threads that share that VM
The VM must be running for work to execute. srv has no Orb-style automatic wake integration: any schedule or external or plugin automation that targets this runner requires the VM to already be running. Amp's Multiplayer feature is currently restricted to Orb-backed threads. See Amp's Owner's Manual for the current runner, thread-sharing, and remote-control behavior.
2.3 Tailscale services instead of HTTP-only portals
Every VM joins the tailnet with its own identity and MagicDNS name. A development service can be reached directly by authorized tailnet devices without port forwarding:
http://:3000 postgresql://:5432/app ssh root@
This is broader than an HTTP preview tunnel: Tailscale carries TCP and UDP, supports multiple simultaneous services, works with native clients, and applies tailnet ACLs to the whole VM identity. The service must listen on an address reachable through Tailscale, and the VM must be running.
Amp Portals provide conveniences that raw Tailscale connectivity does not: Amp-managed HTTPS, embedding and annotation in the thread, access derived from thread visibility, and automatic coupling to Orb sleep and wake. srv instead provides private, general-purpose network access to the complete VM. You can put a Tailscale service address in the thread, but it remains accessible only to authorized tailnet devices.
2.4 Bring your environment with you
There are two setup layers:
~/.config/amp/srv-runner.jsondefines workstation-wide skills, binaries, private files, guest symlinks, andNO_PROXYentries to copy into every runner VM.- An executable
.agents/setupin the repository installs project-specific dependencies after the clone.
Configured files are validated before VM creation. The confirmation shows how many profile items will enter the persistent VM.
2.5 Host-controlled credentials and egress
The Amp credential is stored root-only in the VM. Optional provider and HTTP integration gateways keep upstream API credentials on the srv host and expose only per-VM proxy endpoints. General public HTTPS traffic from the runner uses a per-VM CONNECT gateway that rejects private, tailnet, host-local, and special-use destinations.
Treat the VM as sensitive persistent state: its Amp credential and configured private files remain until deletion.
2.6 Persistent when useful, disposable when done
Unlike an Orb, an srv VM is persistent and consumes capacity on hardware you operate.
- Stop it to release runtime resources while preserving the checkout and disk.
- Start it again and the systemd-managed Amp runner reconnects.
- Delete it to remove the VM, checkout, copied credentials, and plugin state.
- Inspect or SSH into failed provisioning attempts instead of losing the environment.
2.7 srv runner and Amp Orb at a glance
| srv Amp runner | Amp Orb | |
|---|---|---|
| Compute | Your Firecracker host | Amp-managed infrastructure |
| Capacity | Bounded by the host | Elastic hosted capacity |
| Lifecycle | Persistent; explicit start, stop, delete | Ephemeral; automatic pause and wake |
| Thread URL and remote control | Standard Amp thread and runner remote control | Standard Amp thread and Orb control |
| Service access | Private Tailscale TCP/UDP under tailnet ACLs | Amp-managed HTTP Portals |
| Environment | Workstation profile plus .agents/setup |
Amp project and Orb setup |
| Networking and identity | Per-VM Tailscale identity | Amp-managed Orb networking |
| Multiplayer | Not supported for runner threads | Supported for eligible Orb threads |
Choose srv when you want Amp's remote thread experience on hardware, networks, credentials, and VM boundaries you control. Choose Orbs when managed elasticity, automatic wake-up, Portals, or Multiplayer matter more than operating the executor yourself.
2.8 Get started
After meeting the runner prerequisites, install the bundled plugin from the srv checkout:
mkdir -p ~/.config/amp/pluginsln -sf "$PWD/contrib/amp/plugins/srv-runner.ts" ~/.config/amp/plugins/srv-runner.ts
Reload plugins from Amp's command palette, then run srv Runner: New isolated thread.
Continue with the AI coding-agent guide for detailed provisioning behavior, profile configuration, secure branch pushing, resource limits, and cleanup.
3. Installation
3.1 System requirements
- Linux host with cgroup v2 and
/dev/kvm - IPv4 forwarding enabled:
net.ipv4.ip_forward=1 SRV_DATA_DIRmust be a btrfs subvolume root for all VMs and Orbs, with every base rootfs image on the same btrfs filesystembtrfs-progsinstalled and the btrfs mount optionuser_subvol_rm_allowedenabled for deletion of service-owned subvolumes by unprivilegedsrv- Orb runtime and jail directories in the same subvolume, not merely the same filesystem; see path constraints
- Tailscale installed and working on the host
- Tailscale OAuth client credentials (
TS_CLIENT_IDandTS_CLIENT_SECRET) with permission to mint auth keys for the configured guest tags ip,iptables,cp,e2fsck, andresize2fsavailable on the host- Official static Firecracker and jailer release pair (the installer can download these for you)
Existing installations must follow the storage migration runbook before upgrading a non-btrfs host. Starting the new service on XFS cannot convert it in place.
srv is intentionally a single-host control plane. Clustering, multi-host scheduling, and high availability are out of scope for the current phase.
3.2 Build
Build the three binaries from source:
go build ./cmd/srvgo build ./cmd/srv-net-helpergo build ./cmd/srv-vm-runner
Or install them to a standard location with the provided installer (see below).
3.3 Build the guest image
The Arch base image builder produces the vmlinux kernel and rootfs-base.img rootfs that srv provisions from.
On an Arch Linux host:
sudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh
On a non-Arch host, use the podman workflow:
sudo podman run --rm --privileged --network host \ -v "$PWD":/work \ -v /var/lib/srv/images/arch-base:/var/lib/srv/images/arch-base \ -w /work \ docker.io/library/archlinux:latest \ bash -lc ' set -euo pipefail pacman -Sy --noconfirm archlinux-keyring pacman -Syu --noconfirm arch-install-scripts base-devel bc e2fsprogs rsync curl systemd OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh '
See Building a custom guest image and the guest image reference for details on what the image includes and how to customize it.
3.4 Install and configure
The systemd installer handles binary installation, unit setup, and downloading the official static Firecracker/jailer pair:
sudo ./contrib/systemd/install.sh
Enable IPv4 forwarding:
sudo tee /etc/sysctl.d/90-srv-ip-forward.conf >/dev/null <<'EOF'net.ipv4.ip_forward = 1EOFsudo sysctl --system
Write the environment file. At minimum you need Tailscale credentials and guest artifact paths:
sudoedit /etc/srv/srv.env
Key entries to fill in:
TS_AUTHKEY=tskey-auth-xxxxxxxxxxxxxxxxTS_CLIENT_ID=your-oauth-client-idTS_CLIENT_SECRET=your-oauth-client-secretTS_TAILNET=your-tailnet.ts.netSRV_BASE_KERNEL=/var/lib/srv/images/arch-base/vmlinuxSRV_BASE_ROOTFS=/var/lib/srv/images/arch-base/rootfs-base.imgSRV_GUEST_AUTH_TAGS=tag:microvm
See the full configuration reference for every variable.
Then start the services:
sudo ./contrib/systemd/install.sh --enable-now
3.5 Validate
Run the end-to-end smoke test to confirm everything works:
sudo ./contrib/smoke/host-smoke.sh
The smoke test verifies systemd units, SSH reachability, guest creation, readiness polling, backup/restore, cgroup limits, and cleanup. It is the supported validation gate after install, restore, and upgrade.
See the smoke test reference for details on overrides and failure artifacts.
3.6 Next steps
- Walkthrough — create your first VM
- Running as a daemon — systemd details
4. Multi-host frontend
srv-front provides one SSH endpoint in front of independent srv hosts. It
keeps only a static host configuration and its own Tailscale/SSH identity, not a
VM registry. It can run on a small separate Linux server without KVM,
Firecracker, a reflink filesystem, or the srv helper services.
Each backend still owns VM state, permissions, admission, images, pools, and backups. An unavailable frontend does not stop VMs; direct backend SSH remains available. There is no HA failover, replication, or automatic rebalancing.
4.1 Configure trust and start the frontend
Upgrade the backends to a version supporting forwarding, placement, and
migration before adding them. Give each backend a distinct SRV_HOSTNAME
(for example srv-a, srv-b); the frontend can take the friendly name srv.
Build and install the separate binary:
go build -o srv-front ./cmd/srv-frontsudo install -m 0755 srv-front /usr/local/bin/srv-frontsudo install -m 0644 contrib/systemd/srv-front.service /etc/systemd/system/
Create /etc/srv-front.json with explicit allowed user logins and pinned backend
host keys. Addresses must include the SSH port:
{ "hostname": "srv", "data_dir": "/var/lib/srv-front", "listen_addr": ":22", "allowed_users": ["alice@example.com", "ops@example.com"], "hosts": [ {"name": "a", "address": "srv-a:22", "host_key": "ssh-ed25519 REPLACE_WITH_HOST_A_PUBLIC_KEY"}, {"name": "b", "address": "srv-b:22", "host_key": "ssh-ed25519 REPLACE_WITH_HOST_B_PUBLIC_KEY"} ]}
Obtain each public host key through a trusted administrative connection, not
an unauthenticated first-use network scan. Each upgraded backend logs its public
key at startup. Read the public_key value from its service journal:
sudo journalctl -u srv -b --no-pager | grep 'ssh host key'
Copy the ssh-ed25519 ... value without the surrounding log-field quotes.
Only the public key, never /var/lib/srv/state/host_key, goes into the frontend
configuration. Changing a backend key requires updating its pin.
Put the frontend's node-join credentials in /etc/srv-front.env (root-readable,
mode 0600). TS_AUTHKEY, TS_CLIENT_ID, TS_CLIENT_SECRET, TS_CONTROL_URL, and
SRV_ADVERTISE_TAGS are supported. Use a dedicated frontend node identity; it
does not need credentials for creating guest nodes. Restrict tailnet access so
the frontend can reach the configured backend SSH ports and intended users can
reach the frontend.
sudo systemctl daemon-reloadsudo systemctl enable --now srv-frontsudo journalctl -u srv-front
The frontend logs its stable Tailscale node ID at startup. Configure that exact
ID on each backend in /etc/srv/srv.env:
SRV_TRUSTED_FRONTENDS=nREPLACE_WITH_FRONTEND_STABLE_NODE_ID
Restart each backend after updating its configuration. This trust is powerful: the frontend can assert user identities, including administrators. Protect its state directory and credentials accordingly. Re-enrolling it as a new node requires updating the backend trust entries.
The frontend resolves the original user with Tailscale WhoIs; tagged client
nodes cannot impersonate human users. Backends accept forwarding only from the
configured stable node IDs, then apply their usual SRV_ALLOWED_USERS,
SRV_ADMIN_USERS, and per-instance ownership checks. Audit records retain the
user identity, actual frontend peer address, and forwarding node ID. No SSH
username grants delegation rights. A trusted frontend itself may be tagged.
4.2 Commands and placement
ssh srv node listssh srv -- --json node listssh srv listssh srv statusssh srv -- --json listssh srv new demo --ram 8G --rootfs-size 20Gssh srv new other --host bssh srv inspect demossh srv stop a/demossh srv logs -f a/demo serialssh srv pool list --host a
node list shows one row per configured server: running/total VMs, allocated
vCPUs versus CPU budget, one-minute load average, RAM reservations versus their
budget, and measured disk usage and available filesystem space. These are allocations and
capacity, not instantaneous CPU/RAM utilization percentages. Unreachable or
unauthorized hosts remain visible with an error rather than disappearing. Use
node list --host a to query just one host; status gives more detail.
node list, list, and status query hosts concurrently and label their results.
node list and status require backend admin access. With --json, aggregate responses contain
a hosts array with host, data, and optional error. Partial failures retain
successful results, print errors, and exit nonzero. Host-local operations such
as pools, integrations, snapshots, and raw imports require --host.
Short VM names resolve only when all hosts answer and exactly one active source
matches. Use host/name or --host when ambiguous or when another host is down.
Completed migration sources remain visible but are excluded from short-name
resolution. Keep guest names unique within the tailnet; the frontend does not
reserve names globally or rewrite guest DNS names. Interactive top/PTY sessions
must go directly to a backend.
Automatic new placement asks each backend whether the requested image, shape,
pool, and integrations fit. It ranks eligible hosts by remaining RAM budget,
then remaining disk space, then host name. RAM includes VM overhead; disk checks
measured available filesystem space against a 1 GiB runtime floor, not virtual
rootfs reservations.
CPU remains advisory, consistent with srv's existing overcommit policy.
Preflight does not reserve capacity. The selected host still performs normal
admission. A failed create is not retried on another host: after a network
failure the original create may already have succeeded. Inspect that host before
retrying. --host bypasses automatic selection, not backend permissions or
admission checks.
4.3 Cold migration
ssh srv migrate a/demo --to b
The frontend checks destination placement and both native-transfer runners before stopping the source, records the existing durable source start fence, and asks the source runner for a readonly disk snapshot. The runners reuse coldstore's validated Btrfs send/receive, with streams relayed through the frontend's pinned SSH connections and bounded pipes. No additional host-to-host SSH key is needed.
An offloaded source disk is automatically hydrated on the source host during
preparation, before taking the transfer snapshot. Allow local space for the full
disk and time for the download; this is not a direct cold-store-to-destination
transfer. The migration fence prevents retention from offloading it again.
If hydration fails, the source stays fenced in preparing; resolve the storage
error and retry preparation with the same token, target and memory-policy flags.
If the disk has a known readonly image base, the destination receives that base
once, then receives each VM using btrfs send -p BASE SNAPSHOT. A matching stored
base is reused by its UUID and exact manifest, not by an image name or a content
hash alone. Independently created, byte-identical bases with different UUIDs are
not interchangeable Btrfs parents. Unknown lineage falls back to a full Btrfs
send, not a tarred rootfs. Concurrent first arrivals are safe, although they can
send redundant base traffic; duplicate publication consumes the stream and
retains the existing immutable base.
The destination verifies the received UUID, rootfs size and SHA256 before
publication, creates a writable snapshot for the VM, and imports its metadata
and logs using the existing archive framing (without rootfs bytes). A root-owned
receipt binds this writable incarnation to its retained original base so onward
and return migrations can remain incremental. The existing SQLite import receipt
still fences incomplete imports. Only after the destination commits does the
frontend complete the source, clean up its export snapshot, and start the
destination if the source was previously running. An already stopped VM stays
stopped. migrate
currently reports text and progress, and rejects --json before doing any work. The
frontend needs no disk-sized buffer, but all transfer traffic crosses its network
connection. This is cold migration: downtime includes hashing, transfer and startup.
4.3.1 Enable native transfer
Set SRV_MIGRATION_STORE in each backend's /etc/srv/srv.env, then restart its
runner. The directory must already exist on the same Btrfs filesystem as that
host's instances. The directory and every ancestor must be root-owned,
nonsymlink directories, not writable by group or others. Use a separate private
directory, not the service-writable data tree or a remote coldstore namespace.
The runner also accepts -migration-store. An empty setting disables native
migration; a capability refusal occurs before source preparation.
Use a consistent Btrfs mount-path view for the data directory and migration store.
With btrfs-progs 6.17.1, accessing an image-base parent through a bind-mount alias
while accessing the source snapshot through the original mount can fail with
ERROR: not on mount point, despite matching filesystem UUIDs. For a new host,
use, for example, SRV_DATA_DIR=/srv-btrfs/srv and
SRV_MIGRATION_STORE=/srv-btrfs/private/srv-migration. These may be different
subvolumes. The capability check verifies filesystem identity, not compatibility
of mount aliases with incremental send. Do not relocate existing instances by
changing SRV_DATA_DIR: their stored paths are absolute.
This is an explicit trust grant: a configured trusted frontend can relay native
streams to a privileged receiver. Btrfs receive is not safe for malicious
streams. Trust the frontend and every participating source host; isolate them
from untrusted users and machines. Public import still accepts portable
file archives only, and users cannot invoke the internal migration-disk
command through the frontend or directly on a backend.
Bases remain in the private store for reuse; there is no automatic expiry or
cache sweeper. The temporary received VM object is removed after its writable
clone and SQLite import receipt are durable. Failed/interrupted transfers and
failed cleanup can leave objects or source snapshots for explicit administrator
recovery. Do not share this store with remote offload operations or delete a base
still needed by migrated guests. This change does not add a space-reservation
ledger. One srv per host serializes its portable imports, native receives and
cold hydrations using the installer-provisioned SRV_DATA_DIR/.host-locks/payload.lock.
Admission measures available space after acquiring this lock, requiring the
1 GiB runtime floor plus the announced payload (logical rootfs size and logs
where applicable). Create, grow, start, backup and template operations check only
the floor; virtual disk sizes are not lifetime space reservations.
Local Btrfs subprocesses inherit held locks so a surviving storage writer keeps them after its parent dies. SSH transport processes do not retain these file descriptors; remote coldstore operations use their own namespace lock and tombstones. Independent forced-command coldstore uploads and other external writers are outside host-payload serialization. Neither the estimate nor Btrfs CoW guarantees fit: metadata, guest writes and unrelated writers can still cause ENOSPC. Upgrade srv and its runner together; older runners are rejected when they cannot report journal presence or serialized receive support.
Cold payload stages live under SRV_DATA_DIR/.cold-staging, on the data
filesystem; the existing root-only journal remains in the runner receipt tree.
Old stages there block operations rather than being silently ignored. Resolve
them before upgrading; moving SRV_DATA_DIR is not a recovery procedure.
For pooled VMs, explicitly select an existing destination pool or convert to fixed memory. A fixed-memory VM can also be assigned to a destination pool:
ssh srv migrate a/demo --to b --pool sharedssh srv migrate a/demo --to b --fixed-memory
Pools are host-local memory reservations and shared limits, not shared disks.
Pool IDs are never copied and pools are never created automatically. The target
pool must support this VM's guest-visible RAM; it is charged once at host level,
not again for every member. This does not guarantee spare memory under concurrent
pool usage. The source pool stays allocated until an operator removes it.
Without an explicit policy, pooled migration is rejected before stopping the VM.
Raw imports of pooled exports likewise require import --pool NAME or
import --fixed-memory. Upgrade both backends: pooled exports use a format that
older importers reject instead of silently changing the memory policy.
VMs with enabled integrations remain blocked: credentials, gateway routes, and bindings are host-local and are not part of the artifact. An administrator must configure the intended integration on the destination, disable every source binding, migrate, and explicitly enable the destination bindings:
ssh srv integration disable demo openai --host assh srv migrate a/demo --to bssh srv integration enable demo openai --host b
Expect integration-dependent workloads to be unavailable during this sequence. The destination must have a compatible kernel/initrd under the same image name; its rootfs template is not used for migration. Matching names do not prove kernel compatibility; operators must deploy compatible image versions. Per-VM backups are not copied.
The source is retained and fenced, not automatically deleted. After verifying the destination, explicitly delete the completed source:
ssh srv delete a/demo
Deleting a completed source removes its local copy without revoking the shared guest Tailscale identity. Never start both copies: the rootfs contains the same durable guest identity.
4.3.2 Interrupted migrations
There is no automatic rollback or automatic resumption. Keep the reported source, target, and migration token. Inspect both hosts directly:
ssh srv-a -- --json migration status demossh srv-b -- --json migration receipt demossh srv-b inspect demo
An unknown target outcome must leave the source fenced. A successful import is recorded durably on the destination. Only after verifying the destination receipt belongs to the intended transfer may an operator complete the source and start the destination. A completed source cannot be aborted.
| Source phase | Destination observation | Safe next action |
|---|---|---|
| No migration record | No transfer started | Inspect both hosts before issuing a fresh migration. |
preparing |
Stop not yet confirmed | Keep source fenced. Resolve its stop failure, then repeat migration prepare NAME TARGET TOKEN directly with the same token and memory-policy flags. Do not export yet. |
prepared |
Missing or importing receipt |
Keep source fenced. Inspect partial destination disks and the native store. Use a deliberate portable export/import recovery with the selected memory policy, or follow the abort procedure below. Do not issue another frontend migration over an uncertain transfer. |
prepared |
imported, with matching token and source instance ID |
Complete the source with migration complete NAME TOKEN; then start the destination if wanted. |
completed |
Matching committed import | Never abort or restart the source. Retry destination start if necessary; delete the source only after verification. |
| Any active phase | Unreachable host or mismatched receipt | Stop recovery actions until the outcome is established. Neither a timeout nor a same-name VM is proof of this transfer. |
Recovery mutations go directly to the backends; srv-front intentionally has no
automatic recovery loop. migration status records the selected memory policy.
When manually resuming a transfer, pass that same policy to import. After abort,
any fresh migration needs a new token.
If abandoning an incomplete migration, an administrator must first establish
that all destination copies of the guest identity are destroyed, including
saved transfer artifacts that might be booted. For native transfers this includes
the immutable VM object keyed by the migration token in SRV_MIGRATION_STORE,
not just the VM directory. The existing local-admin srv-cold-store --root DIR --discard TOKEN command can fence and discard that object; this is destructive
and is not a substitute for checking which transfer it belongs to. A shared base
does not contain that VM's identity and should be retained. Source export
snapshots under sources/<name-hash>/<token> can be explicitly removed after the
outcome is resolved. Then the explicit recovery command
on the source removes the fence without starting the VM:
ssh srv-a migration abort demo TOKEN --confirm-destination-destroyed
This confirmation is an operator assertion, not a distributed proof. Do not use it merely because the destination is unreachable. Preserve the source until the outcome is understood; do not manually edit migration database rows.
5. Walkthrough
This walkthrough assumes you have completed the installation and the smoke test passes.
5.1 Create a VM
ssh srv new demo
demo created — state: provisioninginspect: ssh srv inspect democonnect: ssh root@demo
The control plane creates a reflink clone of the base rootfs, allocates a /30 network, mints a one-off Tailscale auth key, injects it through MMDS, and boots the VM through the jailer.
With custom sizing:
ssh srv new demo --cpus 4 --ram 8G --rootfs-size 20G
5.2 Check status
ssh srv list
NAME STATE CPUS MEMORY DISK TAILSCALEdemo ready 1 1.0 GiB 10.0 GiB 100.64.0.2
For detailed info:
ssh srv inspect demo
Machine-readable output for scripting:
ssh srv -- --json listssh srv -- --json inspect demo
5.3 Connect to the VM
Once the VM reports state: ready and shows a Tailscale IP, connect over the tailnet:
ssh root@demo
Because the guest image bootstraps tailscale up --ssh, Tailscale SSH handles authentication without needing per-user OpenSSH keys in the guest.
You can also get the IP from inspect:
ssh srv inspect demo# look for tailscale-ip and tailscale-name fields
5.4 View logs
ssh srv logs demossh srv logs demo serialssh srv logs demo firecrackerssh srv logs -f demo serial
The serial log shows guest boot, bootstrap, and tailscaled output. The Firecracker log shows VMM lifecycle events.
5.5 Stop, restart, and delete
ssh srv stop demossh srv start demossh srv restart demossh srv delete demo
Stopping a VM does a graceful shutdown. The guest rootfs persists across stop/start cycles.
5.6 Resize a VM
Resize requires the VM to be stopped. CPU and memory can be increased or decreased within limits, while rootfs can only grow:
ssh srv stop demossh srv resize demo --cpus 4 --ram 8G --rootfs-size 20Gssh srv start demo
See Resize a VM for details.
5.7 Back up and restore
ssh srv stop demossh srv backup create demossh srv backup list demossh srv restore demo
See Backup and restore for the full workflow.
5.8 Move a VM between hosts
ssh srv-a export demo | ssh srv-b import
See Export and import for the semantics.
5.9 Next steps
- Instance lifecycle — full command reference
- Networking overview — how VM networking works
- Configuration — all environment variables
6. Manuelle DRBD-Übernahme mit srv
B darf erst übernehmen, wenn A sicher nicht mehr schreiben oder Gäste betreiben kann und der Datenstand auf B geklärt ist. Ein fehlgeschlagener Ping oder SSH-Zugriff reicht nicht. Im Zweifel bleibt B passiv.
Dieses Runbook gilt für zwei vorbereitete Hosts mit DRBD 9, Protocol C, Single-Primary und manueller Übernahme. A ist der aktuell aktive Host, B der Standby. Die Rollen können wechseln. Es gibt kein automatisches Failback. Die Befehle sind mit dem srv-Code und der DRBD-Dokumentation abgeglichen, aber noch nicht auf dem Zielsystem erprobt.
6.1 Vor dem ersten Einsatz
- Ressourcenname, DRBD-Gerät, Btrfs-Subvolume, Mountpfad und Managementzugang zu beiden Hosts eintragen. Beispiele unten: Ressource
srv, Mountpoint undSRV_DATA_DIR/var/lib/srv, logischer Tailnet-Endpunktsrv. Der Managementzugang muss unabhängig vom logischensrv-Endpunkt funktionieren, etwa über BMC oder Hypervisor-Konsole. - Auf beiden Hosts dieselbe
srv-/Runner-Version, passende Firecracker-/Jailer-Binaries, kompatible/etc/srv/srv.env, Netzkonfiguration, Secrets und passende numerische UID/GID für die Dateien bereitstellen. Das DRBD-Volume enthält den vollständigen Btrfs-Datenbestand, inklusive SQLite, VM-Disks, Boot-Images undstate/tsnet. Der aktive Host mountet das richtige Btrfs-Subvolume am identischen absoluten Pfad; der Standby mountet es nicht. Externe Dateien und Abhängigkeiten separat bereitstellen. - Auf beiden Hosts den Datenmount mit
noautound ohnex-systemd.automountvorbereiten. DRBD selbst soll beim Boot als Secondary zur Replikation verfügbar sein (auto-promote no). Keine anderen Units oder Skripte dürfen den Mount oder die Dienste beim Boot aktivieren. - Dieses Runbook setzt
quorum offvoraus: Bei genau zwei Knoten könnenmajorityundallnach einem harten Ausfall die normale Promotion blockieren. Die Freigabe erfolgt hier ausschließlich manuell nach sicherem Ausschluss des alten Primary. A kann bei Verbindungsverlust allein weiterschreiben. Bis B nachgezogen hat, schützt Protocol C diese Schreibvorgänge nicht. Replikationsunterbrechungen und den Plattenstatus als Ereignisse mit Zeitstempel außerhalb beider Hosts protokollieren und bei fehlender Replikation alarmieren. VM-Startliste, Anwendungschecks und Zugang zu unabhängigen Backups außerhalb des DRBD-Volumes bereithalten. - Auf beiden Hosts die tatsächlich wirksame DRBD-Konfiguration prüfen:
after-sb-0pri,after-sb-1pri,after-sb-2priundrr-conflictmüssen aufdisconnectstehen. Kein Handler darf bei einem Konflikt automatisch eine Kopie verwerfen. Vorab festlegen und testen, wie sich die Replikationsverbindung von A vor dem Boot unabhängig vom Host blockieren lässt.
6.1.1 Systemd: Mount schützen, Prozessneustarts behalten
Den Vollinstaller nur auf dem freigegebenen Primary mit geprüftem Mount und gestopptem Dienststack ausführen. Der Installer schreibt in SRV_DATA_DIR und kann bei fehlendem Mount ein lokales Btrfs-Subvolume anlegen. Vor der Übergabe zur Erstinstallation auf B die Dienstkonten srv, srv-vm und die Gruppe srv mit denselben numerischen IDs wie auf A anlegen und prüfen (id srv, id srv-vm, getent group srv). In der vom Installer gelesenen Env-Datei (/etc/srv/srv.env im Standardsetup) den Datenpfad als unquotierte Zeile hinterlegen, etwa SRV_DATA_DIR=/var/lib/srv. Die Installation findet erst nach der Mountprüfung im Abschnitt B übernehmen lassen statt.
Auf jedem Host nach der Installation aus dem Repo-Verzeichnis ausführen, bevor ihr den Dienststack freigebt. Die optionale Drop-in-Vorlage wird für srv und den Runner installiert. Bei einem anderen Mountpfad AssertPathIsMountPoint= in beiden Kopien an SRV_DATA_DIR anpassen und daemon-reload erneut ausführen.
for unit in srv.service srv-vm-runner.service; do sudo install -D -m 0644 contrib/systemd/drbd-mount.conf \ "/etc/systemd/system/$unit.d/drbd-mount.conf"donesudo systemctl daemon-reloadsudo systemctl disable srv.service srv-vm-runner.service srv-net-helper.service
disable entfernt den regulären Bootstart, stoppt aber keine laufenden Dienste. Die Dienste nicht maskieren: Ein manueller Start von srv.service soll Runner und Netzwerkhelfer weiterhin als Abhängigkeiten starten können. Auch ein abgewiesener Start von srv.service kann den Netzwerkhelfer starten. Das Drop-in macht bereits gestartete Abhängigkeiten nicht rückgängig.
Das Drop-in verweigert den Dienststart, wenn /var/lib/srv kein eigener Mountpoint ist. Es löst weder einen Mount noch eine DRBD-Promotion aus. Es prüft nicht, welches Gerät oder Subvolume eingehängt ist. Vor der Freigabe deshalb weiterhin Quelle, Subvolume und Schreibmodus prüfen.
| Ereignis | Verhalten |
|---|---|
srv- oder Runner-Hauptprozess crasht oder wird vom OOM-Killer beendet |
Systemd behält Restart=on-failure mit fünf Sekunden Wartezeit bei. Der Neustart setzt einen vorhandenen Datenmount voraus und unterliegt den systemd-Startlimits. Nach einem Runner-Crash können Gäste ausgefallen sein; der Prozessneustart allein bestätigt keine Wiederherstellung. |
| Host bootet neu | Datenvolume und Dienste bleiben aus, auch auf dem bisherigen Primary. Erst nach manueller Promotion und geprüftem Mount srv starten. |
| Operator stoppt den Dienst für die Übergabe | systemctl stop löst keinen Neustart aus. |
| Nur ein Firecracker-Gast stirbt, der Runner läuft weiter | Die Restart-Policy des Runners startet diesen Gast nicht neu. |
6.2 Geplanter Wechsel: A sauber herunterstufen
- Neue Jobs und Änderungen blockieren. Die Ausgabe von
ssh srv -- --json listund die Namen der VMs, die auf B wieder laufen sollen, außerhalb von A sichern. Dienste mit eigener Shutdown-Prozedur zuerst in den Gästen sauber beenden, dann diese VMs mitssh srv stop NAMEstoppen. Bewusst gestoppte VMs bleiben beim Start vonsrvoffline; die Startliste ist deshalb Teil der Übergabe. - Auf A zuerst
sudo systemctl stop srv.service, danachsudo systemctl stop srv-vm-runner.serviceund zuletztsudo systemctl stop srv-net-helper.serviceausführen. Der Runner hat beim Stop einen Drain-Schritt. Prüfen, dass die Dienste aus sind und keine Firecracker-Gäste diesessrvmehr laufen. Andere Schreiber auf dem Volume ebenfalls stoppen. - Auf A
sudo umount /var/lib/srvausführen, dannsudo drbdadm secondary srv. Beide Schritte müssen erfolgreich sein. Bei einem belegten Mount oder fehlgeschlagener Demotion anhalten; kein erzwungenes oder Lazy-Unmount. A nicht erneut starten. - Auf B mit
sudo drbdadm status srvprüfen: lokalSecondaryundUpToDate, Peer ebenfallsSecondaryundUpToDate, Replikation verbunden und keine Synchronisierung mehr aktiv. Bei Abweichung erst klären, dann mit B übernehmen lassen fortfahren.
6.3 Ungeplanter Ausfall: A ausschließen, bevor B übernimmt
- Wenn nur Tailnet-Zugriff oder DRBD-Verbindung weg ist, nicht umschalten. A über einen unabhängigen Managementzugang prüfen. Für die Übernahme A über Konsole, BMC oder Hypervisor nachweislich ausschalten und ausgeschaltet halten. Ein Auto-Reboot oder eine automatische Wiederherstellung darf A nicht reaktivieren. Uhrzeit und Bestätigung festhalten. Wenn das nicht möglich ist: hier stoppen.
- Auf B
sudo drbdadm status srvprüfen. B muss nochSecondarysein, seine lokale DiskUpToDate. Der Peer darf nach dem bestätigten Abschalten als getrennt erscheinen. WederUpToDatebei getrennter Verbindung noch der letzte grüne Monitoring-Wert beweist, dass B alle letzten Schreibvorgänge von A hat. Die Zeit zwischen dem letzten belegten synchronen Zustand und dem bestätigten Ausfall oder Abschalten gilt als ungeklärt, sofern ihr anhand der Ereignisfolge oder eines nachweisbaren Schreibstopps nicht ausschließen könnt, dass A in dieser Zeit allein geschrieben hat. Bei lückenhafter Erfassung ist ein fehlender Disconnect-Eintrag kein Nachweis. Bleibt eine Lücke: Übernahme stoppen und möglichen Datenverlust mit dem Dienstverantwortlichen klären. Wenn möglich, erst den letzten Datenstand von A sichern. Eine Übernahme mit akzeptiertem Datenverlust ist eine gesonderte Entscheidung, kein Standardablauf. - Bei
Outdated,Inconsistent,Diskless, gemeldetem Split-Brain oder unklarer Datenquelle nicht nach diesem Runbook übernehmen. Keine Force-Promotion und keine Befehle zum Verwerfen einer Kopie. Logs und beide Datenstände für die Wiederherstellung behalten.
6.4 B übernehmen lassen
-
Auf B normal promoten. Wenn der Befehl scheitert oder der Status danach nicht
Primarymit lokaler DiskUpToDatezeigt, abbrechen.sudo drbdadm primary srvsudo drbdadm status srv -
Mit dem vorbereiteten Mount-Eintrag für das DRBD-Gerät und das richtige Btrfs-Subvolume mounten. Mit
findmntQuelle, Dateisystem, Subvolume undrwprüfen. Stimmen sie nicht, nichts starten.srvdarf nie in das leere lokale Verzeichnis unter dem Mountpoint starten.sudo mount /var/lib/srvfindmnt --mountpoint /var/lib/srv -o TARGET,SOURCE,FSTYPE,FSROOT,OPTIONSsudo btrfs subvolume show /var/lib/srvStopp bei Erstinstallation oder Update auf B: Den Dienststack aus lassen. Erst mit geprüftem Mount, passendem
SRV_DATA_DIRund übereinstimmenden Dienst-IDssudo ./contrib/systemd/install.shausführen. Keine Flags--start,--enableoder--enable-nowverwenden; die generische Startanweisung des Installers nicht ausführen. Danach wie unter Systemd beide Drop-ins installieren und mitsystemctl catprüfen, den Bootstart deaktivieren und mitsystemctl is-enabledje Unitdisabledfür alle drei Units bestätigen. Schlägt ein Schritt fehl, nicht starten. Wenn B nur vorbereitet werden sollte, das Volume bei weiterhin gestoppten Diensten geplant zurückgeben. -
Erst danach
srvstarten. Systemd zieht Runner und Netzwerkhelfer mit. Wenn der Start oder eine der einzelnen Dienstprüfungen scheitert, auf B bleiben und die Logs prüfen, bevor ihr die Anwendung freigebt.sudo systemctl start srv.service && systemctl is-active srv.service && systemctl is-active srv-vm-runner.service && systemctl is-active srv-net-helper.serviceLogs:
sudo journalctl -u srv.service -u srv-vm-runner.service -u srv-net-helper.service -b -n 100 --no-pager. -
Von einem anderen Tailnet-Knoten
ssh srv statusundssh srv listprüfen. Der SSH-Hostschlüssel muss dem bekannten Schlüssel entsprechen; eine Warnung nicht umgehen.srvversucht beim Start, geeignete zuvor aktive Gäste wieder zu booten. Nach einem geplanten Wechsel die bewusst gestoppten Gäste anhand der Startliste mitssh srv start NAMEin Anwendungsreihenfolge starten. Nach einem Crash zunächst den automatischen Start und dessen Logs prüfen; bei fehlenden Gästen den Zustand klären, bevor ihr manuell startet. Absichtlich offline gehaltene VMs bleiben aus. -
Für jeden Dienst den vorbereiteten Anwendungscheck über den echten Clientpfad durchführen, etwa einen HTTP-Healthcheck über den Gastnamen und einen ungefährlichen Lesezugriff.
readyinsrvreicht nicht als Freigabe. Zeit vom Ausfall bis zur erreichbaren Anwendung und gegebenenfalls festgestellten Datenverlust dokumentieren.
6.5 A wieder anschließen, B aktiv lassen
Sobald B gemountet hat, B als aktive Datenquelle behandeln. A darf auch bei einem Fehler auf B nicht einfach wieder gestartet werden. Ein Rückwechsel ist eine neue, geplante Übergabe.
- A erst wieder hochfahren, wenn Boot-Schutz und ausgeschalteter Dienststart sichergestellt sind. Bei unklarer Schreibgeschichte alle Replikationspfade zu A vor dem Einschalten blockieren. Schon beim Verbindungsaufbau kann DRBD mit dem Abgleich beginnen. In diesem Fall beide Datenstände sichern. Die Verbindung erst freigeben, wenn B als maßgebliche Kopie bestätigt ist. Ist die Quelle ungeklärt oder liegt sie auf A, die Sperre beibehalten und in einen separaten Wiederherstellungsablauf wechseln.
- A bleibt ohne Mount und ohne
srv/Runner. A mussSecondarysein, B bleibtPrimary. Nach dem Wiederverbinden den Status auf beiden Hosts prüfen. Falls resynchronisiert wird, muss B die Quelle (SyncSource) und A das Ziel (SyncTarget) sein. Bei unerwarteter Richtung, Split-Brain oder widersprüchlichen Zuständen die Replikationsverbindung unterbrechen und keine Kopie verwerfen. - Mit
sudo drbdsetup status srv --verboseVerbindung und Replikation prüfen. A erst als einsatzbereiten Standby behandeln, wenn die VerbindungConnected, der ReplikationszustandEstablishedund beide DisksUpToDatesind.
6.6 Abnahme vor Produktion
- [ ] Auf dem Standby ohne Datenmount
sudo systemctl start srv-vm-runner.serviceund separatsudo systemctl start srv.serviceversuchen. Beide Starts müssen scheitern; Runner undsrvdürfen nicht laufen. Einen beim Versuch gestarteten Netzwerkhelfer danach stoppen. Nach einem Neustart des Standbys und später des früheren Primary prüfen, dass ohne Eingriff weder Datenmount noch eine der drei Service-Units aktiv ist. - [ ] Auf dem aktiven Pilothost mit geprüftem Mount und einer entbehrlichen Test-VM nur den
srv-Hauptprozess mitsudo systemctl kill --kill-whom=main --signal=SIGKILL srv.servicebeenden. Prüfen, dass systemd ihn automatisch neu startet und die Testanwendung erreichbar ist. Danach denselben Test separat fürsrv-vm-runner.serviceausführen. Prüfen, dass der Runner-Socket wieder erreichbar ist,srvläuft und die Testanwendung über den normalen Clientpfad antwortet. Schlägt ein Check fehl, den Fehler auf dem aktiven Host klären; der ausgefallene Prozess allein ist kein Grund zur Promotion des Peers. - [ ] Geplant von A nach B wechseln. Eine vorher laufende VM anhand der Liste starten; eine absichtlich gestoppte VM bleibt offline. Einen Anwendungscheck über Tailscale durchführen.
- [ ] A mit einer laufenden Test-VM hart ausschalten. B bei nachvollziehbarem Replikationsverlauf nach diesem Runbook ohne Force-Promotion übernehmen lassen. Wiederanlaufzeit messen und Datenstand mit zuvor bestätigten Test-Schreibvorgängen prüfen. Den Gegenfall getrennt proben: A verliert die Replikation, schreibt allein weiter und fällt dann aus. B bleibt im Standardablauf passiv.
- [ ] Die Erfassung der Replikationsereignisse vor dem Ausfall von A unterbrechen. Trotz letztem grünem Messwert muss B wegen der Nachweislücke passiv bleiben.
- [ ] Nur die Replikationsverbindung trennen, A eingeschaltet lassen. B darf weder promoten noch mounten noch
srvstarten. Prüfen, dass der Alarm auslöst, A bei diesem Profil weiter schreiben kann und B danach nachsynchronisiert. - [ ] Den alten aktiven Host zurückbringen. Prüfen, dass er als Standby zurückkommt, ohne Gäste zu starten oder den aktiven Host abzulösen.
- [ ] Wiederanschluss bei unklarer Schreibgeschichte separat proben: A mit blockierten Replikationspfaden booten. Auf B prüfen, dass keine Verbindung zustande kommt; auf A
Secondaryund fehlenden Datenmount bestätigen. Die Pfade bleiben blockiert, solange B nicht als maßgebliche Kopie bestätigt ist.
Quellen: DRBD 9 User Guide (Basic manual failover, Quorum), srv-Systemd-Unit, Runner-Drain, srv-Wiederanlauf, Host-Snapshots und separate Backups.
7. Self-hosted Amp orbs on srv
srv-orb-dispatch connects Amp's self-hosted orb provider
to existing srv SSH commands. It works with one srv host or with srv-front for
automatic placement. It does not replace srv's control plane or the separate
Amp runner plugin.
This is an initial integration: subprocess tests cover the dispatch contract, but image boot and the Amp connection still need validation on a real srv host.
| Amp job | srv behavior |
|---|---|
First spawn |
Create an Orb, wait for its host-only vsock agent, start amp orb bootstrap as user. |
Later spawn |
Start the same stopped Orb, or reuse the running Orb; restart bootstrap with the fresh token. |
pause |
Shut the Orb down and keep its disk. With SRV_ORB_RAM_CACHE=true, also keep its RAM if the host's RAM cache has room. With ORB_SNAPSHOT_ID, never keep RAM, and publish an immutable prepared disk template. |
delete |
Remove the native Orb; retain any legacy backups, shared snapshots, project templates and the exact cleanup receipt. |
Orbs use the same Firecracker, capacity accounting and placement infrastructure as VMs, but have a separate workload kind and default inventory:
ssh srv list # ordinary VMs onlyssh srv orb list # Orbs onlyssh srv list --all # both, with their kindssh srv orb new demo --image amp-orb
Names remain unique across both kinds on each backend. Existing records remain VMs; they are not inferred or converted from image names. Previously created Tailscale-based Orbs need a deliberate rebuild rather than automatic adoption.
Orbs do not support individual backups or restore. backup create, backup list,
backup delete and restore reject Orbs, including for admins. Legacy backups
are left untouched by deletion and may be cleaned up manually if desired. A reused
name may also have backups of a former VM. Project templates and shared host
snapshots are unchanged.
Common inspect, start, stop, delete and capacity commands still
operate on both kinds. The same list separation applies through srv-front.
By default, an Amp pause shuts the Orb down and keeps only its disk. Wake uses
the existing start command and boots from that disk. There is no automatic
migration.
7.0.1 Optional RAM cache for pauses
A provider can ask srv to also keep the RAM of a paused Orb, so that a wake continues the running processes. This is off by default. Saved RAM is a cache: srv can drop it at any time, and the Orb then boots from its disk.
To turn it on:
- Upgrade
srvandsrv-vm-runneron every host to this release, and restart them. - Set a size limit on each host. Add
SRV_RAM_CACHE_SIZE=64G(or--ram-cache-size) to the runner's environment and restart the runner. The default is0, which keeps no RAM. A zero in any unit, such as0G, also keeps none. - Upgrade the dispatcher, then set
SRV_ORB_RAM_CACHE=truein/etc/srv-orbs.env. The dispatcher then pauses withstop --cache-stateinstead of a plainstop.
Keep this order. An older srv does not know --cache-state and rejects the
command, so every pause fails until srv is upgraded or SRV_ORB_RAM_CACHE is
removed.
Both settings are required. Without a host limit, --cache-state is a plain stop.
How the cache behaves:
- Host limit. The saved RAM of all paused Orbs on a host stays within
SRV_RAM_CACHE_SIZE. Each image is as large as the Orb's configured RAM. - Eviction. When a new image does not fit, srv deletes the least recently saved images first. An Orb that is busy at that moment is skipped.
- Fallback. If there is still no room, or the save fails for any reason, the pause is an ordinary shutdown that keeps the disk. The pause does not fail.
- Wake.
startresumes from RAM if the image is still there and still matches the Orb, its disk and the installed Firecracker snapshot format. Otherwise srv discards the image and boots from disk. No operator step and no--discard-stateis needed. - Cold storage first. A cold-disk offload, including the
SRV_COLD_STORAGE_RETENTIONtimer, discards the Orb's cached RAM and then offloads the disk. WithSRV_COLD_STORAGE_AFTER_STOP=true, a pause does not save RAM at all, because the offload follows at once. - The disk is complete on its own. Before srv pauses the VM, the guest
agent flushes and freezes the Orb's filesystems. Every finished write is on
disk before RAM is saved. Losing the image can lose running processes, never
a file. The next
startthaws the filesystems.
The freeze needs a guest agent from this release. An Orb with an older agent rejects the request, and its pause is an ordinary shutdown. Rebuild the image to use the cache. Project-snapshot pauses and guests without RAM-resume support always shut down normally.
An explicit srv stop <name> --save-state is different. It must save RAM or
fail, and srv never evicts that image. See
Save RAM before stopping.
test/firecracker_orb_ram_cache.py checks the disk guarantee on real
Firecracker: it writes a file, pauses, evicts the RAM, offloads the disk, wakes
the Orb and reads the file back.
Every wake refreshes Amp bootstrap with the fresh token. The guest stops the
previous bootstrap and its descendants before starting the replacement. Prepared
images put bootstrap in amp-control.slice and set
AMP_ORB_WORKLOAD_SLICE=amp-workload.slice. The pinned official Amp runtime
provides an independent amp-headless.service and amp-run-workload launcher.
Workloads launched by that executor can remain in sibling scopes when srv
replaces bootstrap. Processes still owned by bootstrap are stopped.
This separation permits workload survival; it does not guarantee Amp session, Terminal, or Desktop continuity. Killing a workload launcher forwards signals to its scope. An executor restart or Amp's own cancellation can therefore stop its workloads. Authenticated Amp behavior across fresh-token RAM resume still needs the live validation below.
New orbs reuse a known ORB_SNAPSHOT_ID on its recorded backend; unknown IDs
fall back to the base image. Existing orbs retain their own disk and use Amp's
resume workflow.
7.1 Project snapshots
Amp requests a snapshot by sending pause with ORB_SNAPSHOT_ID, then wakes the
same orb again. srv stops the source, reflink-clones its disk, sanitizes the copy,
and publishes it atomically in an owner-scoped template namespace. The source
disk remains unchanged. Snapshot pauses use disk-only stop. If the source is
already stopped with cached RAM, the
snapshot request leaves that RAM on the source. Templates never copy RAM.
A later new orb gets a clone of this prepared template
and fresh srv allocation, rather than a migration of the source VM. Templates
retain their workload kind: an Orb cannot clone a normal VM template or vice versa.
Templates are host-local. The dispatcher persists their backend mapping and pins
new template-based VMs to that host, even when SRV_ORB_HOST changes. There is no
cross-host template replication or failover. A known but incomplete mapping,
image mismatch, unavailable backend or missing template fails rather than silently
claiming snapshot reuse. A missing mapping permits Amp's base-image fallback.
Snapshot IDs are immutable: repeat requests from the same source reuse the saved copy; another source cannot replace it. Templates survive source-orb deletion. Back up both dispatcher mappings and backend templates. Restoring only one side does not restore usable snapshots.
To preview old ready mappings, run the dispatcher as the provider user with
its existing SRV_ORB_STATE_DIR and SRV_ORB_ENDPOINT:
srv-orb-dispatch snapshot-gc --dry-run --older-than 720h
The JSON report includes the snapshot ID, template name, backend host (empty for
a direct endpoint), mapping modification time, and recorded times. published_at
is when publication was confirmed. last_used_at records an attempt to create a
new orb from the template, even if the create reply is lost. Waking an existing
orb does not count. Unknown times in legacy mappings remain null. Both the
mapping modification time and any recorded use must precede the cutoff. This is
a review list, not proof that Amp no longer requests the ID or that the backend
template still exists.
The command reads local dispatcher state only and does not lock, modify, or
delete mappings or templates. It never contacts the backend or Coldstorage.
Amp documents no snapshot-delete dispatch operation. To retire one ID, use the same dispatcher binary, state directory, endpoint and SSH identity as the provider. Update the dispatcher and backend before using these commands. Older dispatchers do not recognize retired mappings; do not downgrade while such mappings remain.
srv-orb-dispatch snapshot-gc --quarantine SNAPSHOT_ID# Verify a fresh orb can run setup without the template before proceeding.# To undo quarantine instead: srv-orb-dispatch snapshot-gc --restore SNAPSHOT_IDsrv-orb-dispatch snapshot-gc --delete SNAPSHOT_ID
Quarantine keeps the template but makes new orbs fall back to the base image.
After at least 24 hours, --delete first matches the template manifest on the
recorded backend to the source instance ID in the mapping. The original VM need
not exist. If the mapping has no source instance ID or the template cannot be
identified, it stays quarantined and can still be restored. Once deletion starts,
every attempt checks the authenticated owner, source instance and backend ID.
Restore is no longer allowed at that point. If a delete reply is lost, repeat
--delete for the same ID. Keep the retired mapping and lock: they prevent late
snapshot publication jobs from recreating the ID.
Existing orb disks, image bases and Coldstorage objects are not deletion targets.
7.1.1 Automatic retirement (opt-in)
After updating the dispatcher and backend, set SRV_ORB_SNAPSHOT_GC_OLDER_THAN=2160h
(90 days, for example) in /etc/srv-orbs.env. Install the two units on the
provider machine and enable the daily timer:
sudo install -m 0644 contrib/amp/orbs/srv-orb-snapshot-gc.{service,timer} /etc/systemd/system/sudo systemctl daemon-reloadsudo systemctl enable --now srv-orb-snapshot-gc.timer
The timer uses the provider's account and state. A run does nothing if the
retention setting is empty or unset. Auto GC only quarantines ready templates
with a recorded source and publication time. Publication, the mapping's last
modification, and any recorded clone attempt must all be older than retention.
Legacy mappings without publication time and manual quarantines are left alone.
On a later run, after at least 24 hours in automatic quarantine, the same
owner/source/backend checks as manual deletion apply. Failed attempts can be
retried by subsequent runs. This is an age policy, not proof that Amp will stop
requesting the snapshot ID; new orbs may need to run setup again.
Use journalctl -u srv-orb-snapshot-gc.service to see transitions and failures.
Disable the timer or clear the setting to prevent future sweeps. To cancel a
running sweep, stop the service as well; a deletion that already started may
have completed. Use --restore as the provider user to recover quarantines that
have not entered deletion. Restored mappings become eligible again after the
retention period.
Backend commands, executed as the same srv owner, are:
ssh srv-front -- --json project-template create ORB_VM_NAME TEMPLATE_ID --host assh srv-front -- --json orb new NEW_ORB_NAME --image amp-orb --template TEMPLATE_ID --host a
Use no --host when connecting directly to srv. Template creation requires a
stopped source. No RAM, running processes or terminal sessions are copied.
Backends need debugfs and e2fsck from e2fsprogs. Cleanup operates on the copied
ext4 disk in userspace; it never mounts the guest filesystem on the host.
It removes machine/Tailscale identities and named Amp authentication/session
files, while retaining prepared settings, skills, CLI binaries and project data.
Spaces and Unicode names are supported; ambiguous debugfs output and escape/control
characters in cleanup paths fail closed. Filesystem checks honor job cancellation.
Templates remain confidential artifacts in the source's trust domain:
removing active identity files is not secure erasure of free blocks/journals and
does not remove arbitrary project secrets. Do not distribute them as public images.
7.2 Prepare an image
Build an Arch
or Debian
image with SRV_AMP_ORB=1. This adds user:user, passwordless sudo, Amp,
Node.js, Python, tmux, the Desktop stack and a narrow host-only bootstrap agent.
Orb builds omit Tailscale and mask native srv enrollment; ordinary image builds
retain their existing boot and enrollment behavior. Use an Orb-enabled kernel
with built-in virtio-vsock support and rebuild older Orb images for this transport.
Both image builders include Docker and Compose v2; the supported command is
docker compose. Amp runs as user with passwordless sudo, not as root:
use sudo docker compose for daemon operations with the default root-owned
Docker socket. This is an access convention, not a privilege boundary against
the agent, which already has sudo. No Docker-group grant or socket-mode change
is required. Browser/test dependencies belong in the repository's .agents/setup.
Podman, Nix and legacy Compose v1 are not interchangeable provider contracts;
projects that need them must prepare and qualify those environments explicitly.
Register the prepared kernel/rootfs as amp-orb in
SRV_IMAGES_FILE on every
eligible backend. Keep any existing catalog entries. Example additional entry:
{ "amp-orb": { "kernel": "/var/lib/srv/images/amp-orb/vmlinux", "rootfs": "/var/lib/srv/images/amp-orb/rootfs-base.img" }}
Check the configuration reference for the catalog's complete format. Do not use
the raw Amp OCI image as a Firecracker rootfs. In this adapter, ORB_IMAGE is an
explicit prepared srv image name, not an OCI URL. Set it in the provider's
environment as shown below, otherwise Amp supplies its default OCI URL and the
adapter rejects the job before creating a VM.
Desktop preparation copies /opt/amp-wayland from a checksum-pinned layer of
Amp's official amd64 image and installs its distro-specific runtime dependencies.
It needs build-time access to us-central1-docker.pkg.dev and blob redirects, but
no Docker daemon. The source digest is retained inside the guest at
/opt/amp-wayland/srv-layer.sha256. Bootstrap and login shells load the bundled
program paths from /etc/amp-orb.env. The bundled executables use private RPATHs
for their libraries; a global LD_LIBRARY_PATH would break newer distro clients.
The catalog name is your choice. If you register the image as amp-orb-desktop,
normal srv clients can use:
ssh srv orb new demo --image amp-orb-desktop
For the Amp provider, set both ORB_IMAGE=amp-orb-desktop and
SRV_ORB_IMAGE=amp-orb-desktop. srv-front already considers image availability
when placing new VMs. This is provider configuration, not a new per-thread Amp
image selector. Existing VMs keep their original rootfs; rebuild and create a
new orb to pick up Desktop support. With the optional RAM cache, RAM resume retains
Desktop processes only if their owning service and workload launcher survive the
fresh-token bootstrap cycle. Desktop continuity
still needs authenticated Amp validation.
7.2.1 Executor and workload runtime
Both guest builders install selected executor and workload assets from Amp's official runtime layer. The runtime installer defines the checksum pin and asset allowlist, and verifies the layer before writing files. It installs the executor, workload launcher, environment watcher, and their systemd and sudo configuration. srv's vsock agent remains the sole bootstrap owner. The installer excludes vendor bootstrap and unrelated image configuration.
Preparation enables the environment watcher. When Amp creates the executor
environment, the watcher starts the independent executor. Bootstrap runs in
amp-control.slice, while the executor launches workloads in
amp-workload.slice. Project templates clear the source thread's executor
environment and enabled executor link but retain the runtime and watcher.
Rebuild the image and create a new Orb to add this runtime to an existing
deployment.
The environment helper avoids restarting the executor when its environment is unchanged, but the watcher can restart it when the environment changes. srv does not alter this behavior or provide a token-refresh API. Live Amp validation must establish whether a fresh bootstrap leaves the executor and its workload launchers running.
7.3 Provider machine and identity
Use a Linux machine with Amp, OpenSSH, network access to the control endpoint,
and a persistent local filesystem supporting flock, atomic rename and
fsync. It does not need KVM if the backends run elsewhere.
Give the provider a dedicated Tailscale node, optionally tagged, and explicitly map its stable node ID to a service owner. For example, on srv backends:
SRV_PROVIDER_NODES='{"nPROVIDER1":"amp-orbs"}'SRV_ALLOWED_USERS='service:amp-orbs'
Append to existing allowlists rather than replacing their entries. With
srv-front, also configure its provider_nodes map and allowed_users for the
same service owner; see provider identities.
The frontend remains a separate trusted forwarding node, not a provider node.
Tags or SSH usernames alone never grant a service identity. Unconfigured tagged
clients remain rejected. Service owners cannot be configured as admins.
All orbs and project templates from this provider belong to service:amp-orbs,
isolated from normal users' VM ownership. The dispatch contract contains no Amp
member ID, so this does not separate members within one Amp workspace. Use
separate provider identities for separate trust domains. An existing untagged
user provider still works; switching its identity does not transfer existing
VMs or templates automatically.
Configure ACLs so the provider can reach:
- The srv or srv-front SSH endpoint, under the existing allowed-user rules.
ampcode.comandstatic.ampcode.comfor provider traffic and CLI updates.
Guests need outbound HTTPS/WSS to ampcode.com, tunnel.ampcode.com and
static.ampcode.com, plus their Git hosts and package registries. The dispatcher
uses the per-VM Amp CONNECT gateway reported by inspect when present; otherwise
bootstrap uses direct egress. The gateway's existing private-address restrictions
still apply. Private Git hosts or a private AMP_URL require an appropriate
network/proxy policy; this integration does not weaken it automatically.
Proxy bypass is provider configuration, not a security boundary. Bootstrap
writes a fixed bypass list for guest-local services, MMDS, the CGNAT range and
.ts.net tailnet MagicDNS names. To send additional destinations past the
gateway — an internal registry, a private DNS suffix — set
SRV_ORB_PROXY_BYPASS in the provider environment to a comma-separated list
of at most 512 characters including commas, with no separate entry-count limit.
Each entry is a hostname, an
IPv4 literal, or a leading-dot DNS suffix; an optional trailing dot (the FQDN
form) is accepted verbatim but only matches clients that compare the same
form. The entries are client-native NO_PROXY tokens, not a universal
matcher: label-boundary subdomain matching agreed across urllib, curl and
Go's httpproxy in the runs verified for this change, but apex handling does
not — urllib and curl match the bare apex host for a leading-dot entry while
Go's httpproxy does not, so configure the bare hostname (which matched apex
and subdomains in all three) when the apex itself must be covered. CIDR
support differs between clients:
Python's urllib ignores CIDR entries entirely (including the built-in CGNAT
entry), while Go honors them for IP literals. CIDR ranges and IPv6 literals
remain outside this field's supported syntax.
Repeated supported entries, including built-in hostnames and IPv4 literals,
are accepted and forwarded verbatim. Empty entries and an explicitly empty
environment variable are configuration errors; unset the variable for no additions.
The dispatcher validates the list before spawn creates or starts
compute; pause and delete remain available with an invalid list. The guest
independently re-validates every entry before consuming its guest-side generation and
appends the list to the unchanged built-in entries; unset keeps exactly the
built-in list, and repository setup must not be used to repair this provider
networking. Bypass only removes the gateway from the path: the guest still
needs actual routing to the destination.
Setting SRV_ORB_PROXY_BYPASS adds a proxy_bypass field to the bootstrap
payload. A new dispatcher with the variable unset, and an older dispatcher
against a new guest image, both keep working because the field is simply
absent; but a set variable needs the dispatcher, srv backend and orb guest
image upgraded together, since older components reject the extra field and the
bootstrap fails rather than silently dropping the destination.
Guests with the earlier bypass policy still reject repeated entries and lists
longer than eight entries. Update guest agents/images before using those newly
accepted configurations with an updated dispatcher. Otherwise bootstrap fails
after backend request admission, even though guest-side validation precedes
guest generation consumption. Existing accepted configurations remain compatible;
a backend that already supports proxy_bypass needs no change for this relaxation.
On the wire, an empty or absent proxy_bypass still means no additional destinations.
The control endpoint's SSH host key must be installed in the service user's
known_hosts through a trusted channel. Control connections use strict host-key
checking. The provider never connects to guest SSH: the authenticated backend
forwards bootstrap over a local Firecracker vsock endpoint. Its guest listener
accepts only host CID 2 and only ping/bootstrap requests, not arbitrary commands.
SSH username selection does not grant control-plane permissions.
7.3.1 Optional project Tailscale
Guests do not require a Tailscale account, auth key or enrollment for readiness, bootstrap, Terminal, Desktop or portals. The srv control plane and provider still use Tailscale for their existing authenticated transport.
For project-specific tailnet access, follow
Amp's Tailscale setup: install the
client in .agents/setup, then start/authenticate it in .agents/resume using
Amp OIDC and an ephemeral node. Tailscale is not preinstalled or masked; the
project owns its installation and lifecycle. Do not bake reusable credentials
into the image or snapshot.
Keep the Amp connection independent of project networking; avoid an exit node
and configure proxy bypasses for private destinations when necessary.
7.4 Install and run
Build and install the adapter:
go build -o /tmp/srv-orb-dispatch ./cmd/srv-orb-dispatchsudo install -m 0755 /tmp/srv-orb-dispatch /usr/local/bin/srv-orb-dispatch
Create a dedicated local account srv-orbs with home /var/lib/srv-orbs.
Install a current Amp CLI accessible as /usr/local/bin/amp; for self-updates,
keep its actual installation writable by this account. Configure its SSH trust
and test ssh srv -- --json orb list as that account before starting the provider.
Initialize a new empty dispatcher directory explicitly, using the same endpoint and account as the service:
sudo -u srv-orbs env SRV_ORB_ENDPOINT=srv SRV_ORB_STATE_DIR=/var/lib/srv-orbs/dispatch \ /usr/local/bin/srv-orb-dispatch init
Never initialize over lost provider state. Restore its backup instead. Update
srv, srv-front (when used), srv-vm-runner, srv-net-helper and the prepared guest
image together before enabling this protocol. Older components fail closed;
there is no fallback to ordinary delete or unbound bootstrap. Preexisting Orb
records without a backend bootstrap counter require deliberate retirement and
recreation, not a counter reset or automatic adoption. JSON inspection remains
available for diagnostics, omitting bootstrap_generation when its row is
missing; this does not initialize a counter or permit managed bootstrap.
Create a provider in Amp workspace Settings → Orbs → Add Orb Provider.
Store its token in /etc/srv-orbs.env, owned by root with mode 0600. Copy the
non-secret settings from
srv-orbs.env.example and add
AMP_ORB_PROVIDER_TOKEN privately. Do not put tokens in shell arguments, Git,
images or thread messages.
sudo install -m 0644 contrib/amp/orbs/srv-orbs.service /etc/systemd/system/sudo systemctl daemon-reloadsudo systemctl enable --now srv-orbssudo journalctl -u srv-orbs -f
The service runs:
amp orb provider /usr/local/bin/srv-orb-dispatch
Select this provider in Amp's thread composer, or use:
amp -ox "Inspect this repository" --orb-provider YOUR_PROVIDER_NAME
7.4.1 Configuration
| Environment variable | Default / meaning |
|---|---|
SRV_ORB_ENDPOINT |
srv; an OpenSSH destination/alias for a backend or srv-front. |
SRV_ORB_STATE_DIR |
Required absolute persistent directory. Example service: /var/lib/srv-orbs/dispatch. |
SRV_ORB_IMAGE |
amp-orb; prepared srv image for new VMs. |
ORB_IMAGE |
Set to the same prepared image name in the provider environment. |
SRV_ORB_HOST |
Optional srv-front host name; omit for automatic placement. Do not set for direct backend access. |
SRV_ORB_CPUS |
2; new VM vCPUs for jobs without ORB_TYPE. |
SRV_ORB_RAM |
4G; new VM memory for jobs without ORB_TYPE. |
SRV_ORB_TYPES_FILE |
Optional absolute path to the orb type resource map described below. |
SRV_ORB_POOL |
Optional existing memory pool for new VMs (new --pool); SRV_ORB_RAM stays the guest-visible RAM. Unset creates fixed-memory VMs. |
SRV_ORB_DISK |
20G; new VM rootfs size. |
Sizes are operator configuration. To support Amp orb types, set
SRV_ORB_TYPES_FILE=/etc/srv-orbs/types.json and create a JSON object whose keys
match the type names advertised by your Amp provider, for example:
{ "small": {"cpus": 2, "memory_mib": 4096}, "large": {"cpus": 8, "memory_mib": 16384}}
Amp supplies the selected name as ORB_TYPE on spawn. Before allocating a new
VM, the dispatcher validates every configured shape using srv's machine limits
and selects its CPU and memory values. A typed allocation fails if the file is
missing, malformed, or has an unknown type; it never falls back to the untyped
sizes. Jobs without ORB_TYPE use SRV_ORB_CPUS and SRV_ORB_RAM, without
reading the map. SRV_ORB_DISK and SRV_ORB_POOL apply to all types.
Changing these settings affects new allocations only. Existing VMs keep their
CPU, memory, disks, and placement; resume, pause, and delete do not read the type
map. Type selection does not resize an existing VM. The map need not retain old
type names to resume existing threads.
AMP_URL, when provided by Amp on spawn, is passed to bootstrap.
Only one provider installation may own an Orb ID. Do not run independent providers with separate state directories against the same orbs. The dispatcher serializes same-orb jobs with local file locks; it is not an HA controller. Different orbs can run concurrently. Jobs time out after 270 seconds, including lock waits, leaving time inside Amp's five-minute dispatch limit.
New Orb names use orb- plus 48 hex digits. With the default runner paths, the
jailed API socket is 106 bytes long, below Linux's 107-byte pathname limit.
Existing 60-character names and their provider records/locks are retained, not
renamed; keep their working shortened SRV_JAILER_BASE_DIR configuration until
their compute is deleted. Successors use the shorter names. Custom longer data
or jailer paths can still exceed the limit and are rejected before launch.
Do not mix dispatcher versions against the same state directory.
7.5 Recovery and security
The state directory contains an identity/host mapping, operation phase and deletion
record. Bindings include the backend's own SSH host-key fingerprint, VM UUID,
creation timestamp, workload kind and image, not just a frontend placement label.
Back it up and keep it private. It never stores
the provider or orb tokens. The bootstrap token travels over control SSH stdin
and the host-only vsock channel,
briefly enters a root-only environment file under /run, and is removed after
systemd starts bootstrap. It remains in the bootstrap process environment;
root inside the VM is trusted. Guest bootstrap output is not relayed to provider
logs because it could contain credentials.
The srv daemon and dispatcher disable process dumpability. For the daemon this
also restricts ptrace and changes /proc ownership/access; debugging must account
for those effects. Both token-bearing
systemd units set LimitCORE=0. The example provider unit additionally refuses a
piped host core_pattern: not all external collectors honor the process limit.
This intentionally excludes a stock systemd-coredump configuration until the
operator supplies a reviewed no-dump policy; the integration does not change
host-wide core settings. Guest root and its configured collector are trusted;
the guest unit's limit is not a guarantee against a privileged piped collector.
The srv-front forwarding process, SSH client and Amp CLI remain part of the
trusted transport/runtime boundary. Avoid diagnostic dumps of those processes.
The adapter records creating before sending orb new. If the SSH response is
lost, a later job refuses automatic adoption or replay. It never automatically
retries a missing, uncertain create. The one exception is srv's explicit admission
refusal (exit status 3, for example a full host memory budget): nothing was
allocated, so the record returns to new and a later spawn or delete proceeds normally.
Only admission refusals qualify: host memory budget, pool lookup and pool size,
and the disk floor. Other errors before orb new reaches admission (invalid
size, unknown image, template mismatch, authorization) still exit 1 and fence.
Records fenced in creating before this rule existed are not healed by it. To
repair one, first confirm that orb list on every backend shows no VM with the
record's name, then stop the provider and remove both <name>.json and
<name>.json.lock. Removing only the .json is reported as a lost record. Initial discovery through srv-front requires
every host to answer; after placement is recorded, only the selected host is
queried, so an unrelated backend outage does not prevent wake-up.
An explicit srv-orb-dispatch bind ORB_ID UUID, under the provider's existing
configuration, can bind a visible native Orb on the already recorded host
with no import/migration history and bootstrap generation zero. A lost reply to
automatic frontend placement has no recorded host and cannot use this escape
hatch. Use a pinned host when deterministic create reconciliation is required.
Missing dispatch records, counters or lock-associated records fail closed.
Do not delete or hand-edit JSON/lock files to release a fence, except for the
pre-refusal-rule creating repair described above. A VM found without
a record is not silently adopted: restore the state backup instead. An unknown
allocation that cannot satisfy these checks remains unavailable pending a
separate reconciliation design.
7.5.1 Discard compute and continue the same thread
An operator can permanently discard an old Orb's compute and workspace without
requesting deletion of its Amp thread. Use the normal srv SSH API as the instance
owner or an administrator. Here srv-a is the direct backend endpoint:
ssh srv-a orb listssh srv-a -- --json inspect ORB_NAMEssh srv-a delete ORB_NAME
Confirm that the name, backend and instance identity match the intended Orb.
Through srv-front, add --host HOST to select its backend. For delayed automation
or retries that must survive name reuse, use
delete NAME --expect …
with the saved identity and request ID instead of bare deletion.
Deletion destroys the Orb's disk, including uncommitted work. Save any
required files first. Unlike pause, it does not preserve the workspace. This
SSH command makes no Amp API call: conversation history and attachments
already stored by Amp remain subject to Amp's own access and retention rules.
They are not a backup of the whole filesystem. Amp's UI may not immediately
reflect provider-side deletion. The next Amp spawn creates fresh compute for
the same thread; no separate authorization command is needed.
Manual SSH deletion leaves the dispatch record untouched. On the next Amp job,
the dispatcher queries the recorded backend for cleanup-receipt --instance UUID
when its managed VM is absent. Only the complete, matching receipt permits it to
record deletion and release pending work. The query uses the original instance
UUID, not a reused name; the original owner and administrators can read it even
when a different administrator performed deletion. Amp delete still records its
own deletion request before submission. Both paths save the authoritative receipt
before publishing the deleted state.
Individual backups, project templates and shared host snapshots remain outside
deletion scope.
Failed preflight is rechecked on retry; incomplete SSH deletion resumes under its
existing fence through srv background reconciliation or another delete.
For a lost reply, query cleanup-receipt --instance UUID or repeat the saved bound
request. An absent VM alone never reports success. The dispatcher creates nothing
until cleanup succeeds and its receipt is saved locally; lookup or persistence
failures can be retried. A pending Amp deletion can also be completed by a later
delete or spawn. Repeated Amp delete and pause after completed deletion are
no-ops until another spawn. A saved bound deletion for the old instance never
deletes the successor.
To continue the same retained thread, send a new message in Amp. Its spawn
supplies the fresh token. Following Amp's
dispatch contract,
the dispatcher resumes an existing VM or creates a new one after confirmed
deletion. This applies after both manual SSH deletion and ordinary Amp deletion.
The dispatcher validates the completed deletion's full v3, v4 or v5 receipt, then durably publishes one successor with a distinct srv name before attempting creation. The new VM uses normal base-image or ready project snapshot selection, gets a new instance UUID, and bootstraps with the new token. Amp runs repository setup again when needed; prepared snapshots may skip setup. This does not restore the discarded thread workspace's uncommitted changes. Subsequent pause/wake retains the successor's own disk and follows normal resume behavior.
Job-ordering limitation: Amp's documented dispatch contract has no upstream incarnation or sequence field. A local job that observed the old incarnation before waiting for its lock is rejected after the switch; old identity-bound srv commands cannot target the new name/UUID. But an old upstream job first delivered after the switch is indistinguishable from a current job. Incoming Amp jobs are treated as current instructions, not subjected to a locally unverifiable queue drain requirement. This does not establish an upstream ordering guarantee or protect against arbitrary upstream reordering.
The stable root record and lock select the current incarnation. Cleanup receipts remain scoped to each incarnation's srv name and are not overwritten by its successor. No predecessor archives are created or traversed; existing archives are left untouched and are not required to operate a bound successor. A crash before publication leaves the completed deletion current. A crash after publication but before creation resumes the same successor. Unknown create outcomes retain their existing fences and require reconciliation, not another allocation. An unreachable backend is never treated as proof of absence.
A successor can consume a ready project template but cannot capture into its predecessor's snapshot ID. New mappings bind snapshot authorship to the instance UUID. Legacy mappings may only be completed by the original, non-replacement incarnation; a successor must use a new snapshot ID for new content.
Do not remove provider records, manually remove disk files, or reuse the managed instance name. File removal does not produce a cleanup receipt. There is no automatic expiry, bulk deletion or recreation of unexpectedly missing managed disks without a matching receipt.
Upgrade: the retire and fresh-start commands have been removed, without
aliases. External deletion reconciliation requires the updated srv backend's
cleanup-receipt --instance UUID query. Legacy
retiring records resume as pending deletion, and retired or deleted records
allow a later spawn only with a valid bound cleanup receipt. A legacy deletion
before any allocation needs no receipt. Previously published successors continue
without their predecessor archives. In particular, deleted no longer means a
permanent ban on future compute for that Orb ID. Older dispatcher versions retain
the old behavior; do not mix versions against the same provider state. See the
coordinated deletion-protocol upgrade below.
7.5.2 Operation receipts and bootstrap generations
The dispatcher persists a fresh request ID before start, stop, bootstrap or
delete. Bound start/stop accept --expect REQUEST UUID CREATED_AT BACKEND_ID IMAGE;
unbound human start/stop commands retain their previous behavior. srv checks the
binding and admission under the instance lock. Repeating an admitted start/stop
request never reexecutes it. operation-result REQUEST only reads its stored result.
After a lost outer SSH reply, a matching done result is sufficient to recover.
Known start-validation failures, such as insufficient memory, produce a durable
rejected result with a nonzero exit code. The next spawn may clear that exact
bound attempt and submit a new request ID after the problem is resolved; it never
replays the rejected request. Generic helper, hydration, reconciliation or launch
failures are not classified as rejections. Existing executing/interrupted
records from older versions cannot be retrospectively classified from VM state.
Upgrade srv and the dispatcher together to use this result.
srv-orb-dispatch cancel ORB_ID REQUEST attempts cancellation of a pending
start or stop. srv takes the same instance lock and installs an exactly bound
cancel tombstone only if the request was never admitted. If the worker won the
race, cancel reports its actual phase and never overwrites it. No operator flag
asserts quiescence. Failed, executing or interrupted operations mean unavailable
pending later reconciliation, not safe to retry. A stopped/started observation
or srv reboot alone is insufficient: downstream runner work is not durably bound
to the ingress request at every crash boundary. Stop/start remain fenced, and
the dispatcher refuses delete while either is uncertain.
Bootstrap has a narrower recovery protocol. Before sending credentials the dispatcher fsyncs its next generation and request ID. srv atomically consumes a strictly increasing generation for the exact UUID/creation timestamp, together with request admission. It holds the instance lock through the vsock exchange. A new spawn may supersede an uncertain bootstrap with a higher generation; an equal generation never executes again. Lower/missing/inconsistent provider or backend counters fail closed, rather than catching up or resetting. Pause remains refused while bootstrap is uncertain. Receipt-based deletion is allowed without an intervening spawn, provided the normal cleanup proof succeeds.
The guest serializes generation check, consumption and effects with a lock in
/run/srv-orb. It first records executing, installs KillMode=control-group,
synchronously stops any old unit/job with systemd's replace job mode, and checks
inactive state, no queued job and an empty cgroup. A completed forced kill may
leave systemd's unit in failed state; only after checking no processes remain is
that bookkeeping cleared and inactive state checked again. Only then does it
write the new environment, start the unit, verify active, unlink the environment
file, record done and acknowledge the exact generation. Consuming a generation
is never reported as success. The acknowledgment certifies the old unit's
processes are gone and the replacement exec is active with new credentials;
it does not certify Amp registration.
The journal survives agent restarts within a guest boot and is never part of
disk templates. A guest reboot starts a new Firecracker process, discarding the
old guest's vsock/backlog and unit processes; srv's durable high-water excludes
older host-queued requests. This argument depends on that runtime boundary, not
on arbitrary state rollback. Deleting all /run journal state within a live
guest, restoring coherent old copies of all stores, or cloning backend host keys
is outside the supported recovery model. Preserve state and distinct host keys.
Partial journal loss refuses initialization. No reset/adoption command exists.
Old guests without the echoed generation acknowledgment are rejected.
7.5.3 Authoritative native-Orb deletion
delete NAME --expect REQUEST_ID UUID CREATED_AT BACKEND_ID IMAGE supports both native
Orbs and ordinary VMs. Plain delete NAME and background recovery use the same
durable deletion engine. cleanup-receipt REQUEST reads the stored
result without invoking deletion. Both require an explicit --host through
srv-front. On a failed or lost reply, repeat the same deletion: the dispatcher
queries the receipt and, if missing, resubmits the original identity and request
ID. Never substitute a new ID or downgrade to plain delete.
The former delete-proof SSH command is removed, with no alias. Update the
dispatcher and other callers together with srv and srv-front. The durable
request format and existing receipts are unchanged, so the new syntax can resume
an already-admitted request using its original request ID and identity arguments.
New deletions publish v5 receipts with gateways_absent: true. After preflight
and durable cleanup admission, srv closes this instance's Amp CONNECT, provider
and integration listeners, cancels their upstream requests and upgraded streams,
and waits for admitted handlers (including pending dials) to finish. Gateway
reconciliation cannot reopen the fenced instance from stale inventory. A timeout
leaves cleanup fenced without a receipt; a preflight rejection leaves the live
gateways untouched. Neighboring instances' gateways remain available.
This proves absence of per-instance listeners and active handlers/streams, not
absence of every host socket: shared idle upstream transport pools are retained.
Upgrade srv, srv-vm-runner, srv-net-helper, its systemd unit and
srv-orb-dispatch together. Stop provider admission and srv first, then
stop/drain the old helpers and their children before starting the updated
services. Old unbound helper requests cannot be retrospectively fenced; do not
enable recovery while they can still run. The unit provisions
/var/lib/srv-net-helper for durable network deletion
records. Preserve it alongside the backend state; do not clear it or downgrade
to a helper that ignores incarnation fences. Manual installations must provision
this directory root-owned with mode 0700. The existing root-owned payload lock
must also be installed for storage deletion.
The dispatcher accepts v3, v4 and v5 receipts. Stored v2 receipts remain readable,
unchanged; they do not prove gateway quiescence and cannot finalize a
deleting dispatcher record under the new version. Already-finalized deleted
records backed by v2 receipts still make repeat delete a no-op but reject spawn;
that no-op does not upgrade the historical receipt. Do not rewrite receipts or
tombstones to bypass this distinction.
The existing coordinated runner/nethelper/guest-image protocol requirements still
apply; this change does not deploy or validate any installed host binary.
The backend fences ingress, drains gateways, stops the runtime, and removes cold
storage directly, without hydration. A remote-storage error leaves the instance
in deleting for retry. The runner durably fences the deleted incarnation before
proving runtime/jailer/cgroup absence through cleanup-proof-v2.
The exact recorded start receipt must be closed, and the runner
scans the entire name's receipt journal for corrupt identities or nonclosed
attempts. It checks for no live VM with that name, no jailer workspace or runtime
socket, and no delegated cgroup. This is name-scoped proof, not a separate
UUID-bound enumeration of every historical runtime path. A never-started instance
may have no start attempt: its exact durable deletion fence and vacant runtime
are still required. A missing expected attempt is not treated as absence.
Nethelper binds network
finalization to the incarnation, request and TAP/CIDR, fences late setup/cleanup,
and durably records completion after checking absence. A completed retry does no
more destructive work, even if another instance has since reused the network.
Mutating helper children retain the network lock until exit, including after a
helper crash. Missing/older helper endpoints and unreadable resources fail closed.
For both kinds, srv removes instances/<name> and fsyncs its parent, then atomically
commits the receipt, deleted tombstone and release of
the cleanup fence. Failed cleanup remains charged by the existing srv capacity
accounting. The same request can resume after timeout, service restart or partial
removal, including a missing disk or partially removed instance directory. Missing
owned trees are already complete; filesystem errors are not absence. Btrfs
children retain the existing payload lock so a retry cannot release the allocation
ahead of old filesystem work. Known preflight failures and startup-cancelled
admissions are rechecked; executing/interrupted cleanup requires its original
fence. Another request cannot take it over. Background reconciliation resumes
that same owning request. There is no added scheduler or independent slot counter.
Deletion retains all individual backups and v5 records backups_absent: false.
Ordinary VM deletion removes only the exact recorded Tailscale node, retaining the shared identity
for a completed migration source or an incomplete destination import.
never-minted is derived only for native Orbs with no enrollment-key row and no
node ID. It says nothing about project-managed Tailscale or external copies.
Project templates and shared host snapshots are neither scanned nor removed,
including copies of the Orb's disk/backups. v4 and v5 set snapshots_absent: false
and retained_templates: null: neither makes a copy-erasure or exhaustive template
inventory claim. Cold-storage cleanup must confirm remote absence; missing local
files alone do not establish it.
Receipt/request records survive name reuse. An uncertain bootstrap
can be deleted through this path: the runtime proof closes the guest work and
the backend tombstone prevents late host admission. A persisted start that never
reached the runner is resolved into a closed exact-attempt receipt, fencing its
late arrival. An outcome that remains unknown still blocks deletion.
Do not manually migrate, recreate or reuse managed orb names. A missing managed disk without a committed cleanup receipt causes spawn to fail rather than creating an empty replacement. Migration state is rejected for operator recovery. After receipt-backed deletion, a later Amp spawn can create a distinct successor for the same Orb ID. This does not solve upstream reordering of jobs: the documented contract has no sequence number.
For bootstrap errors, inspect the VM and run, through a trusted guest session:
systemctl status srv-orb-bootstrap.servicejournalctl -u srv-orb-bootstrap.servicesystemctl status srv-orb-guest.service
Treat journal contents as sensitive. No service is enabled at guest boot with an old token: the next spawn supplies fresh credentials and restarts only bootstrap.
7.6 Validate on a real host
Before relying on this provider, create a disposable Amp thread and verify:
- The guest boots and registers with Amp without Tailscale or guest SSH; setup runs successfully. Verify separate VM/Orb lists and common capacity accounting.
- Write a file and install a dependency; pause and wake the thread. Both survive.
Verify
.agents/resumebehavior and fresh-token bootstrap. - Rebuild the prepared image with the runtime above. Start a long-running
workload through Amp's executor,
then pause and wake. Record its PID,
/proc/PID/cgroup, and an in-memory counter before and after. Verify the workload scope is inamp-workload.slice, the counter continues, bootstrap receives a fresh token, and old bootstrap descendants stop. Inspect executor restarts and environment-watcher events withjournalctl -u amp-headless.service -u amp-headless-env.servicewithout printing environment contents or tokens. Open an Amp Terminal, Portal, and Desktop and verify reconnect/service startup. Do not assume old sessions survive. Repeat a project snapshot pause and verify the new thread gets prepared disk contents without the source's in-memory state. - With srv-front, take an unrelated backend out of service and wake the orb on its recorded healthy host.
- Let Amp save a project snapshot; create a second thread from it. Verify prepared dependencies survive, setup is skipped, and machine ID and bootstrap credentials differ. If the project enables Tailscale, verify a fresh node identity too. Verify the original still wakes.
- Delete the source thread, then create another from its snapshot. Verify the template survives while the source VM/disk is removed.
- Under the configured service identity, verify foreign users' VMs are invisible and admin commands are rejected, both directly and through srv-front.
- On a disposable retained thread, use SSH
delete NAME, then send a new message. Verify the thread/history remain readable, the replacement has a different name/UUID and fresh bootstrap credentials, old disk-only files are absent, and repository setup or snapshot activation runs. Change a replacement file, pause/wake and confirm it survives. Repeat the cycle using bound deletion; replay its saved request after replacement and confirm it returns the old receipt without resetting the workspace. Then delete the thread and verify cleanup with all prior receipts retained.
Local automated checks:
go test ./cmd/srv-orb-dispatch ./internal/store ./internal/service ./internal/provision ./internal/front ./internal/vmrunner ./internal/nethelper ./internal/orbguest# From the repository root, download the layer selected by the installer.# The integration checks verify its checksum before installing it.python3 - <<'PYTHON'import runpyimport urllib.requestruntime = runpy.run_path("contrib/amp/orbs/install-runtime.py")with urllib.request.urlopen(runtime["LAYER_URL"], timeout=60) as response: with open("/tmp/amp-runtime.tar.gz", "wb") as layer: layer.write(response.read())PYTHONAMP_RUNTIME_LAYER=/tmp/amp-runtime.tar.gz python3 -m unittest discover -s contrib/amp/orbs -p 'test_*.py'# Disposable root/systemd Linux environment with Bash and sudo only:sudo python3 contrib/amp/orbs/probe_guest_systemd.py --runtime-layer /tmp/amp-runtime.tar.gz
The Go dispatch tests use a subprocess SSH stand-in, not Firecracker or Amp.
The runtime tests install the real pinned layer into a temporary root, check the
allowlist and executable modes, reject a bad checksum before target writes, and
run the vendor environment helper with a systemctl stand-in. Set
AMP_RUNTIME_LAYER to include those integration checks; otherwise they are skipped.
The root probe exercises the real guest handler, systemd jobs, token-holding descendants, and environment lifecycle over a socketpair. It runs the pinned vendor workload launcher from an independent synthetic executor service. Only the slice names are mapped to unique disposable units. It checks workload PID, in-memory identity/counter, scope placement, and executor PID across bootstrap replacement, lost replies, stale requests, and a killed handler's queued start. It also checks old synthetic-token holders are gone. Cleanup stops the executor and workload scopes and removes the probe's units.
These checks do not run authenticated Amp, actual vsock, Firecracker RAM save/restore, Terminal, Portal, or Desktop. They do not establish that real Amp leaves an executor running across a token change, or prove the guest-reset runtime boundary. Run the disposable live cycle above before relying on session continuity. Provision tests additionally check real temporary ext4 images, identity cleanup, retained settings/skills, immutable templates and cancellation. Actual Amp setup-skipping still requires the live cycle above; its internal completion-marker format is not a documented provider contract.
8. Sandboxed AI coding agent
srv makes it straightforward to run AI coding agents in isolated microVMs. Each VM gets its own cgroup limits, per-instance Tailscale identity, and optional provider API proxies that inject host API keys without exposing them inside the guest.
For Amp users, the repository also includes an opinionated plugin that creates the VM, installs a dedicated Amp runner, opens a thread on that runner, and later pushes the thread's branch from the VM.
For an outcome-oriented overview, including Amp remote control, thread URLs, Tailscale development services, and a comparison with Orbs, start with Amp runners on srv.
8.1 Create a VM for an agent
ssh srv new agent-1 --cpus 4 --ram 8G --rootfs-size 30G
Wait for it to report ready:
ssh srv inspect agent-1
Look for state: ready and a tailscale-ip.
8.2 Provider API proxies
When provider API keys such as SRV_ZEN_API_KEY or SRV_DEEPSEEK_API_KEY are configured on the host, srv binds per-instance HTTP proxies on the guest's gateway IP and the provider gateway ports. The proxies:
- Only accept requests from that VM's guest IP
- Forward
/v1/...requests to upstream provider APIs with host keys injected - The guest bootstrap writes
/root/.config/opencode/opencode.jsonand Pi config under/root/.pi/agent/pointing at these gateways
This means the agent inside the VM can use opencode, pi, or any OpenAI-compatible client against the per-provider gateway URLs without ever seeing the real API keys.
8.3 Connect the agent
ssh root@agent-1
The preinstalled opencode and pi CLIs are already configured to target the per-VM gateway. Chromium and agent-browser are also installed; agent-browser is configured to launch the system browser at /usr/bin/chromium instead of downloading a separate browser build.
If you are using a different agent framework, point its API client at:
http://:11434/v1
The gateway IP is the default route inside the VM. You can read it from the inspect output under host-addr.
8.4 Run Amp on a dedicated VM runner
Install the bundled Amp plugin on the workstation where Amp is running:
mkdir -p ~/.config/amp/pluginsln -sf "$PWD/contrib/amp/plugins/srv-runner.ts" ~/.config/amp/plugins/srv-runner.ts
Reload plugins from Amp's command palette after installing or updating it. The plugin expects:
- A Git repository with an
originremote, a checked-out branch that already exists onorigin, and no detached HEAD - Working
ssh srv ...andssh root@<vm-name>access from the workstation - An authenticated Amp installation at
~/.local/share/amp/secrets.json - A local SSH agent when the repository uses an SSH remote
The plugin always copies the Amp credential required by the runner. To add workstation-wide default skills, binaries, private files, guest symlinks, or NO_PROXY entries, create ~/.config/amp/srv-runner.json; see the plugin README and its full example profile. Put repository-specific dependencies and setup in an executable .agents/setup script, which runs inside the cloned repository before the runner starts.
Run srv Runner: New isolated thread from the command palette. The plugin asks for the task, Amp mode, VM size, and explicit consent to copy the Amp credential and configured defaults. It then:
- Creates an
amp-<repository>-<suffix>VM and waits for guest SSH. - Copies the Amp credential and optional workstation-wide profile into the persistent VM.
- Installs Amp, makes a fresh clone of the current branch under
/workspace/repository, initializes submodules, and runs.agents/setupwhen that executable exists. - Configures
amp-runner.serviceto use the VM's per-instance Amp CONNECT gateway, starts a dedicated Amp runner, creates a thread on it, and sends the requested task.
The clone comes from origin; uncommitted and untracked workstation changes are not copied. Credentials remain in the persistent guest until the VM is deleted, so treat the VM as sensitive state.
The plugin also provides commands to show the VM for the current thread, list all managed VMs, start or stop the current VM, retry failed provisioning, and permanently delete a managed VM. Failed provisioning leaves the VM intact for inspection.
8.4.1 Amp remote control and thread features
The dedicated process runs with --remote-control-terminal. It is a normal Amp runner thread rather than a separate agent UI, so the thread remains available through ampcode.com on desktop or mobile with its conversation, visibility, changes UI, and remote terminal while the VM is online.
Amp plugins and agents can target the live runner for additional threads. Scheduled or plugin-created work needs the runner to be online, and Amp cannot currently wake a stopped srv VM; start it first with srv Runner: Start current thread VM. Amp currently limits Multiplayer to Orb-backed threads.
8.4.2 Development services over Tailscale
The VM's Tailscale name is a private network endpoint for more than SSH. Services that listen on a Tailscale-reachable address can be opened directly from authorized tailnet devices over TCP or UDP—for example a web app on http://<vm-name>:3000 or a database on <vm-name>:5432.
This covers the connectivity role of an Amp Portal and supports more protocols, but it does not embed the service in the Amp thread, create Amp-managed HTTPS, or grant access based on thread visibility. Tailnet ACLs control access. See Networking overview.
8.5 Push an isolated thread's branch
From a plugin-managed thread, run srv Runner: Push current VM branch…. This command only supports SSH Git remotes. Before asking for confirmation, it reads the VM's current branch and commit over host-key-verified SSH. The confirmation shows the repository, branch, and abbreviated commit that will be pushed.
After confirmation, the plugin temporarily forwards the workstation's SSH agent and pushes that exact commit to the same branch. The push:
- Aborts if the VM's branch or commit changes after confirmation
- Uses a temporary bare repository and disables repository hooks and global/system Git configuration for the operation
- Requires strict host-key checking for the Git server
- Ends agent forwarding when the command completes, with a two-minute overall timeout
The push does not include uncommitted changes. Commit all intended VM changes first.
8.6 Resource limits
Each VM runs in its own cgroup v2 leaf with:
cpu.max— capped at the vCPU countmemory.max— capped at the requested guest RAM plus a small Firecracker overhead reservememory.swap.max— set to 0 (no swap)pids.max— default 512, configurable viaSRV_VM_PIDS_MAX
This prevents a misbehaving agent from consuming the entire host.
8.7 Clean up
ssh srv delete agent-1
For a plugin-managed thread, srv Runner: Delete current thread VM removes the VM, persistent checkout, copied Amp credential, workstation profile files, and local plugin record.
8.8 Multiple agents
Create as many agent VMs as the host can hold. Each gets independent networking, identity, and resource limits:
ssh srv new agent-2 --cpus 2 --ram 4Gssh srv new agent-3 --cpus 2 --ram 4G
Use ssh srv status to check remaining host capacity before creating more.
9. Architecture
srv is a single-host control plane that manages Firecracker microVMs through an SSH command surface on a Tailscale tailnet.
9.1 Control plane
┌────────────────────────────────────────────────────────┐│ srv process ││ ││ ┌──────────┐ ┌──────────────┐ ┌──────────────────┐ ││ │ tsnet │ │ gliderlabs/ │ │ authorization │ ││ │ :22/tcp │──│ ssh │──│ (Tailscale │ ││ └──────────┘ └──────────────┘ │ WhoIs) │ ││ └──────────────────┘ ││ ││ ┌──────────┐ ┌──────────────┐ ┌──────────────────┐ ││ │ SQLite │ │ reflink │ │ Tailscale API │ ││ │ store │ │ cloner │ │ (auth key │ ││ └──────────┘ └──────────────┘ │ minting) │ ││ └──────────────────┘ ││ ││ ┌─────────────┐ ┌─────────────────────────────────┐ ││ │ Provider │ │ per-VM HTTP proxies │ ││ │ gateways │ │ (inject host API keys) │ ││ └─────────────┘ └─────────────────────────────────┘ │└────────────────────────────────────────────────────────┘ │ │ │ ┌────┴────┐ ┌────┴────┐ ┌────┴─────┐ │ net- │ │ vm- │ │ Tailscale│ │ helper │ │ runner │ │ coord. │ │ (root) │ │ (root) │ │ server │ └────┬────┘ └────┬────┘ └──────────┘ │ │ ┌────┴────┐ ┌────┴─────────────┐ │ TAP + │ │ Firecracker │ │ iptables│ │ + jailer │ │ + NAT │ │ → srv-vm:srv │ └─────────┘ │ → cgroup v2 │ └──────────────────┘
9.2 Key components
9.2.1 tsnet + gliderlabs/ssh
srv joins the tailnet as the hostname configured in SRV_HOSTNAME (default srv) and listens on the tailnet TCP port configured in SRV_LISTEN_ADDR (default :22). The gliderlabs/ssh library handles SSH exec requests and rejects shell sessions.
Caller identity comes from Tailscale WhoIs data resolved from the incoming tailnet connection — not from the SSH username.
9.2.2 SQLite store
All instance state, event history, command audits, and authorization decisions are stored in SQLite under SRV_DATA_DIR/state/app.db. Migrations run during startup and are additive.
9.2.3 Reflink cloning
When a new VM or Orb is created, the base rootfs is reflink-cloned on btrfs into a dedicated instances/<name>/disk subvolume. This gives each instance its own writable rootfs.img while initially sharing data extents. All base rootfs images must be on the same btrfs filesystem as the data-root subvolume. Legacy stopped instances migrate automatically on start using a durable journal; see storage migration.
9.2.4 Network helper
A root-only helper process owns all TAP device creation, iptables MASQUERADE rules, and FORWARD rules. The main srv process communicates with it over a unix socket.
9.2.5 VM runner
A root-owned process invokes Firecracker through the official jailer binary. After the jailer sets up the chroot and drops privileges, the microVM process runs as srv-vm:srv. Each VM is placed into its own cgroup v2 leaf under firecracker-vms/<name> with enforced limits.
The runner bind-mounts the disk, kernel, initrd, and log files into the jail.
Only the Orb socket is hard-linked, so Orb runtime and jail directories must
remain in the same subvolume. The main srv process gains no new capabilities.
9.2.6 Tailscale integration
For each new VM, the control plane:
- Mints a one-off Tailscale auth key using the configured OAuth credentials and tags
- Injects the key into the VM's MMDS payload
- The guest bootstrap service reads the key and runs
tailscale up --auth-key=... --ssh
On warm reboots (after a stop + start or restart), the guest reuses its persisted tailscaled state instead of minting a new key.
9.2.7 Provider gateways
When SRV_ZEN_API_KEY or SRV_DEEPSEEK_API_KEY is set, srv binds a per-instance HTTP proxy on each VM's gateway IP and the provider's configured port (SRV_ZEN_GATEWAY_PORT for Zen, SRV_DEEPSEEK_GATEWAY_PORT for DeepSeek). The proxies forward guest requests to the upstream APIs while injecting the host keys. See Provider gateways for details.
9.3 Data paths
SRV_DATA_DIR/├── state/│ ├── app.db # SQLite store│ ├── tsnet/ # Tailscale persistent state│ └── host_key # SSH host key├── images/│ └── arch-base/│ ├── vmlinux # Guest kernel│ └── rootfs-base.img # Base rootfs (reflink source)├── instances/│ └── / │ ├── disk/ # btrfs disk subvolume│ │ └── rootfs.img # Writable reflink clone│ ├── serial.log # Serial console output│ └── firecracker.log # VMM log├── backups/│ └── / │ └── / │ └── rootfs.img # Backup copy├── jailer/ # Jailer workspaces└── .snapshots/ # btrfs archive subvolume └── /
Host snapshots are root-and-disk bundles with a manifest, not recursive snapshots of the data root. They do not provide global disk atomicity. Optional cold storage over SSH moves stopped disks to a trusted btrfs server and restores them fully before boot. The root runner owns transfer journals and shares its name lock with VM starts; the unprivileged control plane gains no filesystem capabilities. Complete host snapshots require all cold generations hydrated and purged first.
9.4 Service architecture
| Service | User | Role |
|---|---|---|
srv.service |
srv |
Main control plane (tsnet, SSH, SQLite, API) |
srv-net-helper.service |
root |
TAP, iptables, NAT management |
srv-vm-runner.service |
root → srv-vm:srv |
Firecracker invocation, cgroup management |
The srv-vm-runner process starts as root, and the jailer drops the Firecracker process to srv-vm:srv within each VM's cgroup v2 leaf.
10. SSH command reference
All srv commands are invoked through the SSH surface. The service treats SSH as command transport only — there is no shell session.
10.1 Syntax
ssh srv [args]
For machine-readable output, use --json with supported non-streaming commands such as list, inspect, status, integration ..., and pool .... With OpenSSH, terminate local option parsing first:
ssh srv -- --json listssh srv -- --json inspect demossh srv -- --json status
10.2 Instance commands
| Command | Description |
|---|---|
new <name> |
Create a new VM |
new <name> --image <name> |
Select a configured guest image, e.g. debian-13 (default: arch) |
new <name> --image <name> --template <id> |
Clone an owner-scoped prepared project template; requires explicit --host through srv-front |
new <name> --integration <name> |
Create and enable one or more existing integrations (admin only) |
new <name> --guest-network host |
Create a VM that does not join the tailnet and is reached by SSH from the host; see Guests without Tailscale |
new <name> --guest-network external-only |
Create a VM that does not join the tailnet and may only reach the internet through SRV_EXTERNAL_UPLINKS; see External-only guests |
new <name> --cpus <n> |
Create with custom vCPU count |
new <name> --ram <size> |
Create with custom memory (2G, 512M, or MiB integer) |
new <name> --pool <name> --ram <size> |
Create a pooled-memory VM in an existing memory pool |
new <name> --rootfs-size <size> |
Create with custom rootfs size |
list |
Show visible VMs (all for admins, own for regular users) |
orb list |
Show visible Orbs only |
list --all |
Show both workload kinds, still subject to ownership rules |
orb new <name> --image <name> |
Create an Orb with a prepared Orb image; uses host vsock instead of guest Tailscale enrollment |
inspect <name> |
Show VM details and event history |
logs <name> |
View serial log (default) |
logs <name> serial |
View serial log |
logs <name> firecracker |
View Firecracker VMM log |
logs -f <name> [serial|firecracker] |
Follow log output |
top [--interval <duration>] |
Watch live per-VM CPU, memory, disk, and network usage; run with ssh -t and press q to exit |
10.3 Lifecycle commands
Lifecycle commands work for both VMs and Orbs. Names share one namespace per
backend; the image name does not determine the workload kind. Existing instances
remain VMs. See Amp orbs for bootstrap and optional
project networking. orb bootstrap <name> is a streaming provider command:
credentials are JSON on stdin, never command arguments; it does not accept --json.
| Command | Description |
|---|---|
start <name> [--discard-state] |
Resume saved RAM automatically; optionally discard it and cold boot. Also rechecks readiness in awaiting-tailnet / awaiting-guest. Guests without Tailscale never resume saved RAM and refuse stop --save-state |
stop <name> [--save-state | --cache-state] |
Graceful shutdown by default. --save-state must save RAM and device state for one resume, or fail. --cache-state saves them only if the host RAM cache has room; srv may discard that image later and boot from disk |
restart <name> |
Stop and start a VM |
fsck <name> |
Force-check and repair the rootfs of a stopped VM |
delete <name> |
Delete an instance's runtime, network, and local/cold disk allocation |
delete <name> --expect REQUEST_ID UUID CREATED_AT BACKEND_ID IMAGE |
Delete the exact expected incarnation; return its durable JSON cleanup receipt |
cleanup-receipt REQUEST_ID |
Read the stored cleanup receipt without executing deletion |
cleanup-receipt --instance UUID |
Read the deleted incarnation's receipt as its original owner or an administrator, without knowing the deletion request ID |
Deletion uses the same durable workflow for VMs and Orbs. It drains gateways,
stops the runtime, removes any remote cold disk without hydration, and only marks
the instance deleted after cleanup succeeds. Once cleanup has begun, a failure
leaves it deleting; background reconciliation or another delete resumes the
same request. A preflight rejection need not change the instance's state. All backups
(including legacy Orb backups), project templates and shared host snapshots are
retained. A fresh delete NAME selects the current incarnation: automation replaying
an old request after name reuse must use delete NAME --expect … instead. Bound
deletion and receipt queries require an explicit --host through srv-front.
The former delete-proof command is no longer accepted; there is no alias.
The updated runner and network helper are required; drain old helper work during
the coordinated upgrade described in Orb deletion.
10.3.1 Manual deletion
Here srv-a is a direct backend SSH endpoint. These commands actually delete the
active environment; substitute the intended instance name. No preceding stop
or disk hydrate is required. Cold storage holds the offloaded active disk, not
an independent backup, so deletion removes it too.
# Normal VMssh srv-a delete demo# Orb: the same command, not "orb delete"ssh srv-a delete dev-orb
Successful text output for demo:
deleted: demostate: deleted
Repeat delete demo to resume an incomplete deletion. It reports an error if the
instance is already deleted. If the name has been reused, however, it selects the
new instance. Use bound deletion for delayed jobs and automated retries.
For an Amp-managed Orb, manual SSH deletion discards compute, not the Amp thread.
The next Amp spawn retrieves the exact instance's cleanup receipt and creates
fresh compute with a new name and UUID. No provider-side retire command is
needed or accepted. Pause without deletion still retains the workspace. See
discard compute and continue the same thread.
10.3.2 Bound deletion and retries
delete NAME --expect REQUEST_ID UUID CREATED_AT BACKEND_ID IMAGE deletes only
the expected incarnation and returns a JSON cleanup receipt without needing
--json.
| Argument | Source and meaning |
|---|---|
NAME |
.instance.name from JSON inspect |
REQUEST_ID |
A new UUID for this deletion request; keep it unchanged on retry |
UUID |
.instance.id, the instance UUID, not the request UUID |
CREATED_AT |
.instance.created_at, preserving the returned timestamp |
BACKEND_ID |
.instance.backend_id, the backend SSH host-key fingerprint, not a frontend host name |
IMAGE |
.instance.image |
Prepare the request once, using local jq and uuidgen. Keep these files until
the operation is resolved. Do not overwrite them or repeat this preparation when
retrying: a fresh inspection could select a replacement instance.
ssh srv-a -- --json inspect demo > demo-before-delete.json && uuidgen > demo-delete-request.txt
Execute the following Bash script to submit or retry the saved request. It stops if the saved inputs cannot be read:
set -erequest=$(cat demo-delete-request.txt)name=$(jq -er '.instance.name' demo-before-delete.json)id=$(jq -er '.instance.id' demo-before-delete.json)created=$(jq -er '.instance.created_at' demo-before-delete.json)backend=$(jq -er '.instance.backend_id' demo-before-delete.json)image=$(jq -er '.instance.image' demo-before-delete.json)ssh srv-a delete "$name" --expect \ "$request" "$id" "$created" "$backend" "$image"
Use the same authenticated user and exactly the same arguments on every retry. A mismatched identity is rejected. An incomplete request resumes; a completed request returns its stored receipt without deleting a later same-name instance. This replay contract applies to deletion, not to all start/stop operations.
10.3.3 Query completion after a lost reply
ssh srv-a cleanup-receipt "$(cat demo-delete-request.txt)"
This only reads the receipt; it does not execute deletion. A receipt establishes completion. An error means no receipt could be retrieved, not that deletion had no effects. If needed, resubmit the original bound request above.
For manual deletion, or when another administrator performed deletion, query by the original instance UUID saved before deletion instead:
ssh srv-a cleanup-receipt --instance "$(jq -er '.instance.id' demo-before-delete.json)"
This lookup is available to the deleted instance's original owner and current administrators, even after name reuse. It does not grant the new same-name instance's owner access to the old receipt. Request-ID lookup still requires the user who owns that deletion request. Neither lookup starts or retries deletion.
The backend's bound-deletion and receipt handlers return exit code 75 for handled errors, including an uncommitted receipt or mismatched request. Do not interpret that code as proof that nothing changed. Transport and frontend errors may use other exit codes.
10.3.4 Deletion through srv-front
Here srv is the frontend and a is its configured backend name. For preparation
through the frontend, replace the direct inspect command above with:
ssh srv -- --json inspect demo --host a > demo-before-delete.json && uuidgen > demo-delete-request.txt
For manual deletion, submission using the saved variables above, or receipt lookup:
ssh srv delete demo --host assh srv delete "$name" --host a --expect \ "$request" "$id" "$created" "$backend" "$image"ssh srv cleanup-receipt "$(cat demo-delete-request.txt)" --host assh srv cleanup-receipt --instance "$id" --host a
These are alternative operations, not a sequence to run together. Bound deletion
and receipt lookup require explicit --host; a does not replace BACKEND_ID.
When using the bound frontend example, load the saved variables but replace the
direct ssh srv-a delete line with the frontend submission line.
10.4 Cold disk commands
| Command | Description |
|---|---|
disk status <name> |
Inspect local/remote disk residency without contacting remote storage |
disk offload <name> |
Upload and evict a stopped instance's disk after verified remote publication |
disk hydrate <name> |
Restore/recover a stopped disk without booting |
disk purge <name> |
Delete a retained remote generation; requires a valid local disk |
Supports --json and backend-qualified names through srv-front. Mutations on
native Orbs require admin access. start, migration preparation, export,
backup/restore, template creation, resize and fsck hydrate automatically when
needed. Offline commands still require a stopped instance; migration can stop
the source itself. Host snapshots still require explicit hydration and purge. See
configuration, outage behavior and recovery.
10.5 Resize command
| Command | Description |
|---|---|
resize <name> --cpus <n> |
Resize vCPUs on a stopped VM |
resize <name> --ram <size> |
Resize memory on a stopped VM |
resize <name> --pool <pool> |
Assign a stopped VM or Orb to an existing memory pool, or switch pools |
resize <name> --fixed-memory |
Remove a stopped VM or Orb from its memory pool |
resize <name> --rootfs-size <size> |
Resize rootfs (stopped VM, grow-only) |
All flags can be combined except --pool and --fixed-memory, which are mutually exclusive. Omitted flags keep the current value.
For pooled VMs, resize --ram keeps the VM in the same pool unless --pool or --fixed-memory is also supplied. The VM or Orb must be stopped, and the final guest-visible RAM must fit within the target pool's reservation when using a pool. Both resize --pool and resize --fixed-memory without --ram preserve the current RAM size. Fixed-memory host capacity is checked on the next start; leaving a pool does not delete it or release its reservation.
10.6 Backup commands
| Command | Description |
|---|---|
backup create <name> |
Create a backup from a stopped VM |
backup list <name> |
List backups for a VM |
backup delete <name> <backup-id> |
Permanently delete a backup |
restore <name> <backup-id> |
Restore a stopped VM from a backup |
Backup and restore commands support normal VMs only. Orbs reject all four commands, including for admins. Old Orb backups remain untouched even when the Orb is deleted; clean them up manually if desired. Project templates remain supported.
10.7 Project templates
| Command | Description |
|---|---|
project-template create <name> <id> |
Save an immutable, identity-cleaned copy of your stopped VM |
project-template verify <name> <id> |
Verify an existing template belongs to the stopped source; never recreate a missing template |
project-template delete <id> |
Delete a template in your owner namespace; does not delete VMs created from it |
These commands support --json and require explicit --host through srv-front.
Unlike backups, templates create new identities rather than restore an existing
VM. Templates outlive their source VM. See Amp orbs
for storage, security and retention requirements.
10.8 Transfer commands
| Command | Description |
|---|---|
export <name> |
Stream a stopped VM as a tar artifact to stdout |
import |
Read a tar artifact from stdin and recreate the VM |
import --pool <name> |
Import into an existing destination memory pool |
import --fixed-memory |
Explicitly import with fixed memory, including pooled exports |
Usage: ssh srv-a export demo | ssh srv-b import
Pooled exports require an explicit destination memory policy. For coordinated
cold migration, host-qualified names, and node list across servers, see the
multi-host frontend.
10.9 Admin and host commands
| Command | Description |
|---|---|
pool create <name> --size <size> |
Admin-only create a reserved memory pool |
pool resize <name> --size <size> |
Admin-only shrink or grow a memory pool live, with usage checks before shrinking |
pool list |
Admin-only list reserved memory pools |
pool inspect <name> |
Admin-only show a memory pool and its member VMs |
pool delete <name> |
Admin-only delete an empty memory pool |
status |
Admin-only host capacity and allocation summary |
snapshot create |
Admin-only host-local readonly root-and-disk snapshot bundle with a manifest |
wazuh enable <name> |
Admin-only opt a tailnet VM in to Wazuh enrollment; VMs are opted out by default (Wazuh agent) |
wazuh disable <name> |
Admin-only opt a tailnet VM out of Wazuh enrollment again |
pool resize sets the total reservation, not a size delta. The size must be
positive and at least as large as each member's configured guest RAM, not the
sum of their RAM. Growing also requires enough host reservation budget.
Shrinking releases reservation budget without changing VM RAM or membership.
Members may be running (ready) or stopped. Retry after any start, stop,
failure cleanup, or migration has finished. Before lowering a live cgroup limit,
srv requires the target to exceed its current usage by at least 256 MiB or 10%
of the target, whichever is larger. An unused pool with zero usage needs no
headroom. Missing or invalid usage readings reject the shrink. There is no
force option and no forced reclaim or balloon inflation.
The check is a snapshot: concurrent allocations and later workload growth can still reach the new hard limit and trigger the OOM killer. A successful resize does not guarantee that future workloads fit.
Growth reserves host budget before raising the live limit; shrinking releases budget only after the runner durably confirms the lower limit. If a request's outcome is unknown, srv keeps the reservation and a persistent pending operation. Other resize targets, pool deletion, and new VM starts or assignments into that pool are blocked until the outcome is resolved. Retry the same resize command and target size, including after a control-plane restart.
Even a confirmed rejection of growth keeps the increased reservation: a runner error does not always prove that the limit was unchanged. After fixing the runner error, resize to the desired size again to apply it or recover the budget.
The runner stores operation receipts in instances/.pool-resizes/, including
rejections. Retries return the recorded result instead of changing the limit
again. Receipts survive pool deletion and runner restarts; do not remove them
while the host is in use. A confirmed rejection clears the pending operation,
so a later command can try again after usage falls. Repeating the current size
with no pending operation synchronizes the live limit. Both the control plane
and VM runner need the updated binary and the /pool/resize protocol.
10.10 Integration commands
All integration commands are admin-only.
| Command | Description |
|---|---|
integration list |
List configured integrations |
integration inspect <name> |
Show integration target, auth mode, header references, and timestamps |
integration add http <name> --target <url> |
Create an HTTP integration |
integration add http <name> --target <url> --header NAME:VALUE |
Add a static upstream header |
integration add http <name> --target <url> --header-env NAME:SRV_SECRET_FOO |
Add an env-backed upstream header |
integration add http <name> --target <url> --bearer-env SRV_SECRET_FOO |
Inject bearer auth from a host env var |
integration add http <name> --target <url> --basic-user USER --basic-password-env SRV_SECRET_BAR |
Inject basic auth from host-managed credentials |
integration delete <name> |
Delete an integration that is no longer enabled on any VM |
integration enable <vm> <name> |
Enable an integration for a VM |
integration disable <vm> <name> |
Disable an integration for a VM |
integration list-enabled <vm> |
List integrations currently enabled for a VM |
10.11 Notes
newaccepts--cpus,--ram,--pool, and--rootfs-sizein any combination that matches the memory mode contractnew --pool <name>requires--ram <size>because guest-visible RAM stays explicit in pooled modenewandorb newexit with status 3 when admission refuses the create (host memory budget, pool size or disk floor) before anything is allocated; srv-front passes that status through and also uses it when no host is eligible. Other failures keep exit status 1newalso accepts repeated--integration <name>flags; the create request fails if any requested integration cannot be enabled- Fixed mode remains the default. Without
--pool,--rammeans guest-visible RAM; the hard per-VM host cgroup cap is that RAM plusmax(256 MiB, RAM/16)Firecracker overhead reserve - In pooled mode,
--rammeans guest-visible RAM while host reservation comes from the pool created withpool create - Pool ballooning checks measured cgroup usage every five seconds. Above 80% of the pool limit, it requests bounded reclaim toward 75%. Reclaim and memory returns each have a separate pool-wide budget of at most 512 MiB or 5% of the pool per round, whichever is smaller, so donors cannot consume the budget needed to help a pressured guest. Below the trigger it holds targets, returning memory when a guest needs headroom and the pool has space below 90%. These thresholds are best-effort defaults, not OOM guarantees.
- Fixed VMs use free-page reporting without active balloon inflation. Pool VMs aim to retain guest headroom of at least 256 MiB or one eighth of guest RAM, and balloon targets are capped at half of guest RAM. Outstanding requests are tracked; stalled inflation is cancelled after 30 seconds without progress. After startup, pool resize, a target change or actual balloon progress, the runner observes for at least ten seconds before requesting further inflation. New inflation and memory grants wait until every current member's target and actual size have been observed; missing guest statistics do not count as free capacity.
- Balloon targets and actual balloon sizes are not measurements of host RAM saved: free-page reporting may already have released those pages. The pool's hard
memory.maxremains authoritative, with swap disabled. The runner logspool pressure without responsive safe balloon donorswhen pressure persists without pending reclaim or a new safe request; inspect guest responsiveness, reduce demand or grow the pool rather than relying on ballooning to recover memory that every guest is actively using. resizerequires the VM to be stopped; CPU and RAM may increase or decrease within limits, while rootfs is grow-onlyresize --pool <name>moves a fixed-memory or pooled VM or Orb into an existing pool;resize --fixed-memoryswitches back to fixed memoryresize,fsck,backup, andrestoreall require the VM to be stopped- Backups are tied to the original VM record — they cannot be restored onto a different VM
- Export requires the source VM to be stopped
- Import recreates the VM under the same name and leaves it stopped
toprefreshes continuously by default; usessh -t srv top --interval 2sor similar to slow the redraw rateinspectshowsmemory-modeand whether host reservation is dedicated or shared via a poolstatusmemory accounting now splits fixed reservations from pool reservations so pooled member VMs are not double-countedtopshows live/configured RAM for every VM and appends the pool name for pooled rows- Integration targets are intentionally narrow in v1: HTTP only, operator-managed, no guest-supplied raw secrets, and no automatic outbound interception
11. Testing
srv separates fast correctness checks, generated lifecycle models, process-crash matrices, fuzzing, and mutation checks. Use the narrowest tier that exercises the changed boundary.
11.1 Fast
go test ./...go vet ./...gofmt -l cmd internal
The default suite covers the store, provision, service, vmrunner, nethelper, config, front, and CLI packages. It needs no root, no KVM, and no network.
11.2 Race
GORACE=atexit_sleep_ms=0 go test -race -count=1 -timeout=15m ./...
cmd/srv-orb-dispatch re-execs the race-instrumented test binary for every fake
SSH call. Disabling the race runtime's atexit sleep keeps that harness inside the
package timeout; without it the package can exceed the default limit.
11.3 Generated lifecycle model
go test ./internal/store -run '^TestLifecycleStateMachine$' -count=1
Hegel generates up to 15 operations per case over a fresh SQLite store: create, admit fresh/same/changed requests, begin/finish starts and bound cache stops, begin/commit cleanup, reserve/fresh/existing/collision imports, create an import instance, finalize, and interrupt. An independent model tracks instance state, request binding/phase/exit, fence, cache-stop binding, cleanup receipt, and import receipt. A SQLite trigger injects binding-write failure during generated cache stops. Generation is derandomized, and eligible IDs are sorted for replay and shrinking.
The store model remains sequential. A separate service property test generates
groups of inspect, stop, delete, and migration prepare commands and queues
them behind a runner RPC barrier, then races two retries of the original stop.
It checks the actual command handlers and SQLite, including absence of conflicting
fences and exactly one successful retry. It does not enumerate all schedules.
go test ./internal/service -run '^TestConcurrentCacheStopLifecycle$' -count=1
Set HEGEL_STATISTICS=1 to print rule-event counts.
11.4 Provision policy matrix
go test ./internal/provision -run '^TestProvisionPolicyMatrix$' -count=1
Exhaustively combines migration phase (none/preparing/prepared/completed/aborted),
import receipt (none/importing/imported), and cleanup fence (none/fenced). It
asserts PrepareMigration and DeleteWithProof outcomes, file removal,
tombstones, and receipts. Interrupted preparing retries are exercised with the
matching token/target and with a changed binding. The preparing/prepared/completed
plus importing combinations are unreachable through the public import path and are
skipped.
11.5 Process-crash matrices
internal/store: SIGKILL at every scripted lifecycle boundary, reopen, and exact durable-prefix checks.internal/vmrunner: SIGKILL while holding the name lock, SIGKILL after the accepted receipt is durable, receipt-scan recovery, and a started receipt whose runtime cannot be verified.internal/nethelper: setup/cleanup failures at every command, retry idempotence, missing-state tolerance, and existing-rule skipping.internal/provision: import staging/commit-failure, cleanup admission window, restore retry after a partial replacement, and missing-rootfs start refusal.
These cover process crashes, not power-loss durability or fsync ordering.
11.5.1 Bound Orb pause recovery
| Fault boundary | Injection | Expected result |
|---|---|---|
| SQLite admission, binding commit, terminal receipt | SIGKILL after each scripted step; trigger aborts the binding insert inside the transaction | Admission alone is cancelled; the binding and executing survive together; done does not reopen. |
| Service before runner RPC | Trigger rejects stopping; run startup sweep, inspect a halted serial log, and try other stops |
No plain or competing stop is sent; explicit recovery uses the same request and managed start. |
| Delete while the bound stop still owns a live VM | Reject shutdown, then issue delete |
No cleanup fence is committed; the original stop can still resume. |
| Migration while the bound stop still owns a live VM | Reject shutdown, then prepare with no migration or with an aborted migration | No preparing record is committed, and the original stop can still resume. |
| Runner shutdown rejected, then VM exits independently | Firecracker fixture rejects shutdown; the test kills the subprocess and reads the start receipt | The start receipt can close, but does not prove the stop. |
| Shutdown acknowledged without exit | Firecracker fixture acknowledges the first shutdown but exits only on the next request | The first attempt times out without killing the VM; the same bound retry reissues shutdown. |
| Runner confirms action, but cleanup fails | Fake cgroup fails removal; a fresh runner reloads the receipt | Original stop can finish on the same host boot. An unclosed receipt from a previous boot cannot prove exit. |
| RAM capture or graceful shutdown succeeded, reply lost | Repeat the same bound request, then try a different stop ID | Only the original ID can obtain the completed stop's proof. |
| Service after runner proof | Helper rejects network cleanup; triggers reject stopped or done writes |
No premature terminal receipt; a retry can finish with the same proof. |
| Immediate cold offload with cache opt-in | Run the service fault sequence with immediate offload enabled | The binding survives without RAM capture; offload begins only after done. |
| Dispatcher after a lost reply with a restarted Orb | Backend fixture publishes the original terminal receipt and presents a running Orb on inspect | Plain pause completes the original request; snapshot pause reports a conflict. Neither stops the successor. |
The Service tests run the actual command handler, provisioner, and SQLite with Unix-socket helper doubles. Runner tests use real receipts, pidfds, and a VMM subprocess fixture. They do not simulate power loss, all kernel I/O errors, or real Firecracker end to end.
11.6 QEMU integration tests
python3 test/qemu/run.py all --kernel /path/to/vmlinuz \ --modules /path/to/lib/modules/KERNEL_VERSION --busybox /path/to/busybox
Run net, durability, btrfs, or front instead of all for a single suite.
The harness uses x86-64 QEMU with TCG, a matching Linux kernel and module tree, static BusyBox,
Go, kmod, and Python 3. Durability also needs mke2fs; networking copies
ip, iptables-nft (with Debian's amd64 xtables library layout), and nft
into the initramfs with their libraries. The Btrfs suite needs zstd, GNU cp,
a guest kernel with Btrfs support, and btrfs-progs 6.10.1 or newer (or a
backport of the reverse-receive fix). The harness copies
btrfs from PATH. Use --logs DIR to keep the guest console output. The host
needs neither root nor KVM. QEMU has no external NIC.
-
DRBD (separate
drbdmode, not part ofall): Use the same command with a module tree containing DRBD 9 and its TCP transport. ThedrbdCI job builds the pinned driver for the guest kernel. The host also needsdrbd-utils,mkfs.btrfs, andsqlite3. No DRBD resource or module runs on the host. Two QEMU guests replicate over a private socket link using Protocol C, Single-Primary andquorum off, as in the failover runbook. The harness records SQLite commits over serial and kills the primary QEMU process. With synchronised disks, B must recover every acknowledged value and commit a new one while A is offline. A then boots from its original disk as an unmounted Secondary. After resync, B unmounts and demotes. A takes over, reads the complete journal (including B's write), and commits another value. A forensic guest without a network link checks the full journal on a copy of A's disk. Four more runs cover replacement and failure cases:- Replacement after losing A's disk: B stays Primary while a fresh A joins
with an empty disk as an unmounted
SyncTarget. B receives the token before A boots and commits it on observingSyncSource. B checks its role in the resync before and after the ACK; its DRBD event stream through demotion must show one uninterrupted resync. After full resync and a planned handoff, A must read that commit and accept another. An isolated guest checks all five acknowledged values on a copy of the replacement disk. - Link loss without a crash: B observes a DRBD disconnect event and remains unmounted. A acknowledges a solo write, stays Primary and reconnects. Only after resync and planned demotion of A does B take over. Its isolated disk must contain the solo write as well as a subsequent write on B.
- Link loss followed by a crash: after A acknowledges a solo write, the harness kills A and boots it from its original disk with no replication NIC. Both nodes must stay disconnected, Secondary and unmounted. Separate offline inspections must find the solo write on A and only the earlier commits on B.
- Missing evidence: the fixture stops its
drbdsetup events2observer while the disks are current, then kills A. B stays passive even though its disk still reportsUpToDateand a later offline inspection finds all rows.
These are storage tests. The disconnect notification comes from a test observer; the harness plays the manual operator. They do not certify a monitoring deployment, automatic promotion policy, physical power loss, fencing hardware, or Firecracker guest recovery. For the service-level checks, see the disposable two-host pilot.
- Replacement after losing A's disk: B stays Primary while a fresh A joins
with an empty disk as an unmounted
-
Frontend: Run
srv-frontand twosrvprocesses in one guest, with separate Btrfs subvolumes and pinned SSH host keys. A client on a local test tailnet runsnode listover SSH. Both backends must return their own hostnames;--host bmust return only the second. Only the client's tailnet login has admin access. No external tailnet credentials or nested Firecracker VMs are used. -
Btrfs: Mount two disposable virtio disks in the guest. Run the cold-store send/receive tests with and without zstd, including incremental restore and checksum rejection. Run the migration preflight against a store on the source filesystem and a store on the other disk; only the first may pass. This suite uses the guest kernel's Btrfs implementation and does not launch Firecracker.
-
Durability: Record the guest's block writes and flushes over NBD. For each checkpoint, start a new guest with a disk rebuilt through the last flush. Check the SQLite request and its binding across admission, execution, and completion, and verify the runner's accepted and closed start receipts. A deliberately unflushed raw write disappears in flush-only replay but survives full replay. In disposable source copies,
PRAGMA synchronous = OFFfailed at admission (no new flush), and removing the runner's post-rename directory sync failed when the accepted receipt was missing after reboot. -
Networking: Run the real nethelper with Linux TAPs, network namespaces, and iptables-nft. Exercise permitted and denied packet flow, NAT, and cleanup isolation. Check that an orphan firewall rule blocks absence proof and that retrying an old cleanup receipt preserves a reused TAP's policy.
11.7 Firecracker and Btrfs recovery
Run on a disposable Linux host with root, systemd, /dev/kvm, Btrfs and
loop-device support, btrfs-progs, and iproute2. Supply a compatible static
Firecracker and jailer, and the prepared Orb kernel and rootfs from the
Orb setup guide. Build all three srv binaries from the same
checkout:
go build -o /tmp/srv-vm-runner ./cmd/srv-vm-runnergo build -o /tmp/srv-cold-store ./cmd/srv-cold-storego test -c -o /tmp/srv-service.test ./internal/servicesudo python3 test/firecracker_orb_ram_cache.py \ --runner /tmp/srv-vm-runner --cold-store /tmp/srv-cold-store \ --firecracker /path/to/firecracker --jailer /path/to/jailer \ --kernel /path/to/vmlinux --rootfs /path/to/rootfs.img \ --service-recovery /tmp/srv-service.test
The harness kills a process running the real service command handlers at two
barriers: after done but before delivering the reply, and after the runner
returns bound stop proof but before the service finishes the stop. A fresh
process opens the same database, runs the startup receipt sweep, and either
reads done without the runner or resumes the original executing request.
Both cases then offload and hydrate the Btrfs disk, boot without cached RAM,
and check the file written before the stop. Tailnet command delivery, network
cleanup, and SSH transport to cold storage are fixtures; Firecracker, the
guest agent, SQLite, and Btrfs send/receive are real. The test does not contact
an installed srv.
11.8 Fuzzing
go test -run='^$' -fuzz='^FuzzSetupHandler$' -fuzztime=20s ./internal/nethelper
Targets:
| Package | Targets |
|---|---|
internal/provision |
portable manifest validation, portable TAR parsing |
internal/nethelper |
setup HTTP handler |
internal/storage |
mountinfo line parsing, mountinfo unescaping |
internal/service |
command request, import options, size, integration gateway path |
internal/config |
provider base URL, guest auth tags, machine shape |
internal/vmrunner |
start-result validation, start-response validation |
A returned error is a normal result only when the target's contract expects one;
a panic, hang, or violated contract fails. The committed seeds run in the normal
go test tier. CI runs a 20-second campaign for nine high-value targets.
11.9 Mutation audit
python3 test/mutation_audit.py
The audit copies the worktree, verifies the unmodified focused tests pass, then
disables one durable guard at a time. Each mutant must fail with a focused test
assertion; a surviving mutant, missing anchor, build/setup failure, or timeout
fails the audit. It covers cleanup fence deletion, deleting-state commit, request
rebinding, begin-phase gating, reserve collision, finalize receipt publication,
the migration import-fence policy guard, and the dispatcher rule that only
srv's explicit create refusal (exit status 3) releases a creating fence. The original worktree is not
modified.
11.10 Benchmarks
make bench
Benchmarks cover store reads/list/admission and service parsing. They are not a CI gate; run them when changing those paths.
11.11 Known limits
- QEMU durability covers a flush-prefix loss model on ext4. It does not cover torn writes, other filesystems, or storage that violates flush guarantees.
- QEMU networking uses iptables-nft and a disposable guest topology, not every firewall backend or production network topology.
- The service concurrency model covers contention around a bound cache stop, not arbitrary goroutine schedules or every lifecycle command.
TestDeleteProofQuiescesGatewaysBeforeReceipt requires both established tunnels
and CONNECT requests still dialing at deletion to close without bytes. An
ordinary dial failure without cancellation still returns HTTP 502.
12. HTTP integrations
srv can expose selected upstream HTTP APIs to a VM through a host-side integration gateway without storing the real upstream credentials inside the guest.
This feature is intentionally narrow in v1:
- Admin or operator managed only
- HTTP integrations only
- No guest-side secret submission over SSH
- No discovery, tagging, or attachment system
- No transparent interception of arbitrary outbound HTTPS
12.1 How it works
┌──────────────────────────────────────────────────────┐│ Host ││ ││ srv control plane ││ │ ││ │ integration add/enable ││ ▼ ││ SQLite metadata + /etc/srv/srv.env ││ │ ││ ▼ ││ Integration gateway :11435 on VM gateway IP ││ │ ││ │ /integrations/openai/... ││ │ injects headers/auth from SRV_SECRET_* ││ ▼ ││ upstream HTTP API │└──────────────────────────────────────────────────────┘ │ │ /30 network │ ┌────────┴────────┐ │ Guest VM │ │ │ │ curl http:// │ │ :11435 │ │ /integrations/ │ │ openai/... │ └─────────────────┘
Each enabled VM gets access to a host-side HTTP listener on its gateway IP and SRV_INTEGRATION_GATEWAY_PORT (default 11435). Requests are routed by path prefix:
http://<gateway-ip>:11435/integrations/<name>/...
The host looks up the named integration, rewrites the request to the configured upstream target, injects the configured auth or headers, and forwards the request.
12.2 Supported auth and header modes
An integration can use any combination of:
- Static headers via
--header NAME:VALUE - Env-backed headers via
--header-env NAME:SRV_SECRET_FOO - Bearer auth via
--bearer-env SRV_SECRET_FOO - Basic auth via
--basic-user USER --basic-password-env SRV_SECRET_BAR
Secrets are referenced by env var name only. The raw values are expected to live on the host, typically in /etc/srv/srv.env.
For --header-env, the env var value becomes the exact header value sent upstream.
12.3 Security behavior
The gateway is designed so the guest gets access to the upstream capability, not the underlying secret material.
- The gateway only accepts requests from the owning guest IP
- Guest-supplied
AuthorizationandProxy-Authorizationheaders are stripped on the host - Env-backed secrets are read on the host at request time
- If a referenced
SRV_SECRET_*env var is missing, the gateway returns502 Bad Gateway - Request paths are normalized before routing so traversal attempts cannot escape the configured integration prefix
12.4 Example setup
Add host secrets to /etc/srv/srv.env:
SRV_INTEGRATION_GATEWAY_PORT=11435SRV_SECRET_OPENAI_PROD=sk-live-redactedSRV_SECRET_VENDOR_API_KEY=vendor-key-redacted
Create and enable integrations from the control plane:
ssh srv integration add http openai --target https://api.openai.com/v1 --bearer-env SRV_SECRET_OPENAI_PRODssh srv integration add http vendor --target https://vendor.example/api --header-env X-API-Key:SRV_SECRET_VENDOR_API_KEYssh srv integration enable demo openaissh srv integration enable demo vendorssh srv inspect demo
The VM's inspect output will include URLs such as:
integrations:- openai: http://172.28.0.1:11435/integrations/openai- vendor: http://172.28.0.1:11435/integrations/vendor
From inside the guest, requests go to the gateway IP:
curl http://$(ip route show default | awk '{print $3}'):11435/integrations/openai/modelscurl http://$(ip route show default | awk '{print $3}'):11435/integrations/vendor/ping
12.5 Related references
13. Running as a daemon
srv is designed to run as a set of systemd services on a prepared host. The installer sets up three units that must all be active for the control plane to function.
13.1 Systemd units
| Unit | Purpose |
|---|---|
srv.service |
The main control-plane process. Joins the tailnet via tsnet and exposes the SSH API on port 22. |
srv-net-helper.service |
Root-only helper that owns TAP device creation, iptables MASQUERADE, and FORWARD rules for guest NAT. |
srv-vm-runner.service |
Root-owned process that invokes Firecracker through the jailer, drops to srv-vm:srv, and manages per-VM cgroup v2 leaves. |
13.2 Common systemd commands
# Check statussudo systemctl status srv srv-net-helper srv-vm-runner# View logssudo journalctl -u srv -fsudo journalctl -u srv-vm-runner -f# Restart all servicessudo systemctl stop srv srv-net-helper srv-vm-runnersleep 5sudo systemctl start srv-vm-runner srv-net-helper srv
srv-vm-runner.service must keep User=root, Group=srv, Delegate=cpu memory pids, DelegateSubgroup=supervisor, and a group-accessible socket under /run/srv-vm-runner/. Do not add NoNewPrivileges=yes — the jailer must drop privileges and exec Firecracker on real hosts.
13.3 Host reboot recovery
When srv-vm-runner.service stops, its systemd ExecStop drain discovers running fixed and pooled Firecracker VMs, asks up to eight guests at a time to shut down cleanly, and falls back to terminating guests that do not exit. The drain is bounded by the unit's 120-second stop timeout. It cleans runtime cgroups and sockets without changing the control plane's desired instance state.
Same-host reboot recovery is built into the control plane. Because the drain preserves that desired state, previously active instances are restarted automatically when srv comes back under systemd.
You do not need to manually restart VMs after a host reboot.
Check journalctl -u srv-vm-runner if a service stop reports a drain failure. After the timeout, systemd still terminates processes left in the unit cgroup; the next control-plane startup reconciles persisted state.
13.4 Environment file
Configuration lives in /etc/srv/srv.env. See the configuration reference for every variable.
If /etc/srv/srv.env already exists before an upgrade, the installer keeps it by default. After upgrade, verify that SRV_FIRECRACKER_BIN and SRV_JAILER_BIN still point at the intended static binaries.
13.5 Upgrading
For an existing pre-subvolume installation or customized systemd stack, first read storage layout migration and jailer/custom-unit upgrade checks. In particular, an ordinary Btrfs directory is not converted by the installer, and a short jailer bind-mount alias cannot publish Orb socket hard links.
-
Take a quiesced backup or a host snapshot.
-
Build and install the new
srv,srv-net-helper, andsrv-vm-runnerbinaries. -
If you also refreshed Firecracker, verify
/etc/srv/srv.envstill points at the correct binaries. -
Restart:
sudo systemctl stop srv srv-net-helper srv-vm-runnersleep 5sudo systemctl start srv-vm-runner srv-net-helper srv -
Run the smoke test:
sudo ./contrib/smoke/host-smoke.sh
See the operations reference for full upgrade and rollback procedures.
13.6 Smoke test as a validation gate
The smoke test is part of the supported workflow after install, restore, and upgrade — not an optional extra:
sudo ./contrib/smoke/host-smoke.sh
Overrides:
ENV_PATH=/etc/srv/srv.env.alt— alternate environment fileSMOKE_SSH_HOST=srv-test— alternate control-plane hostnameINSTANCE_NAME=smoke-manual— force a predictable instance nameKEEP_FAILED=1— leave a failed instance intact for debuggingREADY_TIMEOUT_SECONDS=300— override guest-ready timeout
15. Configuration reference
srv is configured through environment variables, read from /etc/srv/srv.env by the systemd units.
15.1 Provider service owners
Provider nodes can have a fixed, non-human owner identity, including tagged Tailscale nodes. This is opt-in and uses stable Tailscale node IDs, never hostnames, tags, SSH usernames, Dispatch parameters or Amp member IDs.
SRV_PROVIDER_NODES='{"nPROVIDER1":"amp-dispatch","nPROVIDER2":"amp-dispatch"}'SRV_ALLOWED_USERS='alice@example.com,service:amp-dispatch'
srv --provider-nodes '{"nPROVIDER1":"amp-dispatch"}' overrides the environment
value. The JSON object maps each node ID to a service name matching
[a-z0-9][a-z0-9_-]{0,63}. The resulting owner is service:amp-dispatch;
values cannot be human logins. Configured nodes use this owner even if their
WhoIs profile belongs to a human/admin. Unconfigured tagged nodes remain denied;
unconfigured ordinary user nodes keep normal user authentication.
For srv-front, add the same mapping to its static --config JSON:
{ "provider_nodes": {"nPROVIDER1": "amp-dispatch", "nPROVIDER2": "amp-dispatch"}, "allowed_users": ["alice@example.com", "service:amp-dispatch"]}
These are additional fields, not a complete frontend config. Configure the
mapping on each backend too: forwarded service owners must be explicitly known
there. Existing frontend trust (SRV_TRUSTED_FRONTENDS) still applies, and
frontend and backend allowlists still apply. Provider nodes must not be
trusted frontends; backend configuration rejects overlap. Trust only the actual
srv-front node, which authenticates the original peer and forwards its owner.
As before, a trusted frontend is a security boundary that can assert identities.
The service: namespace is reserved: direct human profiles cannot claim it and
SRV_ADMIN_USERS cannot contain it (startup fails). Service owners receive normal
owner-scoped operations, never admin privileges or another user's instances.
Multiple nodes mapped to the same name intentionally share ownership; use separate
names for isolation. Dispatch supplies no Amp member ID, so this provides no
per-human Amp ownership. Removing a mapping revokes that node's service identity
after restart, but does not delete or reassign existing instances. Rotate node IDs
explicitly; do not grant a tag-wide wildcard. Protect configuration as admin-owned.
Host-local project-template create NAME ID, project-template delete ID, and
new NAME --template ID require explicit --host HOST through srv-front. Template
creation and use must target the same backend; automatic template placement is
rejected.
15.2 Tailscale credentials
| Variable | Required | Description |
|---|---|---|
TS_AUTHKEY |
Yes* | Tailscale auth key for the control-plane node. After first start, tsnet state usually persists, but keeping this configured is the simplest setup. |
TS_CLIENT_ID |
Yes | Tailscale OAuth client ID for minting guest auth keys |
TS_CLIENT_SECRET |
Yes | Tailscale OAuth client secret for minting guest auth keys |
TS_TAILNET |
Yes | Tailnet name used for API operations |
Use either TS_AUTHKEY or TS_CLIENT_ID/TS_CLIENT_SECRET for the control-plane node. The OAuth flow is preferred for guest auth key minting.
15.3 Core settings
| Variable | Default | Description |
|---|---|---|
SRV_HOSTNAME |
srv |
Tailscale hostname for the control plane |
SRV_LISTEN_ADDR |
:22 |
Tailnet TCP listen address for the SSH API |
SRV_TAILSCALE_PORT |
0 |
Embedded Tailscale UDP transport port (0 selects automatically). Use a distinct fixed port from host tailscaled when applying an inbound firewall. |
SRV_DATA_DIR |
/var/lib/srv |
State directory; must be a btrfs subvolume root on the same filesystem as every base rootfs image. |
SRV_NET_HELPER_SOCKET |
/run/srv/net-helper.sock |
Unix socket for the privileged network helper |
SRV_VM_RUNNER_SOCKET |
/run/srv-vm-runner/vm-runner.sock |
Unix socket for the Firecracker VM runner |
SRV_FIRECRACKER_BIN |
/usr/bin/firecracker |
Path to the Firecracker binary |
SRV_JAILER_BIN |
/usr/bin/jailer |
Path to the jailer binary |
SRV_RAM_CACHE_SIZE |
0 (disabled) |
Runner setting. Host limit for RAM kept by stop --cache-state, for example 64G. The runner evicts the least recently saved images to stay within it. See the RAM cache for pauses |
15.4 Optional cold storage
See cold-disk setup and recovery. Keep these settings consistent between srv and the runner; only the runner reads the SSH credentials. Neither daemon formats storage or configures the remote host.
| Variable | Default | Description |
|---|---|---|
SRV_COLD_STORAGE_HOST |
empty (disabled) | Trusted SSH hostname/IP, optionally prefixed root@; dedicated forced-command namespace per backend |
SRV_COLD_STORAGE_KEY |
empty | Root-owned SSH identity file with no group/other permissions, with protected root-owned ancestors |
SRV_COLD_STORAGE_KNOWN_HOSTS |
empty | Root-owned pinned host-key file, with protected root-owned ancestors |
SRV_COLD_STORAGE_AFTER_STOP |
false |
Set to true to attempt eviction after a successful explicit stop; errors retain local data and do not fail shutdown |
SRV_COLD_STORAGE_RETENTION |
0 (disabled) |
Offload disks after this duration continuously stopped, e.g. 48h for two days; requires a cold-storage host |
The runner's --cold-storage-timeout defaults to 6h, including checksum verification;
the remote helper's --timeout must also cover the operation. Leaving after-stop off
permits manual disk offload when the host is configured. Before changing or
removing the host, hydrate and purge its cold generations.
15.5 Guest artifacts
| Variable | Default | Description |
|---|---|---|
SRV_BASE_KERNEL |
(required) | Path to the Firecracker guest kernel image |
SRV_BASE_ROOTFS |
(required) | Path to the base rootfs image. Must be on the same btrfs filesystem as SRV_DATA_DIR. |
SRV_BASE_INITRD |
(empty) | Optional initrd image path |
SRV_IMAGES_FILE |
(empty) | JSON image catalog; also available as --images-file. Read at service startup. |
SRV_IMAGES_DIR |
SRV_DATA_DIR/images |
Runner's trusted boot-artifact directory; also available as runner --images-dir. |
For example, /etc/srv/images.json can register Debian alongside the existing
Arch defaults:
{ "debian-13": { "kernel": "/var/lib/srv/images/debian-base/vmlinux", "rootfs": "/var/lib/srv/images/debian-base/rootfs-base.img" }}
Set SRV_IMAGES_FILE=/etc/srv/images.json in the service environment. Upgrade
both srv and srv-vm-runner, then restart both services; an old runner rejects
image-aware starts rather than silently using its global kernel. Paths must be
absolute; initrd is optional. Selected kernels/initrds must resolve within
SRV_IMAGES_DIR, except the exact legacy configured kernel/initrd pair and
private boot artifacts created by upgrade under that instance's directory.
Keep this tree and its ancestors root-owned and not writable by the srv service
or guests; do not store secrets in it. Symlinks escaping the tree are rejected.
Every base rootfs must be reflink-cloneable into SRV_DATA_DIR. Names use lowercase letters,
digits, dots, underscores and hyphens, starting with a letter or digit. Unknown
names are rejected before creating a VM.
ssh srv new demo --image debian-13 selects Debian; omitting --image selects
arch. The arch entry falls back to SRV_BASE_KERNEL, SRV_BASE_INITRD and
SRV_BASE_ROOTFS unless explicitly defined in the catalog. These legacy variables
are not needed when all required paths are supplied by catalog entries.
The selected image and boot paths are stored with the VM. All guests keep
their saved kernel/initrd paths across starts, even if the catalog changes or
the entry is removed. Keep those artifacts available and use versioned paths
when replacing kernels. Use upgrade NAME on a stopped VM to install the
configured image's kernel and modules together; upgrade NAME --rollback
restores the pre-upgrade kernel and entire disk, including guest data. See the
upgrade procedure for build
manifest and recovery requirements. Changing the catalog alone does not change
an existing writable rootfs. inspect and JSON responses expose image; older
VM records are treated as arch.
Portable exports preserve the image name. To import a named image on another host, register that name with a compatible kernel/module build first; imports use the destination's boot paths. Older exports without an image name use Arch. Non-Arch exports use format version 2, so older servers reject them instead of importing them as Arch; Arch exports remain compatible with format version 1.
15.6 Guest defaults
| Variable | Default | Description |
|---|---|---|
SRV_VM_VCPUS |
1 |
Default vCPU count for new VMs |
SRV_VM_MEMORY_MIB |
1024 |
Default memory in MiB for new VMs |
SRV_VM_PIDS_MAX |
512 |
Maximum tasks in each VM cgroup |
SRV_GUEST_AUTH_TAGS |
(required) | Comma-separated tags applied to guest auth keys |
SRV_GUEST_USER_AUTH_TAGS |
— | Optional comma-separated tailscale-login=tag:name mappings; a matching creator's tag replaces SRV_GUEST_AUTH_TAGS |
SRV_GUEST_AUTH_EXPIRY |
15m |
TTL for one-off guest auth keys |
SRV_GUEST_READY_TIMEOUT |
2m |
Time to wait for a guest to join the tailnet |
User tag mappings are matched case-insensitively against the login returned by Tailscale WhoIs; callers cannot request arbitrary tags. For example:
SRV_GUEST_AUTH_TAGS=tag:microvmSRV_GUEST_USER_AUTH_TAGS=rene.michaelis@antares.net=tag:rene
VMs created by rene.michaelis@antares.net receive only tag:rene; unmapped creators continue to receive tag:microvm. Every configured tag must exist in the tailnet policy and be assignable by the OAuth client used by srv.
15.7 Networking
| Variable | Default | Description |
|---|---|---|
SRV_VM_NETWORK_CIDR |
172.28.0.0/16 |
IPv4 network reserved for VM /30 allocations |
SRV_VM_DNS |
1.1.1.1,1.0.0.1 |
Comma-separated guest nameservers |
SRV_OUTBOUND_IFACE |
auto-detected | Optional override for the host interface used for NAT |
SRV_EXTERNAL_UPLINKS |
empty | Comma-separated host interfaces through which external-only guests may forward; empty refuses external-only guests |
SRV_EXTERNAL_DENY_CIDRS |
empty | Additional IPv4 CIDRs external-only guests must not reach, in addition to private and special-purpose ranges |
15.8 Authorization
| Variable | Default | Description |
|---|---|---|
SRV_ALLOWED_USERS |
(empty) | Comma-separated Tailscale login allowlist. Empty means allow all tailnet users. |
SRV_ADMIN_USERS |
(empty) | Comma-separated Tailscale logins with cross-instance visibility and management rights |
15.9 Provider gateways
| Variable | Default | Description |
|---|---|---|
SRV_ZEN_API_KEY |
(empty) | OpenCode Zen API key. When set, enables per-VM Zen gateways. |
SRV_ZEN_BASE_URL |
https://opencode.ai/zen |
Upstream Zen API base URL |
SRV_ZEN_GATEWAY_PORT |
11434 |
TCP port for each VM's Zen gateway proxy |
SRV_DEEPSEEK_API_KEY |
(empty) | DeepSeek API key. When set, enables per-VM DeepSeek gateways. |
SRV_DEEPSEEK_BASE_URL |
https://api.deepseek.com |
Upstream DeepSeek API base URL |
SRV_DEEPSEEK_GATEWAY_PORT |
11436 |
TCP port for each VM's DeepSeek gateway proxy |
15.10 HTTP integrations
| Variable | Default | Description |
|---|---|---|
SRV_INTEGRATION_GATEWAY_PORT |
11435 |
TCP port for each VM's host-side integration gateway |
SRV_AMP_CONNECT_GATEWAY_PORT |
3128 |
Per-VM HTTP CONNECT gateway for public HTTPS destinations on port 443; private, local, and special-use networks are blocked |
SRV_SECRET_* |
(empty) | Host-managed secret env vars referenced by integration definitions for bearer auth, basic auth passwords, or env-backed headers |
The SRV_SECRET_* entries are a naming convention rather than a fixed list. They are meant to live in /etc/srv/srv.env so the SSH control surface only ever receives secret names such as SRV_SECRET_OPENAI_PROD, not the raw credential values.
15.11 Alternate Tailscale endpoints
| Variable | Default | Description |
|---|---|---|
TS_CONTROL_URL |
(Tailscale default) | Alternate Tailscale coordination server (e.g. Headscale) |
TS_API_BASE_URL |
https://api.tailscale.com |
Alternate Tailscale API base URL |
SRV_GUEST_TAILSCALE_CONTROL_URL |
(same as TS_CONTROL_URL) |
Alternate control URL injected into guest bootstrap |
15.12 Misc
| Variable | Default | Description |
|---|---|---|
SRV_LOG_LEVEL |
info |
Log level |
SRV_EXTRA_KERNEL_ARGS |
(empty) | Additional kernel arguments appended to the guest boot line |
SRV_JAILER_BASE_DIR |
SRV_DATA_DIR/jailer |
Base directory for jailer workspaces. Must be in the same subvolume as Orb runtime directories. |
15.13 Path constraints
All VMs and Orbs require btrfs storage:
SRV_DATA_DIR— a btrfs subvolume root, not an ordinary directory on btrfsSRV_BASE_ROOTFSand catalog base rootfs images — on that same btrfs filesysteminstances/<name>/disk— a dedicated subvolume containingrootfs.imgSRV_JAILER_BASE_DIR— jailer workspaces in the same subvolume as the instance runtime directories (outsidedisk)
Install btrfs-progs and enable user_subvol_rm_allowed on the mount. This
btrfs mount option
allows owners to delete their subvolumes; appropriate ownership and directory
permissions are still required. Do not grant new capabilities to the main srv
process. The privileged runner bind-mounts disk, kernel, initrd, and log files
into the jail. Only the Orb socket is still hard-linked between runtime and jail;
hard links cannot cross subvolume boundaries even on the same filesystem. They
also cannot cross mount boundaries: shortening only the jailer path through a
bind-mount alias fails with EXDEV, even when both paths report the same Btrfs
subvolume ID. Keep the effective jailer path inside the data root through the
same mount view as instances, outside the per-instance disk subvolumes.
Host-side clients dial SRV_JAILER_BASE_DIR/<firecracker binary name>/<vm name>/root/firecracker.sock
and SRV_DATA_DIR/instances/<vm name>/firecracker.sock (plus orb.vsock for Orbs) by
absolute path, and Unix socket paths are limited to 107 bytes. With the binary named
firecracker, the default SRV_DATA_DIR/jailer is too long for 60-character Orb names;
SRV_JAILER_BASE_DIR must then be at most 12 bytes (9 bytes for 63-character names).
The Orb dispatcher generates 60-character names; srv accepts names up to 63
characters. Check the complete paths, not only the data directory or VM name.
The VM runner rejects overlong socket paths before launching anything.
One verified layout for a data root at /var/lib/srvorb is:
SRV_DATA_DIR=/var/lib/srvorbSRV_JAILER_BASE_DIR=/var/lib/srvorb/jSRV_FIRECRACKER_BIN=/opt/srvorb/bin/fc
Here j is an ordinary directory in the data-root subvolume, not a separate
subvolume or bind mount. fc must be a regular, root-owned executable copy of the
matching official static Firecracker binary (root:root, mode 0755), with identical
bytes. Do not use a symlink: the jailer canonicalizes its executable path, while
srv derives the workspace from the configured executable basename. The jailed
API socket path is 103 bytes for a 60-character name and 106 for a 63-character
name. This is an optional layout, not a requirement to rename every installation's
Firecracker. Refresh and verify the copy whenever upgrading Firecracker, keeping
the matching jailer version.
Choose the base and executable name before the first start. Start receipts and lifecycle locks live under the base, and workspace lookup depends on the executable basename. Changing either on a populated host requires the stopped-boundary upgrade procedure; a new, empty namespace is not proof that the old runtime has been cleaned up.
16. Guest image reference
The default guest image is an Arch Linux rootfs designed for srv. It is built by images/arch-base/build.sh and contains a full Linux userspace with developer tooling, Chromium, and the agent-browser automation CLI preinstalled.
16.1 Artifacts
The builder produces:
| File | Description |
|---|---|
vmlinux |
x86_64 Firecracker-compatible kernel, built from 6.12 LTS with Firecracker's microvm config as baseline |
rootfs-base.img |
Sparse ext4 image populated via pacstrap |
manifest.txt |
Build manifest with version info |
16.2 Included packages
The image is intentionally not minimal — it includes tooling for development and AI agent workflows:
- Docker, docker-compose with
docker.socketactivation instead of an idledockerd - Chromium and the pinned native
agent-browserCLI with matching runtime skill data;/root/.agent-browser/config.jsonselects/usr/bin/chromium - Go, gopls
- Odin, odinfmt, OLS
- Neovim with prewarmed LazyVim (BMW heritage amber theme)
- OpenCode and Pi CLIs with per-VM provider gateway bootstrap
- Git, fd, ripgrep, tree-sitter-cli, gcc, perf, valgrind
- iptables-nft with IPv4/IPv6 nftables support
- Kernel module tree matching the custom kernel (overlay, br_netfilter, Docker-related modules)
16.3 Bootstrap service
The guest includes srv-bootstrap.service, which runs on every boot:
- Discovers the primary virtio interface from the kernel-provided default route
- Adds a route to Firecracker MMDS at
169.254.169.254/32 - Reads the MMDS payload from
http://169.254.169.254/withAccept: application/json - Sets the hostname from
srv.hostname - Starts
tailscaled - Runs
tailscale up --auth-key=... --hostname=... --sshon the first authenticated boot (relies on persisted state on later boots) - Writes
/root/.config/opencode/opencode.jsonplus Pi config under/root/.pi/agent/to the per-VM host provider gateways when provider API keys are configured, or removes those managed defaults when all provider gateways are disabled - Writes
/var/lib/srv/bootstrap.donewith the latest successful bootstrap timestamp
When MMDS sets srv.guest_network (a guest without Tailscale), steps 5 and 6 are replaced. Bootstrap masks tailscaled for this boot. It generates any missing SSH host keys and restarts the image's OpenSSH server; if the image has no OpenSSH server or ssh-keygen, it reports srv-boot: {"nonce":...,"error":...} and fails, and srv fails the start at once instead of waiting for the readiness timeout and records the error on the instance. The guest keeps running until you stop or delete it. Finally, it writes srv-boot: {"nonce":"<srv.boot_nonce>","ssh_host_key":"SHA256:..."} to the serial console. Images without this support never report readiness, and such starts fail closed. Templates made from a guest without Tailscale have their SSH host keys removed; this bootstrap regenerates them on each clone. Templates of tailnet guests keep their host keys.
The --ssh flag on tailscale up is intentional — it enables Tailscale SSH so the control plane's connect: ssh root@<name> output works through the tailnet without per-user OpenSSH keys.
Docker is installed but not started during boot. The image enables docker.socket, so the first Docker CLI/API use starts dockerd and containerd on demand. Getty/serial-getty and udev units are masked to avoid idle daemons that are not needed for the Firecracker bootstrap path.
16.4 Kernel details
- Starts from Firecracker's
microvm-kernel-ci-x86_64-6.1.configand runsolddefconfigagainst the selected source tree - Enables
CONFIG_PCI=yfor ACPI initialization (required by current Firecracker x86 builds) - Disables
CONFIG_VIRTIO_MMIO_CMDLINE_DEVICESso the kernel prefers ACPI discovery - Enables Landlock and adds it to
CONFIG_LSM(keeps pacman's download sandbox working) - Enables virtio ballooning and page reporting so fixed and pooled VMs can return idle guest pages to the host
- Builds real
.komodule files for Docker, overlay, br_netfilter, and nftables - Builds KVM and its Intel and AMD drivers as modules for Arch and Debian images built with this kernel and its matching module tree. For nested KVM, the host and VMM must expose virtualization extensions to the guest. In the guest, load
kvm_intelorkvm_amdwithmodprobebefore starting a nested VM.
To add KVM modules to an existing guest, upgrade its kernel and module tree together.
16.5 DNS
Guest bootstrap configures systemd-resolved with the nameservers supplied through the kernel ip= boot parameter in /proc/net/pnp. /etc/resolv.conf points at the systemd-resolved stub, allowing Tailscale to install MagicDNS and split-DNS routes after joining the tailnet.
16.6 Logging
journald is configured to forward logs to ttyS0, making the guest bootstrap flow visible in each instance's serial log (ssh srv logs <name> serial).
17. Operations runbook
This runbook is for the supported prepared-host path: systemd-managed srv, srv-net-helper, and srv-vm-runner on a Linux host with cgroup v2, /dev/kvm, SRV_DATA_DIR as a btrfs subvolume root, all base rootfs images on the same btrfs filesystem, btrfs-progs, the user_subvol_rm_allowed mount option, and the official static Firecracker/jailer release pair.
Same-host reboot recovery is already built into the control plane: when srv comes back under systemd, previously active instances are restarted automatically. The steps below cover the larger operator workflows that were previously only implied.
Hybrid memory pools are now part of the supported runtime model:
- Fixed memory remains the default and preserves the original dedicated-reservation behavior.
- Pools reserve host memory immediately at
pool createtime. - Pooled member VMs consume guest-visible RAM from that shared reservation and are not charged against host memory a second time.
- Pooled guest RAM changes are stopped-only and must stay within the current pool's reserved size.
17.1 Supported Upgrade Lanes
- Guest-local maintenance is still guest-local. Running
pacman -Syuinside a guest is supported when you want that guest to drift independently, but it is not the control plane's golden-image rollout path. - Kernel and module upgrades for existing guests use
srv upgrade. Starting or restarting a guest keeps its stored boot paths. - Rootfs golden-image rollout is a new-guest lane. Updating
SRV_BASE_ROOTFSchanges what futurenewclones from, but it does not rewrite existing guests' writable disks. - Schema rollout is tied to the control-plane binary. SQLite migrations run during
srvstartup and are currently additive; rollback means restoring the pre-upgrade backup together with the previous binary set.
17.2 Backup
Take backups from a quiesced host so SRV_DATA_DIR and the SQLite WAL state are self-consistent.
Include SRV_JAILER_BASE_DIR/.start-receipts in the same backup and restore it
with the database. These runner-owned launch records and tombstones fence delayed
requests. They can live outside SRV_DATA_DIR; a data-directory snapshot alone
does not capture them. Do not delete receipts to unblock a quarantined launch.
For the archive command below, add the configured receipt directory as a path
relative to / if it is not already covered by var/lib/srv.
If you need a fast host-local point-in-time copy without shutting the control plane down first, use the built-in snapshot barrier instead:
ssh srv snapshot create
That command is admin-only. It briefly rejects every other SSH command, waits for already admitted commands to finish, checkpoints SQLite, flushes the filesystem, and then creates a bundle of readonly root and disk subvolume snapshots with a manifest under SRV_DATA_DIR/.snapshots/<timestamp>. Follow the host snapshot bundle runbook for component layout, replication, restore, and archive migration.
Snapshot semantics are intentionally limited and explicit:
- control-plane consistent
- stopped guests fully safe
- running guests crash-consistent
- no global atomic point across guest disks; the barrier does not pause guest writes
Important caveats for this path:
SRV_DATA_DIRitself must be a btrfs subvolume root. A plain directory on btrfs is not enough.- Root snapshots are not recursive: retain every disk component and the manifest, not just the root.
/etc/srv, environment files, unit overrides, and external runner receipts still need operator-managed backup. - Remote
btrfs send/receivereplication is intentionally out of the barrier path. If you use it for DR or warm standby, run it after the local snapshot already exists.
- Stop every VM and Orb and verify no guest remains running, then stop the services.
sudo systemctl stop srv srv-net-helper srv-vm-runner
- Capture the state directory, environment file, and any unit overrides.
sudo tar --xattrs --acls --numeric-owner \ --ignore-failed-read \ -C / \ -czf /var/tmp/srv-backup-$(date -u +%Y%m%dT%H%M%SZ).tar.gz \ etc/srv \ var/lib/srv \ etc/systemd/system/srv.service.d \ etc/systemd/system/srv-net-helper.service.d \ etc/systemd/system/srv-vm-runner.service.d \ etc/systemd/system.control
- Start the services again if this was only a backup window.
sudo systemctl start srv-vm-runner srv-net-helper srv
Notes:
- Preserve the configured paths in
/etc/srv/srv.env. Instance rows store absolute runtime paths such asSRV_DATA_DIR/instances/<name>/disk/rootfs.img(or the legacyinstances/<name>/rootfs.imgbefore migration), so changingSRV_DATA_DIR,SRV_JAILER_BASE_DIR, or the base artifact paths during restore is not a supported relocation workflow. - Keep Orb runtime and jail directories in the same subvolume, not merely the same filesystem: only the Orb socket is hard-linked. The runner bind-mounts the disk, kernel, initrd, and logs.
- A tar archive preserves files, not btrfs subvolume boundaries or readonly properties. Record and recreate those boundaries and properties before starting services; prefer the bundle restore procedure for btrfs backups.
17.3 Storage Layout Migration
The btrfs-only layout applies to all VMs and Orbs. Writable disks live at
SRV_DATA_DIR/instances/<name>/disk/rootfs.img, with disk a dedicated subvolume.
Legacy instances with instances/<name>/rootfs.img migrate automatically on their
next start while stopped, using a durable migration journal for interrupted
attempts. Do not manually move the image, edit database paths, or remove a journal
to bypass an incomplete migration. Retain the pre-upgrade backup for rollback.
This is a storage-layout migration, not a guest filesystem or OS conversion.
Before upgrading:
- Schedule an outage, stop every VM and Orb, verify all guests are stopped, and stop all three services. Take and verify an offline backup of the complete data tree, database/WAL, configuration, boot artifacts, and matching runner receipts as described above. Keep the original storage untouched until validation.
- For an existing btrfs host, verify the data directory is a subvolume root and
every base rootfs is on the same filesystem. Install
btrfs-progs, configureuser_subvol_rm_allowed, and verify service ownership and directory permissions. The option permits owners to delete their subvolumes; it does not grant access to arbitrary subvolumes. Add no capabilities to the mainsrvservice. An existing ordinary directory on btrfs is not sufficient: neither startup nor the installer converts it. With all writers stopped and the backup verified, prepare a dedicated subvolume at the same configured path, preserve contents, numeric ownership, permissions, ACLs, xattrs, hard links and sparse files, and retain the original tree until validation. Do not change stored absolute paths merely to point at another directory. - For XFS or any other non-btrfs host, prepare separate btrfs storage and a data-root subvolume offline. Copy or restore the stopped data and base images while preserving numeric owners, permissions, timestamps, ACLs, xattrs, hard links, and sparse disk contents. Verify the copy against the backup. Mount the prepared storage at the original configured paths before starting anything: stored absolute paths and runner receipts must remain valid. Do not reformat the source or assume merely starting srv on XFS will migrate it. There is no in-place XFS conversion, automatic formatting, or automatic destructive host-storage command.
- Ensure Orb runtime and jail directories are in the same subvolume and mount
view. A bind-mount alias of only the jailer directory does not work: socket
hard-link publication fails with
EXDEVeven with equal subvolume IDs. Check complete socket path lengths and custom unit overrides using the jailer upgrade checks below. Follow the snapshot archive migration guidance for an existing.snapshotsarchive; do not treat a legacy single-root snapshot as a full bundle. - Install matching binaries, start services, and start a stopped canary instance to exercise automatic journaled disk migration. Verify its new disk path, subvolume, guest data, and stop/start behavior before starting the remaining guests. Run the host smoke test and verify a complete host snapshot bundle. If validation fails, keep services and guests stopped while restoring the matching pre-upgrade data, receipts, configuration, and binaries.
Migration on btrfs can be cheap through reflinks, but shared extents do not guarantee incremental send lineage. Budget for a first full remote send of the new disk subvolumes; later delta sends require suitable retained parent snapshots. Remote replication remains outside the snapshot barrier. Cold offload is a separate, optional disk lifecycle described below.
17.3.1 Jailer Path And Custom Unit Upgrades
Before stopping guests, inspect the effective unit files and drop-ins, not just
the repository defaults. Build matching srv, srv-vm-runner and srv-net-helper
binaries and check custom flags against their -help output. Back up the current
binaries, configuration and units with the data and receipt namespace. Stop any
Orb provider that could create or wake guests before stopping those guests.
Custom stacks must also apply the installer's storage prerequisites without
overwriting their environment or units with defaults: precreate
SRV_DATA_DIR/.host-locks/payload.lock as a root-owned regular file, mode 0660,
with the stack's service group. The data-root ancestor chain and .host-locks
must be root-owned and not group/world-writable. Runtime does not create this
lock. Prepare the .snapshots subvolume and service-owned storage directories
as well; replacing only the executables is not a complete upgrade.
For Orb hosts, test both hard-link publication and Unix socket path lengths in a
disposable fixture before the outage. Equal filesystem/subvolume IDs alone do
not establish that paths can be hard-linked across mounts. The
path constraints include a verified short
j/fc layout for 60-character dispatcher names and srv's maximum 63-character
names. A short symlink to Firecracker is not equivalent to a regular executable
copy. Do not solve socket length by putting the jailer in a different subvolume
or by shortening only its mount alias.
If changing an existing jailer base or Firecracker executable basename:
- At the quiesced backup boundary, use the old configuration to establish that its runtime workspaces, sockets, mounts and cgroups are no longer active. Resolve uncertain accepted starts using their original identities; never delete receipts or inspect an empty new workspace as a substitute for this proof.
- Preserve the complete authoritative
.start-receiptsnamespace, including locks and any cold/migration state, together with its database and disks when relocating it. Do not merge receipts from failed rollout trees or invent replacements. Retain original data/configuration for a coordinated rollback. - Keep control plane, runner, drain and cleanup-proof configuration consistent with the new base and executable. Update custom systemd access restrictions only as needed for the new trusted paths; preserve existing hardening.
- Start one stopped canary per stack before returning other guests. Verify data identity, actual Orb agent/socket communication, repeated stop/start and exact receipt handling. Start providers last. Roll back matching data, receipts, configuration and binaries together if validation fails.
Two custom-unit compatibility checks are especially important:
ExecStopmust usesrv-vm-runner -drain-only -socket <this runner's socket>. Drain now calls the running runner in its mount namespace; a custom stack must not accidentally drain the default stack. Keep the socket consistent withExecStartandSRV_VM_RUNNER_SOCKET. Clear the inheritedExecStopbefore defining its replacement in a drop-in.- Older private net-helper drop-ins may pass
--proof-instances-dir,--proof-jailer-base-dir,--proof-firecracker-binand--proof-cgroup-root. The current net-helper rejects those flags. Runtime absence proof now runs in the root VM runner at/vm/cleanup-proof-v1, using that runner's configured paths and delegated cgroup; network absence proof remains in the net-helper. Upgrade the binaries together and adjust only the obsolete arguments, keeping the intended socket, TAP user, client group and access restrictions. If replacing anExecStartin a drop-in, clear its old value before setting the replacement. Do not bypass proof failures. The current deletion-proof operation is for native Orbs; legacy tailnet-VM proof callers are rejected, not transparently migrated to this API.
After successful conversion, future backups must include the data-root subvolume
and every nested disk subvolume. A parent-only snapshot no longer captures the
disks. See host snapshot bundles; separately preserve
external configuration, binaries, receipts and /boot where applicable.
17.4 Optional cold disks over SSH
Cold storage is disabled by default and applies to both VMs and Orbs. It uses
btrfs send/receive through the root VM runner, without adding capabilities to
the srv service. Uploads and downloads compress the send stream with zstd
before SSH and decompress it before btrfs receive. This also applies to
incremental transfers; stored snapshots and their checksums are unchanged.
There is no demand paging: start restores the entire disk
before booting. A cold instance remains stopped in the instance lifecycle.
Use a dedicated, trusted btrfs storage server. Build ./cmd/srv-cold-store and
install the binary as /usr/local/sbin/srv-cold-store there, owned by root and
not writable by other users. Prepare a dedicated root-owned directory (mode
0700) on btrfs for each backend. Every ancestor must also be root-owned,
nonsymlink and not group/other writable; a private directory under /tmp is
not accepted. Restrict the backend's SSH key to this forced
command in the storage server's root authorized_keys, for example:
restrict,command="/usr/local/sbin/srv-cold-store --root /storage/backend-a" ssh-ed25519
Do not use this key for an unrestricted remote shell. Protect the server,
namespace and SSH configuration: btrfs receive is not a security boundary
against a malicious send stream. The backend and storage server are mutually
trusted administrators. Pin the server host key through a verified channel;
never disable host-key checks. Keep the backend's private key and known-hosts
file root-owned. The private key must grant no group/other permissions (use
0600); known-hosts may be 0644. Keep both under root-owned protected
directories such as /etc/srv/cold-storage/ (not /tmp or a user home).
Upgrade the storage helper and srv-vm-runner before enabling cold storage in
srv. The runner validates credentials and required executables at startup.
For the zstd transport, install zstd on both hosts and upgrade the storage
helper before the runner. The new helper still accepts older uncompressed
clients; the new runner requires zstd transfers and fails against an old helper
without falling back to uncompressed transfers. Existing stored disks need no
migration.
An old runner's missing API fails closed with upgrade advice; never bypass it
to delete an instance whose remote state is unknown. Configure the backend's
/etc/srv/srv.env and restart both matching binaries:
SRV_COLD_STORAGE_HOST=storage.example.netSRV_COLD_STORAGE_KEY=/etc/srv/cold-storage/id_ed25519SRV_COLD_STORAGE_KNOWN_HOSTS=/etc/srv/cold-storage/known_hosts# Optional: attempt offload after a successful explicit stop command.SRV_COLD_STORAGE_AFTER_STOP=true
The runner uses root SSH with batch mode, pinned host keys, no agent, and no SSH
config files. Transfers have a six-hour overall runner deadline (override with
runner --cold-storage-timeout), a 15-second SSH connect timeout and keepalives.
The storage helper's --timeout also defaults to six hours. Size both deadlines
and the caller's timeout for transfer plus verification; a shorter deadline wins.
Backend cold lifecycle commands send SSH keepalives every 30 seconds without
changing stdout/stderr; srv-front already keeps both SSH hops alive. Thus quiet
transfer work does not hit the five-minute idle timeout. disk status reads an
atomic journal snapshot without waiting for the transfer lock; it is advisory,
not permission to mutate a disk.
Each offload hashes its immutable local snapshot once and verifies the received
remote disk once before publication. An existing base is still hashed once
locally; metadata/UUID checks do not rehash it remotely. Hydration verifies the
received disk locally. Stat checks immutable publication and identity, not
media integrity; use filesystem scrubbing separately. These bounds are not a
throughput guarantee. The remote namespace lock serializes transfers, so a long
upload can delay another instance's hydration; deletion scans all manifests.
Both hosts need btrfs-progs and zstd; the backend also needs OpenSSH client and losetup.
The backend's btrfs receive needs btrfs-progs 6.10.1 or newer, or a
distribution backport of the reverse-receive fix.
Older versions can accept an incremental stream's snapshot parent but fail on
shared file extents with clone: cannot find source subvol: clone lookup only
checks received UUIDs, not the original local base UUID. Updating the receiver
preserves incremental hydration; a kernel upgrade or full-transfer workaround
is not required for this bug. Verify the two-filesystem integration test below
with the actual receiver binary before enabling offload.
The runner's private staging beneath SRV_JAILER_BASE_DIR must be on the same
btrfs filesystem as the instance disks; keep its receipt directories root-owned.
Allow transient space for receiving the full disk before publishing it. Disk
reservation accounting remains conservative: eviction does not remove the
instance's capacity reservation.
ssh srv disk offload demossh srv disk status demossh srv start demo # restores first if coldssh srv disk hydrate demo # restores without booting; must be stoppedssh srv disk purge demo # removes retained remote generation; local disk required
Names may be backend-qualified through srv-front, e.g. disk status backend-a/demo.
Explicit mutations on native Orbs require an admin; visible owners can inspect
status. Automatic offload follows the existing authorized stop operation.
The stop response may wait for the optional transfer; transfer failure is logged
but does not turn a completed guest shutdown into failure. Restart, host drain,
and migration shutdown do not trigger this immediate after-stop offload.
For delayed automatic offload, set SRV_COLD_STORAGE_RETENTION=48h (or
--cold-storage-retention=48h) on srv. This applies to both VMs and Orbs after
two days continuously stopped, regardless of how they stopped. Leave
SRV_COLD_STORAGE_AFTER_STOP=false to keep disks local during that period;
enabling both options still permits immediate offload after an explicit stop.
The default retention is 0, which disables the scheduler. Durations use Go
syntax (48h, not 2d).
The scheduler checks after startup recovery and every five minutes, transferring one disk at a time. Busy instances and host snapshots defer work. Stop times survive srv restarts; metadata changes do not reset them, but starting and stopping again does. Already stopped instances without a recorded stop time get a full retention period from the first startup after upgrading. Migration fences still apply. Already cold disks and incomplete recovery states are skipped; recover interrupted transfers as described below. Other failures are logged and retried on a later scan. Long transfers can delay later candidates.
The runner keeps a durable incarnation-bound journal under its start receipts
and a cold-disk.json fence beside instance runtime metadata. Upload publication,
content SHA256, size and subvolume identity are verified before local eviction.
Lost upload replies retain the local disk and conservatively track a possible
remote copy. Retry disk hydrate to recover interrupted local work, then retry
offload. A hot disk remains usable during remote outages. If a genuinely cold
disk has no local copy, an unreachable remote makes start fail; srv never boots
the distribution base or an older remote generation as a substitute.
Hydration preserves the immutable remote generation until disk purge, ordinary
instance deletion, or the next offload removes it. Once local authority resumes,
that remote generation is not a fallback for subsequent local loss. Ordinary
deletion waits for acknowledged remote deletion and retains deleting intent on
failure. Cleanup proofs reject any retained cold-storage state rather than
claim remote erasure without evidence. Do not manually delete journals, markers,
remote objects, or bases. Keep the original SSH destination configured until all
its instances have been hydrated and purged; disabling automatic offload alone
does not prevent hydration.
New distribution clones can send incrementally against their matching immutable content-addressed base. The base is copied once to the remote and retained. Hydration uses that base when its exact identity still exists locally; otherwise it requests a full stream. Legacy migrations and template clones without a matching distribution base use full transfers. Remote snapshots share extents; remote base retention is separate from per-instance generation deletion. Physical space is reclaimed only when no local backup or host snapshot still references the same extents. Small permanent deletion records remain on both ends to reject delayed requests; do not garbage-collect them independently.
Payload checksum corruption does not prevent ordinary remote deletion. If a manifest is corrupt, restore its authoritative metadata from backup or explicitly abandon the affected objects using the storage server's local administrator CLI:
srv-cold-store --root /storage/backend-a --discard UUID1,UUID2
This is irreversible and unavailable through the SSH protocol. Include every corrupt-manifest object and every dependent that must be discarded; all retained manifests must be valid and must not reference the discard set. The command never guesses dependencies or repairs unsafe filesystem layouts. It validates the complete set, permanently fences all IDs, then removes them. After interruption, retry the same complete set; never remove tombstones. Afterwards retry the backend deletion/purge to settle its journal. Do not discard the sole copy of a disk you intend to retain.
An administrator may run this CLI from a normal SSH login using sudo; it is
rejected in a forced-command environment (SSH_ORIGINAL_COMMAND). If the
manifest file itself is missing, first restore that file from authoritative
backup metadata. If the disk's read-only flag was cleared, stop all writers,
verify that the path is the intended object subvolume, and restore its read-only
flag before retrying. Discard is not a general filesystem-repair tool.
For cold disk identity mismatch, do not purge a different incarnation's
journal or clear deletion records to make Start work. Stop srv and the runner,
prevent remote writes, and preserve the database, instance directory, runner
receipts and remote namespace for inspection. Compare the database instance ID
with the journal's instance_id, disk UUID and remote object ID. Restore the
matching control-plane/disk/runner backup set using the host restore procedure;
do not combine an older database with newer journals. Restore the original remote
destination configuration, then use disk status, disk hydrate and disk purge
for that matching incarnation before deleting/reusing its name. If no matching
backup exists, keep the name fenced and recover the data on an isolated host;
there is deliberately no automatic cross-incarnation erasure. Disabling cold
storage with a missing public marker does not make a surviving root journal safe
to ignore.
An unexpected .stage-* name also fails closed. With the backend and remote
writers stopped, inspect and preserve the foreign entry outside the managed
namespace before retrying. Never delete unknown contents automatically or rename
a valid interrupted .stage-put-UUID / .stage-delete-UUID; their recovery is
managed by the helper.
Migration preparation, export, backup creation/restore, template creation,
resize and fsck automatically hydrate a stopped cold disk before using it,
just as start does. The instance lock covers hydration and the operation;
migrations additionally retain their durable fence between transfer commands,
so retention cannot offload the disk during migration. Hydration does not boot
the guest or reset its stop time. After other operations finish, an overdue
stopped disk may be offloaded again by retention. Existing hot disks do not
require contacting remote storage. Missing or unavailable cold data fails the
operation rather than substituting a base image. A failed migration hydration
leaves the source in preparing; retry migration prepare with the same target,
token and memory-policy flags after resolving the storage problem.
Complete host snapshots reject cold/transitional disks and hot disks with retained cold-storage state: hydrate and purge them before taking a bundle. This preserves the self-contained snapshot contract rather than silently producing a backup that depends on the storage server. Cold storage is not an independent disaster-recovery backup: back up the control-plane metadata, runner journals, configuration and remote namespace as well.
Before enabling eviction on production data, run the opt-in kernel integration on two distinct disposable btrfs filesystems as root:
COLDSTORE_TEST_SOURCE=/mnt/test-source COLDSTORE_TEST_REMOTE=/mnt/test-remote \ go test ./internal/coldstore -run TestBtrfsTwoFilesystems -count=1 -v
It exercises full and incremental send/receive in both directions and parent retention. Also run a canary through the actual SSH forced command: offload, disconnect remote access, verify failed cold start preserves metadata, reconnect, hydrate, boot and compare guest data, then stop and purge/delete. Unit tests with substitute filesystem operations do not establish kernel or live-SSH correctness.
17.5 Move One Stopped VM Between Hosts
For single-VM cutover, use the portable stopped-VM stream instead of copying SQLite rows or the whole host state directory:
ssh srv-a export demo | ssh srv-b import
Operational notes:
- The source VM must be stopped before export.
- Import recreates the VM under the same name and leaves it stopped. Start it explicitly on the destination after the stream completes.
- The artifact preserves portable metadata such as name, creator, machine shape, rootfs size, and last-known Tailscale name or IP.
- Serial and Firecracker logs are included when present, but each is capped to the newest
256 MiBduring export. - Import regenerates destination-local runtime state such as absolute file paths, tap device wiring, guest MAC, and VM subnet allocation.
- The copied rootfs carries the guest's durable Tailscale identity, so do not boot the source and destination copies at the same time.
- The destination host uses its currently configured
SRV_BASE_KERNELand optionalSRV_BASE_INITRDon the first laterstart; only the writable guest disk and optional logs come from the streamed artifact.
If the exported VM was in pooled mode, import preserves that metadata. The destination host must already have the referenced memory pool state available through the restored control-plane database before the VM can be started successfully.
17.6 Restore Or Rebuild A Host
- Prepare a fresh host with the normal prerequisites: Tailscale, cgroup v2,
/dev/kvm, a btrfs data-root subvolume sharing its filesystem with every base rootfs image,btrfs-progs,user_subvol_rm_allowed, and the repo checkout. - Reinstall the managed assets.
sudo ./contrib/systemd/install.sh
- Re-enable IPv4 forwarding for guest NAT on the rebuilt host.
sudo tee /etc/sysctl.d/90-srv-ip-forward.conf >/dev/null <<'EOF'net.ipv4.ip_forward = 1EOFsudo sysctl --system
- Restore
/etc/srv/srv.envfrom backup and verify thatSRV_FIRECRACKER_BIN,SRV_JAILER_BIN,SRV_DATA_DIR,SRV_BASE_KERNEL,SRV_BASE_ROOTFS, and any optionalSRV_BASE_INITRDstill point at the intended paths. - Restore the saved
SRV_DATA_DIRtree to the same path, including its subvolume boundaries and readonly snapshot properties. For snapshot bundles use the bundle restore procedure; extracting a tar alone does not recreate subvolumes. - Reload systemd and start the services.
sudo systemctl daemon-reloadsudo systemctl enable --now srv-vm-runner srv-net-helper srv
- Run the prepared-host validation gate before handing the host back to users.
sudo ./contrib/smoke/host-smoke.sh
That smoke pass is part of the supported restore workflow now, not an optional extra.
17.7 Upgrade And Rollback
17.7.1 Control Plane And Schema
The launch-outcome protocol requires matching srv and srv-vm-runner binaries.
Do not run the new control plane with an old helper or mix lifecycle writers.
Stopping the runner can stop its guests: use an approved maintenance window.
Cold enrollment also requires a rebuilt golden rootfs containing the updated
srv-bootstrap script. It reports the guest's stable Tailscale node ID with a
per-launch nonce over the serial channel. An old base image will leave new guests
pending rather than accepting an unrelated same-name Tailscale record. Existing
enrolled guests do not need an in-place rootfs update for warm starts.
- Take the quiesced backup above before starting the upgraded
srvbinary for the first time. - Build and install the new
srv,srv-net-helper, andsrv-vm-runnerbinaries. - If you also refreshed Firecracker, use the matching official static
firecrackerandjailerpair and verify/etc/srv/srv.envstill points at those paths. - Restart the services.
sudo systemctl stop srv srv-net-helper srv-vm-runnersleep 5sudo systemctl start srv-vm-runner srv-net-helper srv
- Run the host smoke test.
sudo ./contrib/smoke/host-smoke.sh
Rollback for control-plane or schema regressions is restore-based:
If rolling back from a version that records stopping, first finish pending
stops with ssh srv stop <name> under that version. Older versions do not
recognize the state and may automatically start those guests. Never mix old and
new control-plane writers against the same database. Swapping only the binary
is not a substitute for the restore-based procedure below.
- Stop the services.
- Reinstall the previous binaries and previous static Firecracker/jailer pair if those changed.
- Restore the pre-upgrade backup of
/etc/srv,SRV_DATA_DIR, and the matching runner receipt directory. Confirm no post-backup guest remains running before replacing state; never combine old database rows with newer runtime state. - Restart the services.
- Run the same host smoke test again.
17.7.2 Kernel Rollout For Existing Guests
- Install the new
vmlinux,rootfs-base.img, andmanifest.txttogether in a new image directory. Point the guest's image configuration at that directory; do not overwrite artifacts that guests may still reference. - Run
sudo systemctl restart srv.serviceto load the updated image catalog. - Follow the kernel and module upgrade procedure: stop a canary guest, run
ssh srv upgrade <name>, then start it and verify its workload before upgrading more guests.
Changing SRV_BASE_KERNEL or SRV_BASE_INITRD does not update an existing guest's stored boot paths. Use upgrade to replace the kernel and module tree together, even if the kernel release string is unchanged. To roll back, stop the guest and run ssh srv upgrade <name> --rollback before starting it again. Rollback restores the entire pre-upgrade disk, so guest writes since the upgrade are lost.
17.7.3 Golden Rootfs Rollout
- Build the new image and install
vmlinux,rootfs-base.img, andmanifest.txttogether in a new image directory. Keep the previous artifacts available for existing guests and rollback. - Update the image catalog entry to point to the new kernel and rootfs together, including the matching initrd if used. Restart
srv.serviceto load the catalog. If using the legacy defaults instead, switchSRV_BASE_KERNEL,SRV_BASE_ROOTFS, and anySRV_BASE_INITRDtogether and make sure both services load their updated settings. If existing guests rely on the runner's exact legacy boot pair outsideSRV_IMAGES_DIR, use the catalog path and keep that legacy boot configuration unchanged. - Create a canary guest with
ssh srv new <name> --image <image>(omit--imagefor the defaultarchimage) and validate it. - After the canary passes, new guests will clone from the new base image.
Switch the paths as a pair even if the kernel release string did not change. To roll back for future guests, restore the previous pair and any matching initrd in the configuration, then reload it as in step 2. This does not revert any guests already created from the new image.
Important caveat: existing guests keep their own writable rootfs.img. There is no host-driven in-place existing-rootfs conversion workflow yet. For an existing guest that needs OS updates today, the supported choices are:
- manage that guest locally with
pacman -Syu, accepting guest-local drift - create a replacement guest from the refreshed golden image and migrate the workload or data to it
17.8 Host Hardening And Caveats
- cgroup v2 is required. The runner depends on a delegated cgroup v2 subtree for both fixed and pooled layouts:
- Fixed VMs use
firecracker-vms/<name>leaves with enforcedcpu.max,memory.max,memory.swap.max, andpids.max. The guest sees the configured RAM; the hostmemory.maxadds a small Firecracker overhead reserve (max(256 MiB, RAM/16)) so VMM/page-table overhead does not consume guest-visible memory headroom. - Pooled VMs use
firecracker-pools/<pool>/<name>leaves. The pool parent holds the hard memory reservation withmemory.max=<pool size>andmemory.swap.max=0, while child VM cgroups still carry CPU and PID limits. - IPv4 forwarding must stay enabled on the host. Guest egress depends on forwarding packets from each TAP device through the host's outbound interface after the helper installs MASQUERADE and
FORWARDrules. srv-vm-runner.servicemust keepUser=root,Group=srv,Delegate=cpu memory pids,DelegateSubgroup=supervisor, and a group-accessible socket under/run/srv-vm-runner/.- Do not add
NoNewPrivileges=yestosrv-vm-runner.service; the jailer must drop privileges andexecFirecracker on real hosts. - Keep using the official static Firecracker and jailer release pairing. Distro-provided dynamically linked binaries can fail after chroot before the API socket appears.
- Preserve
/etc/srv/srv.envacross reinstall or upgrade unless you are intentionally changing configuration and have accounted for the stored absolute paths. - Keep the
SRV_DATA_DIRsubvolume and every base rootfs image on the same btrfs filesystem. Fast per-instance provisioning still depends on reflink cloning the configured base rootfs. - Use pooled mode only for workloads that tolerate an elastic memory contract. Fixed mode remains the supported choice for databases, JVMs, and other memory-sensitive services.
statusis now the operator view for host memory accounting: it separates fixed reservations from pool reservations so pooled members do not look like additional dedicated host claims.inspectandtopare the operator views for VM memory behavior:inspectshowsmemory-modeand host reservation style, whiletopshows host-resident live memory against configured guest RAM. Fixed and pooled VMs both use a virtio balloon with free-page reporting so idle guest pages can be returned to the host; pooled rows also show the pool name.- On reboot recovery, pooled VMs recreate their pool-parent cgroups before restart; if a recovered VM references a missing pool record, treat that as a control-plane state restore problem rather than a guest runtime issue.
- Run
sudo ./contrib/smoke/host-smoke.shafter install, restore, control-plane upgrade, and base-image changes.
18. Troubleshooting
18.1 VM is stuck in provisioning or failed
Check the control-plane view first:
ssh srv inspect
Look for the last_error field and state. Then check the guest and VMM logs:
ssh srv logs serial ssh srv logs firecracker
Common causes:
- Missing or misconfigured base rootfs/kernel
- Tailscale OAuth credentials expired or invalid
- Network helper not running (
systemctl status srv-net-helper) - VM runner not running (
systemctl status srv-vm-runner) /dev/kvmnot accessible
18.2 Running VM remains awaiting-tailnet after a start timeout
A disconnected caller or readiness timeout can leave a running VM in
awaiting-tailnet. Once the VM has booted, srv preserves it rather than stopping
it because the caller disconnected. The background reconciler retries readiness
automatically. Check last_error and the serial log; for an immediate retry:
ssh srv start
For an awaiting-tailnet VM whose recorded process is still running, this checks
the existing runtime and tailnet peer without rebooting or re-enrolling it. srv
matches the API socket to the recorded process, checks the enrolled node against
the local tailnet peer map, and sends a bounded TSMP probe. An unchanged
Tailscale LastSeen, an idle peer with InEngine=false, or a zero reported RTT
does not prevent success. Missing or ambiguous identity and failed probes leave
the running VM pending. If the process has exited, start retains its normal
behavior of starting the VM.
Warm-start ready means the guest responded on the tailnet. It does not prove
SSH access or application health; test those separately. Allow the SSH caller
more time than SRV_GUEST_READY_TIMEOUT (default 2m), plus transport overhead.
list and inspect can wait behind an in-progress lifecycle operation because
their runtime cleanup uses the same instance lock.
After startup recovery, a background sweep runs every 30 seconds. Busy instances are skipped until a later sweep; snapshots exclude background mutations. Readiness and outcome lookup get a 10-second attempt budget per instance. Shutdown and network cleanup retain their own bounded completion deadlines. Slow sweeps can delay later checks; 30 seconds is not a recovery-time guarantee.
The sweep resumes stopping and deleting intent and checks pending readiness.
It does not start stopped guests, restart crashed guests, or monitor application
health. Startup recovery remains the separate path for reboot-time auto-start.
Do not repair this state with raw SQL or restart shared services just to refresh it. Deployments and rollback still require the maintenance and backup procedure in the operations reference.
18.3 Stop was interrupted
stopping records an unfinished stop. The PID and resource reservations remain
until the VM runner and network cleanup succeed. The background sweep retries
the stop; ssh srv stop <name> also retries immediately. Likewise, deleting
resumes an already requested deletion after failures. Backup/restore refuses
instances with unfinished shutdown cleanup;
neither start nor startup recovery may override this state, even if the process
has already exited.
Before downgrading to a version without stopping, finish all pending stops
under the new version. Older versions can treat this unknown state as eligible
for automatic startup. Do not run old and new control-plane writers together.
This is an additional rollback constraint, not a replacement for the documented
maintenance and backup procedure.
18.4 Launch outcome is unknown
Each new launch has a durable request ID in SQLite and a runner receipt under
SRV_JAILER_BASE_DIR/.start-receipts. After a lost HTTP response, srv asks the
runner about that same attempt. It adopts a verified running VM, or cleans up
only after the runner confirms absence. Unknown outcomes preserve disks,
networking, and reservations; another start cannot launch a duplicate.
If the helper dies between accepting a launch and recording its process identity, the attempt remains quarantined for that host boot. Restoring helper connectivity can recover committed launches, but does not make an unverified launch safe. Inspect the runner logs and runtime before planning recovery. Do not clear the receipt, edit the PID in SQLite, or restart the host without a maintenance plan. A host reboot makes old-boot attempts recoverable only after the runner verifies that no conflicting runtime occupies the name.
Cold guests need a serial srv-enrollment report from the updated base image.
Missing reports, wrong nonces, and mismatched node IDs leave them pending even if
a same-name device responds. Warm starts require a stored node ID or a unique
existing API device; a missing legacy device must be investigated before retrying.
Deleting a legacy VM without a stored node ID leaves its Tailscale device for
manual identification and cleanup rather than deleting a potentially unrelated
same-name device.
18.5 VM boots but Tailscale SSH doesn't work
If ssh srv inspect <name> shows state: ready and a Tailscale IP but you can't SSH in:
- Check the serial log for bootstrap errors:
ssh srv logs <name> serial - Look for
srv-bootstrap.servicefailures - Verify that
SRV_GUEST_AUTH_TAGSmatches a tag your OAuth client can mint keys for - Verify that the guest can reach the Tailscale coordination server (check DNS and outbound connectivity from inside the VM if possible)
18.6 Guest can't reach the internet
Guest egress depends on IPv4 forwarding and MASQUERADE rules:
# Check forwardingsysctl net.ipv4.ip_forward# Check iptables rulessudo iptables -t nat -L -nsudo iptables -L FORWARD -n# Check the network helpersudo systemctl status srv-net-helper
If net.ipv4.ip_forward is 0, re-enable it:
sudo sysctl -w net.ipv4.ip_forward=1
18.7 VM runs out of disk space
Check from inside the VM:
df -h
If the rootfs is full, you can resize the VM:
ssh srv stop ssh srv resize --rootfs-size 20G ssh srv start
On the host, check SRV_DATA_DIR usage:
df -h /var/lib/srv
18.8 Check cgroup limits
If a VM is being throttled or OOM-killed, check its cgroup v2 limits:
cat /sys/fs/cgroup/firecracker-vms//cpu.max cat /sys/fs/cgroup/firecracker-vms//memory.max cat /sys/fs/cgroup/firecracker-vms//memory.swap.max cat /sys/fs/cgroup/firecracker-vms//pids.max
18.9 Firecracker or jailer errors
The VM runner logs to journald:
sudo journalctl -u srv-vm-runner -f
Common issues:
- Jailer chroot setup failures — check that
SRV_JAILER_BASE_DIRis on the same filesystem asSRV_DATA_DIR - Permission errors — verify
srv-vm-runner.servicekeepsUser=root,Group=srv,Delegate=cpu memory pids,DelegateSubgroup=supervisor, and noNoNewPrivileges=yes /dev/kvmnot available — check permissions and that KVM is loaded
18.10 Smoke test
The end-to-end smoke test validates the full host setup:
sudo ./contrib/smoke/host-smoke.sh
Overrides:
| Variable | Default | Description |
|---|---|---|
ENV_PATH |
/etc/srv/srv.env |
Alternate environment file |
SMOKE_SSH_HOST |
srv |
Alternate control-plane hostname |
INSTANCE_NAME |
smoke-<random> |
Force a predictable instance name |
ARTIFACT_ROOT |
/var/tmp/srv-smoke |
Artifact storage root |
KEEP_FAILED |
(unset) | Leave a failed instance intact for debugging |
READY_TIMEOUT_SECONDS |
derived from config | Override guest-ready timeout |
GUEST_SSH_READY_TIMEOUT |
45 |
Seconds to wait for guest SSH after ready |
On failure, artifacts are written to /var/tmp/srv-smoke/<instance>/ including inspect, logs, systemctl status, and journalctl output.
19. Backup and restore
srv provides in-place backup and restore for VMs. This is useful for checkpointing VMs before risky changes and rolling them back when something goes wrong.
19.1 Create a backup
ssh srv backup create demo
This copies the current rootfs image into the backup store under SRV_DATA_DIR/backups/demo/<backup-id>/.
Stopping the VM first is strongly recommended. If you back up a running VM, the resulting rootfs is crash-consistent only — like pulling the power cord on a running machine — and the guest filesystem may need journal replay on restore. A crash-consistent backup is still better than no backup at all.
19.2 List backups
ssh srv backup list demo
Each backup has a unique ID and timestamp.
19.3 Delete a backup
ssh srv backup delete demo
This permanently removes the selected backup. The VM may be running or stopped.
19.4 Restore from a backup
ssh srv restore demo
This replaces the current rootfs with the backup's rootfs. The VM must be stopped.
19.5 Full workflow
# Create and configure a VMssh srv new demossh root@demo # install packages, configure services# Checkpoint before risky changesssh srv stop demossh srv backup create demossh srv start demo# ... make changes that break things ...# Reset to the checkpointssh srv stop demossh srv backup list demossh srv restore demo ssh srv start demo# Verify the restore worked — the VM should be back to the checkpoint state
19.6 Constraints
- Restore requires stopped: restoring onto a running VM is not supported
- Stopped recommended for backup: backing up a stopped VM produces a fully safe, clean-filesystem snapshot. Backups of running VMs are crash-consistent only
- In-place only: backups are tied to the original VM record. They cannot be restored onto a newly created VM that reuses the same name
- Single host: backups live on the same host. For cross-host migration, use export/import
- Rootfs only: backups capture the writable rootfs. The kernel and initrd come from the host's current configuration on the next
start
19.7 Backup storage
Backups are stored under:
SRV_DATA_DIR/backups///
Monitor disk usage if you create many backups — each one is a full copy of the rootfs at that point in time.
20. Build a custom guest image
The default guest image is an Arch Linux rootfs with Docker, Go, Neovim, OpenCode, Pi, and common development tools. You can customize it by modifying the overlay or building a completely different rootfs.
For a basic Debian 13 guest without the Arch developer/agent tools, use the
Debian builder. It reuses the custom
Firecracker kernel and matching modules, plus the existing srv bootstrap.
Register its artifacts in the image catalog
and select it with ssh srv new demo --image debian-13.
20.1 Default image builder
The images/arch-base/ directory contains the official builder. The fixed output path in the examples below is for an initial install only. On a host with existing guests, use a new image directory so you do not overwrite artifacts they may still use.
sudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh
This produces two artifacts:
vmlinux— an x86_64 Firecracker-compatible kernel built from the 6.12 LTS sourcerootfs-base.img— a sparse ext4 image populated viapacstrap
20.1.1 What the image includes
- Docker, docker-compose
- Go, gopls, Odin, odinfmt, OLS
- Neovim with a prewarmed LazyVim config (BMW heritage amber theme)
- OpenCode and Pi CLIs with per-VM provider gateway bootstrap
- Git, fd, ripgrep, tree-sitter-cli, gcc, perf, valgrind
- iptables-nft with IPv4/IPv6 nftables support
srv-bootstrap.servicefor Tailscale and MMDS setup
20.1.2 Build overrides
# Change kernel versionsudo KERNEL_VERSION=6.1.167 OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh# Change rootfs size (default 10G)ROOTFS_SIZE=20G sudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh# Reduce kernel build parallelismsudo KERNEL_JOBS=2 OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh
20.2 Podman build on non-Arch hosts
If your host is not Arch Linux and does not provide pacstrap:
sudo podman run --rm --privileged --network host \ -v "$PWD":/work \ -v /var/lib/srv/images/arch-base:/var/lib/srv/images/arch-base \ -w /work \ docker.io/library/archlinux:latest \ bash -lc ' set -euo pipefail pacman -Sy --noconfirm archlinux-keyring pacman -Syu --noconfirm arch-install-scripts base-devel bc e2fsprogs rsync curl systemd OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh '
--privilegedis required because the builder useslosetup,mkfs.ext4, andmount--network hostkeeps mirror and kernel downloads simple
20.3 Customizing the overlay
The images/arch-base/overlay/ directory contains files that are copied into the guest rootfs during the build. Changes here only affect new guests after you rebuild rootfs-base.img and refresh SRV_BASE_ROOTFS.
After modifying the overlay, build into a new image directory and point the image catalog entry at the new artifacts before creating guests. Restart srv.service to load the updated catalog.
20.4 Rolling out a new image
Rootfs changes only affect newly created guests. Existing guests keep their own writable rootfs.img. There is no host-driven in-place rootfs update.
To migrate an existing guest to a new base image:
- Follow the golden rootfs rollout to make the new kernel and rootfs available together
- Create a new guest with
ssh srv new <name> - Migrate workload data to the new guest
- Delete the old guest
Or manage the existing guest locally with pacman -Syu, accepting guest-local drift.
20.5 Kernel rollout
Existing guests keep their stored boot paths on restart. To update the kernel without replacing the guest's OS, build a complete image and follow the kernel and module rollout. Use stop, upgrade, then start so the guest gets both the new kernel and its matching modules. Do not replace the kernel file in place.
21. DRBD real-system pilot
Run test/drbd_pilot.py from a third Linux Tailnet client, not from A or B. It tests the manual runbook; it is not a failover controller or a CI job. Do not point it at an installed shared system. A successful storage-only QEMU run does not count as this pilot.
21.1 Prepare the disposable site
- Use two isolated systemd machines with KVM available to Firecracker, matching srv/runner/jailer/Firecracker binaries, guest kernel and image, numeric IDs and service configuration. Follow the runbook for single-primary DRBD 9 Protocol C, quorum off, auto-promote off, disconnect on conflict, a
noautoBtrfs subvolume at/var/lib/srv, and the mount-assert drop-ins on both hosts. Use one resource namedsrv, one volume and one peer. Keep all three units disabled everywhere. Confirm that nothing else can mount or promote. A starts mounted, B starts passive. Do not install or repair the stack during a test. - Give the test actor full inventory visibility. Create exactly two disposable VMs: one running app VM and one deliberately stopped VM. Confirm they are real Firecracker VMs on the expected machine, not test doubles. Record CLI inventory, guest identity, image versions and effective unit and DRBD configuration outside both hosts. The Firecracker recovery fixture exercises real guests, but its local transport stand-ins are not sufficient here.
- Put the test application inside the running guest, reached via its usual Tailnet name with verified HTTPS. Its
GET /healthreturnsok;PUT /receipts/<token>commits the supplied text token to that guest's replicated persistent disk and returns the token only after durable commit (e.g. SQLite withsynchronous=FULL).GET /receipts/<token>must read the stored value or return 404 for a missing key. No echo handlers, caches, client retries on writes, shared external databases, proxy fallback or alternate healthy replica. Verify the missing-key and durable-write behavior when commissioning the app. Limit the writer to this disposable pilot tailnet. - Use pinned keys from trusted provisioning for both unique management addresses and the stable logical srv name. No SSH aliases that change destination, prompts, key enrollment or trust-on-first-use. The pilot uses standard port 22, agent/default key, and its own known-hosts file. Check the machine IDs and map the immutable A asset ID to its management identity at the console. A and B must be different from each other and the client. Record the Tailnet node IDs/IPs for srv and the guest, and match them after handover; do not accept a newly enrolled node or replacement host key. Check the same guest is serving the receipt reads.
- Prepare independent BMC/hypervisor power control and a switch/hypervisor rule blocking every replication path without blocking management. Validate with the operator that power-off can be maintained despite restart policies/watchdogs. Run timestamped replication event capture with gap detection and disconnect alarms outside A and B; keep clocks synchronized. The driver's before/after samples are not a continuous history. A last green sample is not permission to promote.
- Client needs Python 3.9+, OpenSSH and curl. Hosts need util-linux, DRBD utilities, Python 3.9+, systemd with
busctl --json=short, cgroup v2 and a dedicated sudo-capable pilot account. Use the stock runner undersystem.slice. Root must see all host PIDs and their/proc/PID/exeand/proc/PID/cgroup, not a container PID namespace. The driver usessudo -nonly on the explicitly named machines. Keep the credentials and evidence outside DRBD. No tool installs, new credentials, network rules or DRBD changes are performed by the driver.
Example private client configuration; replace every example value from the pilot inventory:
{ "a": "pilot@mgmt-a.example.invalid", "a_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "b": "pilot@mgmt-b.example.invalid", "b_id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "srv": "srv.pilot.example.invalid", "known_hosts": "/secure/pilot/known_hosts", "srv_node_id": "nExampleSrv", "app_node_id": "nExampleGuest", "firecracker_bin": "/usr/bin/firecracker", "guest_ready_seconds": 180, "device": "/dev/drbd0", "fsroot": "/@srv", "running": "canary", "offline": "parked", "app": "https://canary.pilot.example.invalid", "a_asset": "pilot-chassis-A", "fence_probe": "/secure/pilot/read-fence-status"}
The client needs tailscale whois --json; pin the provisioned Node.StableID for each endpoint. Every application check verifies the IDs for all addresses returned by client DNS.
Set firecracker_bin to the actual runner executable setting (SRV_FIRECRACKER_BIN) and guest_ready_seconds to srv's effective guest readiness timeout in seconds (SRV_GUEST_READY_TIMEOUT, rounded up). Verify both settings on both hosts before the drill. The binary must be present outside DRBD on both hosts and must not change during a run. Root scans actual executable links, checks the content of matching jailer copies against this binary, and reads populated firecracker-vms and firecracker-pools cgroups independently. A passive host must have neither a matching process nor any populated guest group. On the active host both inventory entries must have kind vm; only the canary's inspected Firecracker PID may exist, in exactly its own named cgroup. An empty cgroup is not a running VM.
fence_probe is a site-supplied read-only executable on the independent client. It receives the asset ID as its sole argument. It must query current independent power, reboot inhibition and replication ACL state over authenticated management APIs (not SSH, ping, guest reports or a cached file). Return nonzero on uncertainty; output just JSON, without credentials, for example:
{"asset":"pilot-chassis-A","power":"off","restart_inhibited":true,"replication_paths_blocked":false,"observed_unix":1900000000.0}
observed_unix is the actual observation time, not an example to copy. The driver rejects observations older than 30 seconds, future timestamps, wrong assets and inconsistent values. The probe must not change power or policy. Approvals and switches remain manual. Without a real probe and independent history do not run the crash takeover.
21.2 Run one scenario at a time
Use an interactive terminal and a new evidence file for each run:
umask 077SRV_DRBD_DISPOSABLE_PILOT=YES python3 test/drbd_pilot.py standby \ --config /secure/pilot/site.json --evidence /secure/pilot/standby-01.jsonl
Each checkpoint names an action. Perform only that action (or authorize it if the driver says “Authorize” and performs it), enter an independent log/ticket reference, then type CONFIRM. For promotion/mount the operator executes the runbook; keep services off until the separate start checkpoint. Abort with Ctrl-C on uncertainty. No automated cleanup, resume or rollback follows a failure. Before each subsequent run, return to a known A-active/B-passive baseline using a separate planned handover, or reprovision fresh disposable disks. Never reuse a divergent pair by just reversing the names.
| Scenario | Evidence required to pass |
|---|---|
standby |
B boot ID changes. Secondary/UpToDate, no data mount or guest runtime, all units disabled and off. Each start must fail. Both units must have exactly one effective assert, the positive mount assert for /var/lib/srv. New PID 1 journal records must attribute the start job result assert to the requested unit, or show dependency for srv and assert for its required runner with the network helper active. Generic failure text is not proof. Clean up any network helper. |
restart |
Separate main-PID SIGKILL of srv, then runner on A. Each gets a new PID and increased systemd restart counter without manual start. All units active, runner Unix socket accepts connections, pinned srv CLI and guest HTTPS respond, acknowledged writes survive and new writes succeed. B stays passive. A failed recovery fails the test; do not promote B. |
planned |
External start list recorded before stopping guests. Both hosts confirmed synchronized and Secondary after A unmounts. B mount source/FSROOT/rw checked before services. Both VMs initially stopped; start only the listed canary, read earlier receipts, write/read a new one. Reboot former primary A and verify a connected passive standby with B still active. |
crash |
With a running guest, hard-fence A and inhibit restart. Require live fence proof and operator-reviewed history covering the last possible writes. Normal promotion only. B must recover the previously running guest without a manual guest start, leave the parked guest off, and serve acknowledged and new data. Afterward, rehearse ambiguous rejoin: block links before boot and prove that state from outside. Boot isolated A; check both sides remain disconnected, A unmounted and passive, B serving. Leave paths blocked pending data-authority decision. |
partition |
With A still on, disconnect replication only. Record alarm, acknowledge a solo guest write; B remains passive. Only here restore the known-good A-source link and wait for full resync. |
solo |
After the same split and a confirmed solo write, hard-fence A. B's local UpToDate is insufficient: record the STOP/escalation and verify B still passive. Preserve both copies. |
gap |
Interrupt external event capture after green, then hard-fence A. Despite positive power-off proof and B locally UpToDate, record STOP/escalation and verify no takeover. Keep both copies. |
21.3 Interpret results
For both handovers the driver checks all three units are off and the privileged runtime scan is empty twice on B: after promotion while still unmounted, and after verifying the mount before authorizing service start. A planned guest start is sent only once, with the configured readiness budget plus 60 seconds for SSH and lifecycle overhead. If the reply times out or fails, the driver records the uncertain outcome, tries read-only inspect and a host runtime scan, and stops. Do not issue another start based on the missing reply. Reconcile the PID, cgroup, application and journal before deciding what to do. A crash drill never sends a guest start.
The external JSONL includes command results, timestamps, acknowledged tokens, subsequent reads, referenced decisions and the first verified healthy time. Compare it with console/power events to measure actual fault-to-client recovery; the reported checkpoint interval includes operator time. Archive external monitoring (including gap and alarm), unit journals, console IDs, client identity observations, receipts and evidence references together. Inspect for transient mounts, guest starts, wrong-direction resync or simultaneous writers between samples. Record missing receipts as data loss, not as a successful restart. Keep backups independent of either host.
PASS for solo/gap means the operator refused takeover and the driver observed a passive B, not that production automation enforced a refusal. No scenario authorizes --force, discarding a copy or reconnecting an ambiguous peer. If either history is unclear, retain isolation and preserve both disks for a separate recovery decision. A future approved return uses the runbook and a new evidence record. No real-site acceptance is claimed by adding this test.
22. Export and import
The export and import commands stream a portable VM artifact between hosts. This is the supported way to move a VM from one srv host to another.
22.1 Export
On the source host:
ssh srv stop demossh srv export demo
The command writes a tar stream to stdout. The artifact contains:
- A versioned manifest
- The writable
rootfs.img - Serial and Firecracker logs when present (each capped to the newest 256 MiB)
22.2 Import
Pipe the export stream directly into the destination host:
ssh srv-a export demo | ssh srv-b import
Import creates the VM under the same name on the destination host, allocates new runtime paths and network state, and leaves the VM stopped.
22.3 Start after import
ssh srv-b start demo
The destination host uses its currently configured SRV_BASE_KERNEL and optional SRV_BASE_INITRD — only the writable disk and optional logs come from the streamed artifact.
22.4 Important semantics
Because the guest's durable Tailscale identity lives in the copied rootfs:
- Do not boot the source and destination VMs at the same time — this would cause a Tailscale key conflict
- Treat export/import as cutover or move semantics, not cloning semantics
The destination host regenerates:
- Absolute file paths (runtime directories)
- TAP device wiring
- Guest MAC address
- VM
/30subnet allocation
The artifact preserves:
- VM name
- Creator identity
- Machine shape (vCPUs, memory, rootfs size)
- Last-known Tailscale name and IP (as cached state)
22.5 Save to a file
You can also save the export to a file for later or offline transfer:
ssh srv export demo > demo-backup.tar
Then on the destination:
cat demo-backup.tar | ssh srv import
23. Host snapshot bundles
ssh srv snapshot create is an admin-only local disaster-recovery operation.
It rejects new control-plane commands, drains admitted commands, inventories
storage, checkpoints SQLite, and flushes the filesystem under the existing
snapshot barrier. It snapshots the data root and every managed disk subvolume
read-only, flushes the complete bundle, atomically publishes it, then flushes the
archive before reporting success. Sending just the root snapshot is not a
complete backup: btrfs snapshots are not recursive.
23.1 Layout and consistency
SRV_DATA_DIR must be a btrfs subvolume. Supported nested disk subvolumes are:
instances/<name>/disk(both VMs and Orbs)templates/<owner>/<template>/diskbackups/<name>/<backup>/diskimage-bases/<sha256>/disk(content-addressed distribution image bases)
Each must contain a nonempty regular rootfs.img. Before lazy migration,
instances, templates and backups may instead have a regular rootfs.img directly
in their object directory, with no disk entry. These legacy files are captured
in the root component, so stopped or running guests need not be started just
to make host backups available. SQLite instance paths must match the actual
canonical or legacy layout. Image bases must use the new subvolume layout.
Missing/nonregular/empty disk images, simultaneous legacy and canonical layouts,
pending disk migration journals/stages, ordinary disk directories, storage-path
symlinks, and unknown nested subvolumes cause failure, not partial success.
Runtime links such as instances/<name>/firecracker.sock are allowed and captured
as links, not followed. Do not mutate host storage outside srv during capture.
.snapshots must itself be a subvolume on the same filesystem; srv creates it if
absent. This keeps earlier bundles out of subsequent root snapshots. An existing
ordinary .snapshots directory is rejected: with srv and guests stopped, move
the legacy archive outside the live data root, create the archive subvolume,
and retain/migrate the old snapshots separately. Do not simply rename the old
archive within the data root. Legacy single-root snapshots are not v1 bundles.
Published bundles are ordinary directories .snapshots/<timestamp>/ containing
manifest.json, root, and flat disk-000000, disk-000001, … readonly
subvolumes. Manifest format v1:
{ "version": 1, "id": "20260101T000000.000000000Z", "created_at": "2026-01-01T00:00:00Z", "components": [ {"source": ".", "path": "root", "source_uuid": "", "snapshot_uuid": ""}, {"source": "instances/example/disk", "path": "disk-000000", "source_uuid": "", "snapshot_uuid": ""} ]}
source is relative to the live data root; path is relative to the bundle.
The root is first, followed by all inventoried disks in lexical walk order.
UUID values above are illustrative; real manifests record btrfs source and
snapshot UUIDs for every component. Source identity is checked again after
capture; identity inspection errors or changes prevent publication. Legacy
regular files have no separate subvolume UUID or component: their ownership and
contents are within root and its captured SQLite/metadata records.
Directories named .incomplete-<timestamp>-<random> are never usable backups,
even if they have a manifest. A manifest describes the intended inventory; its
presence alone does not prove completion. Failure after publication but before
the final flush is reported as durability unconfirmed, not success.
- Control-plane consistent: SQLite is checkpointed and lifecycle mutations remain blocked for the entire bundle capture.
- Stopped guests fully safe: their disk contents are consistent on disk.
- Running guests individually crash-consistent: each disk is captured at a different instant, like losing power independently. This is not a global point in time or an application-consistent distributed backup. Guest RAM is not captured. Stop guests/application writers first when stronger consistency is required; a running per-VM backup is not application-consistent either.
23.2 Replicate the whole bundle
Replication happens after publication, outside the barrier. Keep the source
bundle until every component is received and verified. On the receiving btrfs
filesystem create a private staging directory, e.g.
/backup/srv/.incomplete-<id>; never receive directly into a completed bundle.
For each components[].path, send its own stream:
# Bash; BUNDLE is an absolute, completed local bundle path.set -euo pipefailjq -e '.version == 1' "$BUNDLE/manifest.json" >/dev/nullwhile IFS= read -r component; do sudo btrfs send "$BUNDLE/$component" | ssh backup-host "sudo btrfs receive /backup/srv/.incomplete-$ID"done < <(jq -r '.components[].path' "$BUNDLE/manifest.json")scp "$BUNDLE/manifest.json" "backup-host:/backup/srv/.incomplete-$ID/manifest.json"
Set ID to the manifest ID; create the destination staging directory beforehand
with permissions allowing the receiving operator to copy the manifest. These
commands assume trusted srv-generated paths/IDs, not an untrusted manifest.
On the receiver check the version and ID, require unique source/path entries,
one root entry, supported relative disk paths without traversal, and every
listed component present as a readonly btrfs subvolume. Compare the received
manifest with the sender's. On the sender, btrfs subvolume show must report each
component's UUID equal to its snapshot_uuid. On the receiver, the Received
UUID, not its newly allocated local UUID, must equal snapshot_uuid. Do not
compare filesystem-local numeric subvolume IDs across hosts. Check successful exit status for every send/receive;
do not publish on a truncated stream or missing component. Flush with
sync -f /backup/srv/.incomplete-<id>, rename without overwriting to
/backup/srv/<id>, and sync -f /backup/srv. Protect the manifest and components
against modification. Incremental replication must track a valid parent for
each component separately; a root-only incremental stream is insufficient.
23.3 Restore offline
- Stop srv and all guest runners; stop external writers. Restore on an isolated host first and avoid concurrently starting duplicate guest/network identities. Preserve the current data tree for rollback.
- Validate the complete bundle as above. Use a fresh, nonexistent restore path
on the same btrfs filesystem as the bundle (receive there first if needed).
Create a writable root clone:
btrfs subvolume snapshot "$BUNDLE/root" "$RESTORE". - For every non-root manifest entry, remove only the empty placeholder at
$RESTORE/<source>usingrmdir(fail if it is not empty); create a writable clone withbtrfs subvolume snapshot "$BUNDLE/<path>" "$RESTORE/<source>". Do not copy the disk image alone or flatten the subvolume. Check every exit status. Templates, backups and image bases must also be restored as disk subvolumes; usesnapshot -rfor those immutable components instead. Legacy file-only objects already exist in the root clone: leave them there for lazy migration, and do not invent additional components or move their files. - Remove the empty
$RESTORE/.snapshotsplaceholder usingrmdirand create it withbtrfs subvolume create "$RESTORE/.snapshots". The old archive is deliberately not inside the root snapshot; retain it separately. Verify all listed rootfs images and subvolumes, run an offline SQLite integrity check onstate/app.db, and flush the filesystem. - With services still stopped, switch the reconstructed root into the original
SRV_DATA_DIRlocation/mount. Preserve the original absolute path because stored paths refer to it. Restore host configuration and prerequisites, then start srv and deliberately start guests, checking disk recovery/application health. Running-guest disks may need journal replay. Do not regard a root-only restore as successful even if SQLite opens.
23.4 Retention, failures, and confidential data
Bundles retain deleted guest/template/backup data until all matching archive
components are removed. For cleanup proof, inspect every completed manifest's
components[].source; also inspect .incomplete-* bundles, whose manifests may
be absent or only partially written. The root component can contain legacy
guest/template/backup images even without a separate disk entry. Inspect its
captured tree/metadata too. Match recorded snapshot UUIDs before deleting
components; do not treat a replaced path as the same snapshot. Never infer erasure from removing live
instances/<name>/disk alone. The archive can also contain legacy snapshots.
With no active snapshot/replication, delete each bundle's readonly component
using btrfs subvolume delete, then remove its manifest and empty directory;
do not use recursive filesystem deletion as a subvolume retention algorithm.
Confirm filesystem sync/deletion completion before claiming local reclamation.
Off-host copies require separate retention/erasure handling.
Not included: /etc/srv/srv.env, systemd overrides, external images/configuration,
Firecracker/jailer binaries, or any data outside SRV_DATA_DIR. Back these up
separately. Optional cold storage
is separate from host-bundle replication. Snapshot creation rejects every
cold-disk.json marker, including retained remote copies of now-hot disks. Hydrate
and purge those generations first; a successful bundle remains self-contained.
23.5 Integration validation
On a disposable btrfs filesystem, create a data-root subvolume with VM, Orb,
template, backup and image-base disk subvolumes containing distinct data, plus
legacy file-only objects and runtime socket symlinks. Capture a bundle,
mutate live disks, and verify all snapshot images retain the original data.
Capture again and verify root/.snapshots is an empty placeholder. Check missing
images and unknown nested subvolumes fail. Inject a component/sync failure and
verify no success is reported. Send/receive all components to another test
filesystem and perform the offline reconstruction above; check SQLite and all
disk contents and boot stopped/restored guests. Repeat with running writers to
exercise crash recovery, without asserting cross-guest simultaneity. Unit tests
cover inventory and publication failure paths; they do not replace this test.
24. Instance lifecycle
This page covers the full lifecycle of a srv VM from creation to deletion.
24.1 Create
ssh srv new
Arch is the default. To select a configured image at creation:
ssh srv new debian-vm --image debian-13
The image stays with the VM; start does not change its operating system.
See image configuration for the
host-side catalog and the Debian builder
for the basic Debian 13 rootfs without Arch's optional developer/agent tools.
With custom sizing:
ssh srv new --cpus --ram --rootfs-size
--ram and --rootfs-size accept units like 2G, 512M, or plain MiB integers. --cpus must be 1 or an even number, up to 32.
The control plane:
- Clones the base rootfs as a reflink
- Allocates a
/30network subnet and TAP device - Mints a one-off Tailscale auth key via MMDS
- Boots the VM through the jailer with cgroup v2 enforcement
- Polls until the guest reports
state: ready
24.2 Inspect
ssh srv inspect
Shows instance state, vCPU count, memory, rootfs size, network addresses, Tailscale name and IP, and event history.
Machine-readable:
ssh srv -- --json inspect
24.3 List and status
ssh srv listssh srv status
list shows the VMs visible to the caller: all VMs for admins, or only the caller's own VMs for regular users. status is admin-only and reports host capacity — instance counts plus CPU, memory, and disk headroom.
The storage rows answer two different questions:
DISK RSVis logical rootfs reservation headroom. This is the budget used to admitnew,start, and rootfs-growingresizeoperations.FS SPACEis the filesystem's actual used and available space. It also reflects backups, reflink divergence, logs, and other files outside rootfs reservations; shared reflink extents count only once until they diverge.
Use FS SPACE to detect physical storage pressure even when the logical reservation budget still has room.
24.4 Logs
ssh srv logs ssh srv logs serial ssh srv logs firecracker ssh srv logs -f serial ssh srv logs -f firecracker
The serial log is append-only across boots. The Firecracker log is reset when the VMM starts so it only contains the current Firecracker process's output.
24.5 Stop
ssh srv stop
Performs a graceful shutdown through Firecracker. The rootfs is preserved on disk.
24.5.1 Save RAM before stopping
For a VM or Orb that should continue its running processes after host maintenance:
ssh srv stop --save-state
This pauses the guest, saves its RAM and device state, then terminates the VMM without running guest shutdown. Wait for the command to succeed before restarting the runner or host. Ordinary stop, restart, and runner shutdown do not create RAM snapshots. The VM must have been started by a runner with RAM-state support.
There is one host-local saved state per instance, with no snapshot names or history. The disk stays in place and must not change while RAM is saved. Resize, fsck, kernel upgrades, restore, migration, and cold-disk offload are blocked until the state is resumed or discarded. Deleting the instance removes its saved RAM.
Allow disk space for the guest's configured RAM plus at least 256 MiB. An error
after pausing can leave the guest paused; retry stop <name> --save-state after
fixing the error. Never interpret a failed save as permission to reboot the host.
Saving RAM requires the jailer and instance directories to share a filesystem
and subvolume that permits atomic rename between them. Unsupported layouts are
rejected before pausing or recording save intent. A repeated save request only
succeeds while that attempt's saved image still exists; an already consumed image
is not reported as a successful new save.
24.5.2 Keep RAM only if there is room
ssh srv stop --cache-state
This is the best-effort form. It saves RAM only if the host's RAM cache
(SRV_RAM_CACHE_SIZE on the runner) has room, after evicting the least recently
saved images. Otherwise it is an ordinary stop, and the command still succeeds.
srv can discard a cached image later, for example to offload the disk to cold
storage. The instance then boots from its disk. The guest freezes its
filesystems before the save, so the disk is complete without the RAM.
Only Orbs can cache RAM, because the freeze uses the Orb guest agent. For other
instances --cache-state is an ordinary stop. The Amp provider uses this form
when SRV_ORB_RAM_CACHE=true; see
the RAM cache for pauses.
24.6 Start
ssh srv start
Boots a previously stopped VM with its stored kernel and initrd paths. To change the kernel and modules, follow the kernel rollout procedure.
If saved RAM exists, start resumes it automatically. To discard it and boot fresh:
ssh srv start --discard-state
Restore consumes the saved state before guest execution resumes, so a lost response
cannot replay the same execution state. A failed restore does not fall back to a
cold boot. Configuration or disk mismatches detected before restore leave the saved
state intact and require an explicit --discard-state to proceed. A cold start
with that flag removes the saved state as well.
Resume requires the same host, unchanged disk and VM configuration, and compatible
host software. Save records --snapshot-version from the producing executable
opened through /proc/PID/exe, even if the installed Firecracker was replaced
while the VM was running. Start uses the currently installed binary. Its snapshot
format must match exactly; a changed SHA256 is allowed, but no compatibility is
inferred from Firecracker release numbers or semver ranges. Old binaries are not
retained.
A different snapshot format causes start to delete the saved RAM and cold boot with the existing disk. Older manifests without a format version receive the same treatment, even if the recorded binary digest still matches. The runner logs a warning with the reason (and both versions for a format mismatch). Configuration, source-receipt and disk checks run first; their failures preserve the saved state. A failed or malformed version query also preserves it and rejects start. Unexpected restore failures remain quarantined, without an automatic cold fallback.
Do not replace the installed Firecracker during a start operation. The version probe holds its executable open, but the jailer subsequently opens the installation path again. An upgrade between those steps can turn a compatible admission into a failed restore and quarantine; srv does not lock the host's package manager.
Matching formats do not guarantee host-kernel/KVM compatibility. Host upgrades can still prevent restore. Existing network connections may break, and vsock connections are reset; applications must reconnect. The guest needs clock synchronization after a long pause.
The saved files disappear on resume. Firecracker still holds a private memory mapping of the unlinked RAM file, so its disk blocks remain allocated until that VMM exits. This is not a reusable backup or an Amp project-template snapshot.
24.6.1 Runner API
The privileged runner uses HTTP over its local Unix socket (normally
/run/srv-vm-runner/vm-runner.sock). Use the SSH commands for normal operation;
they also update instance state, networking, and readiness in the control plane.
| Request | Body | Result |
|---|---|---|
POST /vm/stop-state-v1 |
Existing stop request plus "save_state": true |
204 after durable save, VMM termination, and runtime cleanup |
POST /vm/start-state-v1 |
Existing full start request; omit discard_state or set it to false |
Resume if present, otherwise cold boot; existing outcome, reason, pid response |
POST /vm/start-state-v1 |
Existing full start request plus "discard_state": true |
Remove saved RAM and cold boot |
Stop must identify the running attempt with name, instance_id, request_id,
and host_boot_id; a PID alone cannot authorize saving RAM. Start supplies a new
request ID and the current host boot ID, along with the usual boot, network, CPU,
and memory configuration. Retry the same start request to recover its outcome,
or use POST /vm/start-result; do not invent a new attempt after an unknown result.
The existing /vm/start and /vm/start-v2 routes also resume saved RAM by default.
The versioned state endpoints make an older runner reject unsupported requests
instead of silently ignoring the save/discard flag.
24.7 Restart
ssh srv restart
Stops and starts the VM in one command. Also picks up the current kernel and initrd.
24.8 Check the root filesystem
ssh srv stop ssh srv fsck && ssh srv start
fsck runs e2fsck -f -p against the stopped VM's ext4 rootfs. It forces a full check and automatically repairs problems that can be fixed safely. Fatal or uncorrected filesystem errors make the command fail and leave the VM stopped.
24.9 Delete
ssh srv delete
Removes the VM's rootfs, runtime directory, TAP device, cgroup, and jailer workspace. This is irreversible.
24.10 Warm boot behavior
When a VM that already has tailscaled state reboots (via start or restart), it reuses its existing Tailscale identity instead of minting a new auth key. This is called a warm boot.
On cold boot (first new), the guest bootstrap service reads the Tailscale auth key from MMDS and runs tailscale up --auth-key=... --ssh exactly once.
25. Resize a VM
Resize lets you change the vCPU count, memory, memory pool, and rootfs size of a stopped VM or Orb.
25.1 Prerequisites
- The VM must be stopped — resize is rejected for running VMs
- vCPUs and memory can be increased or decreased as long as the requested values stay within the supported limits
- Rootfs size is grow-only — shrink requests are rejected
- The srv host must have both
e2fsckandresize2fsavailable for a rootfs grow (and when creating a VM with a custom rootfs size)
25.2 Resize
ssh srv stop demossh srv resize demo --cpus 4 --ram 8G --rootfs-size 20Gssh srv start demo
You can combine flags except --pool and --fixed-memory, which are mutually exclusive. Omitted flags keep the current value:
# Only increase RAMssh srv stop demossh srv resize demo --ram 16Gssh srv start demo
25.3 Assign a memory pool
Use --pool to move an existing VM or Orb into an existing memory pool, or to switch pools:
ssh srv stop demossh srv resize demo --pool sharedssh srv start demo
The guest-visible RAM stays unchanged unless you also pass --ram. It must fit within the target pool's reservation. For example, resize demo --pool shared --ram 2G changes both in one operation.
25.4 Return to fixed memory
Use --fixed-memory to remove a stopped VM or Orb from its pool:
ssh srv stop demossh srv resize demo --fixed-memoryssh srv start demo
RAM stays unchanged unless you also pass --ram, for example resize demo --fixed-memory --ram 4G. The old pool remains available and keeps its reservation. As with other fixed-memory resizes, host memory capacity is checked on the next start. Using --fixed-memory on an already fixed-memory instance is allowed.
25.5 How it works
- vCPU count: stored in the instance record and applied on the next boot
- Memory: stored in the instance record and applied on the next boot
- Memory pool: the pool assignment is stored in the instance record and applied on the next boot
- Rootfs size: runs
e2fsck -f -pagainst the stopped ext4 image, expands the underlying file, and then usesresize2fsto grow the filesystem. Fatal or uncorrected filesystem errors stop the resize before the image is expanded. This operation only increases the filesystem — it never shrinks
If an earlier attempt expanded the image file but did not finish growing the filesystem, retrying the same resize request checks the filesystem and resumes the pending filesystem grow.
Rootfs resize modifies the disk image in place. Take a backup first if you want a safety net.
25.6 Limits
| Dimension | Minimum | Maximum |
|---|---|---|
| vCPUs | 1 | 32 |
| Memory | 128 MiB | host limit |
| Rootfs | current size | host disk limit |
vCPU count must be 1 or an even number. CPU and memory changes are applied on the next boot.
26. View logs
srv provides two log sources for each VM: serial output and Firecracker VMM logs.
26.1 Serial log
Shows kernel boot, srv-bootstrap.service, tailscaled, and general guest console output:
ssh srv logs demossh srv logs demo serialssh srv logs -f demo serial
26.2 Firecracker log
Shows VMM lifecycle events, API requests, and microVM-level errors:
ssh srv logs demo firecrackerssh srv logs -f demo firecracker
26.3 Both logs at once (default)
Without a log source argument, ssh srv logs <name> shows the serial log by default.
26.4 Where logs live on the host
| Log | Path |
|---|---|
| Serial | SRV_DATA_DIR/instances/<name>/serial.log |
| Firecracker | SRV_DATA_DIR/instances/<name>/firecracker.log |
The serial log is append-only across boots. The Firecracker log is reset when the VMM starts so it only contains the current Firecracker process's output.
26.5 Systemd logs
The VM runner and network helper also log to journald:
sudo journalctl -u srv-vm-runner -fsudo journalctl -u srv-net-helper -fsudo journalctl -u srv -f
26.6 Debugging a failed VM
When a VM is stuck or has failed:
ssh srv inspect <name>— control-plane view, state, and recorded eventsssh srv logs <name> serial— guest boot and bootstrap errorsssh srv logs <name> firecracker— VMM errorsjournalctl -u srv-vm-runner --no-pager— jailer and stop-time cleanup failures- Check cgroup limits:
cat /sys/fs/cgroup/firecracker-vms/<name>/memory.max
27. Dev/test environment
srv's reflink-based cloning makes it fast to spin up a VM from a base image, modify it, and then use backup/restore to reset it to a known-good state.
27.1 Create a dev VM
ssh srv new dev --cpus 4 --ram 8G --rootfs-size 30G
27.2 Install your toolchain
ssh root@dev# Inside the VMpacman -Syupacman -S nodejs npm# ... set up your project ...
27.3 Back up the clean state
Once the VM is configured the way you like, take a checkpoint before making risky changes:
ssh srv stop devssh srv backup create devssh srv start dev
27.4 Wipe and reset
After a bad experiment:
ssh srv stop devssh srv backup list devssh srv restore dev ssh srv start dev
The restore rolls the rootfs back to the exact state captured at backup time. This is fast because it replaces the writable disk image rather than copying file by file.
27.5 Repeat
You can create multiple backups at different points:
ssh srv stop devssh srv backup create dev # backup 1: cleanssh srv start dev# ... make changes ...ssh srv stop devssh srv backup create dev # backup 2: with toolchainssh srv start dev
Then restore whichever snapshot you need:
ssh srv stop devssh srv restore dev ssh srv start dev
27.6 Key constraints
- Backups and restores only work on stopped VMs
- Backups are tied to the original VM record — they cannot be restored onto a differently created VM even if the name is reused
- Restore is in-place: it overwrites the VM's current rootfs with the backup's rootfs
28. Isolated service
Each srv VM runs in its own cgroup v2 leaf with its own /30 network subnet, TAP device, and Tailscale identity. This makes it straightforward to run services that need full isolation — container runtimes, network services, databases — without sharing the host's PID, network, or filesystem namespace.
28.1 Run a database
ssh srv new db --cpus 2 --ram 4G --rootfs-size 20G
Once the VM is ready:
ssh root@dbpacman -S postgresql# ... configure and start postgresql ...
The database is now reachable at its Tailscale IP from any other machine on the tailnet.
28.2 Run Docker workloads
The guest image includes Docker and docker-compose:
ssh srv new builder --cpus 4 --ram 8G --rootfs-size 40G
ssh root@builderdocker run ...docker compose up -d
The overlay and br_netfilter kernel modules are preloaded, and nftables supports both IPv4 and IPv6 families.
28.3 Per-VM resource isolation
Each VM is enforced by cgroup v2:
| Resource | Limit |
|---|---|
| CPU | vCPU count (advisory, allows overcommit) |
| Memory | Requested RAM, no swap |
| PIDs | 512 by default (SRV_VM_PIDS_MAX) |
You can verify the live cgroup limits:
cat /sys/fs/cgroup/firecracker-vms//cpu.max cat /sys/fs/cgroup/firecracker-vms//memory.max cat /sys/fs/cgroup/firecracker-vms//memory.swap.max cat /sys/fs/cgroup/firecracker-vms//pids.max
28.4 Per-VM networking
Each VM gets its own /30 subnet, TAP device, and NAT rules. VMs cannot reach each other's private networks. They can reach the host and the internet through MASQUERADE rules.
From any tailnet machine, you can SSH directly to the VM's Tailscale name or IP — no port forwarding needed.
28.5 Clean separation
When the service is no longer needed:
ssh srv delete db
The rootfs, TAP device, cgroup, jailer workspace, and iptables rules are all cleaned up.
29. Throwaway debug VM
One of the most immediate uses for srv is spinning up an isolated Linux environment where you can install packages, run risky commands, or reproduce a bug — then delete it without any trace on the host.
29.1 Create
ssh srv new debug-vm
By default the VM gets 1 vCPU, 1 GiB of RAM, and a 10 GiB rootfs. Adjust if you need more:
ssh srv new debug-vm --cpus 2 --ram 4G --rootfs-size 30G
29.2 Watch it boot
ssh srv logs -f debug-vm serial
You will see the kernel boot, srv-bootstrap.service set up networking and Tailscale, and tailscale up --ssh complete. Once inspect reports state: ready:
ssh srv inspect debug-vm
Look for the tailscale-name and tailscale-ip fields.
29.3 Connect and use
ssh root@debug-vm
The guest image comes with Docker, Go, Neovim, Git, perf, valgrind, and common development tools preinstalled. Install anything else with pacman -S.
29.4 Clean up
When you are done:
ssh srv delete debug-vm
This removes the VM's rootfs, runtime directory, TAP device, cgroup, and jailer workspace. No trace remains on the host.
29.5 Tips
- Use
-- --json inspect <name>to get machine-readable output for scripting - The serial log under
ssh srv logs <name> serialis append-only — always check the newest lines - If a VM gets stuck in
provisioningorfailed, checkssh srv inspect <name>for thelast_errorfield andssh srv logs <name> firecrackerfor VMM errors
30. Networking overview
Every srv VM gets its own isolated network stack: a dedicated /30 subnet, TAP device, and NAT rules. Guest egress is routed through the host's outbound interface after MASQUERADE.
30.1 How it works
Internet │ │ (host outbound interface) │┌───┴─────────────────────┐│ Linux host ││ ┌──────────────────┐ ││ │ iptables MASQ │ ││ │ + FORWARD rules │ ││ └────────┬─────────┘ ││ │ ││ ┌────────┴─────────┐ ││ │ TAP device │ ││ │ (per-VM /30) │ ││ └────────┬─────────┘ ││ │ ││ ┌────────┴─────────┐ ││ │ Firecracker VM │ ││ │ gateway = .1 │ ││ │ guest = .2 │ ││ └──────────────────┘ │└─────────────────────────┘
When ssh srv new demo runs, the network helper:
- Allocates the next free
/30fromSRV_VM_NETWORK_CIDR(default172.28.0.0/16) - Creates a TAP device for the VM
- Installs MASQUERADE and FORWARD rules for guest egress
- Configures the gateway address on the host side
The VM's bootstrap configures the guest interface with:
- Gateway:
SRV_DATA_DIR-derived host address (first usable IP in the/30) - Guest IP: second usable IP in the
/30 - DNS: configurable via
SRV_VM_DNS(default1.1.1.1, 1.0.0.1)
30.2 Tailscale integration
Each VM gets its own Tailscale identity. The control plane mints a one-off auth key and injects it through Firecracker MMDS metadata. The guest bootstrap service:
- Reads the MMDS payload
- Starts
tailscaled - Runs
tailscale up --auth-key=... --sshon the first authenticated boot - Persists
tailscaledstate for warm reboots
This means any machine on the tailnet can reach the VM by its Tailscale name or IP — no port forwarding needed.
30.2.1 SSH access
Guests expose SSH through Tailscale's --ssh flag, so ssh root@<tailscale-name> works from any tailnet machine. Per-user OpenSSH keys are not injected — Tailscale SSH handles authentication based on tailnet identity.
30.2.2 Application and development services
Tailscale connectivity is not limited to SSH or HTTP. A service listening on a Tailscale-reachable guest address can be reached by authorized tailnet devices over TCP or UDP, under the VM identity and the tailnet's ACLs. This supports web applications, databases, debuggers, custom protocols, and multiple ports without host-side port forwarding.
For Amp runner VMs, this provides the network-connectivity role of an Orb Portal with a broader protocol surface. It does not provide Amp-managed HTTPS, thread embedding or annotation, public/thread-visibility access, or automatic Orb sleep/wake integration. Service availability follows the srv VM lifecycle.
30.3 Configuration
| Variable | Default | Description |
|---|---|---|
SRV_VM_NETWORK_CIDR |
172.28.0.0/16 |
IPv4 network reserved for VM /30 allocations |
SRV_VM_DNS |
1.1.1.1,1.0.0.1 |
Comma-separated guest nameservers |
SRV_OUTBOUND_IFACE |
auto-detected | Optional override for the host interface used for NAT |
SRV_EXTERNAL_UPLINKS |
empty | Host interfaces through which external-only guests may forward |
SRV_EXTERNAL_DENY_CIDRS |
empty | Additional IPv4 destinations external-only guests must not reach |
SRV_OUTBOUND_IFACE only selects which interface the MASQUERADE rule matches. It does not choose a route, gateway or source address: the host's routing table has already chosen the output interface.
30.4 IPv4 forwarding
Guest NAT depends on IP forwarding:
sudo tee /etc/sysctl.d/90-srv-ip-forward.conf >/dev/null <<'EOF'net.ipv4.ip_forward = 1EOFsudo sysctl --system
This must stay enabled. Disabling it breaks guest egress.
30.5 Network cleanup
When a VM is deleted, the network helper removes:
- The TAP device
- The MASQUERADE rule
- The FORWARD rule
- The gateway address from the host interface
30.6 Guests without Tailscale
new <name> --guest-network host creates an ordinary VM that never joins the tailnet. The default remains a Tailscale guest. The control plane is unchanged: commands still arrive over the embedded tsnet node and are authorized by Tailscale identity.
The guest gets no enrollment key and Tailscale is masked in the guest even if the image contains it. Readiness is a nonce-bound report the guest bootstrap writes to the serial console for each start attempt, so a report from an earlier boot never makes a new start ready. Readiness proves that this boot completed its bootstrap, not that SSH or applications work. Otherwise the guest uses ordinary VM networking, including NAT and host-side gateways.
Manage the guest over SSH from the host, for example ssh -J <host> root@<guest-ip>. Take the guest IP from inspect; the ED25519 host key fingerprint the guest reported at boot appears in its inspect events. Authorized keys come from the image; srv does not relay SSH or manage guest keys.
stop --save-stateis refused for guests without Tailscale: a RAM resume skips the bootstrap and could not report a fresh boot nonce.startrefuses to resume any saved RAM;start <name> --discard-statecold-boots instead.- Export artifacts of these guests use manifest version 5, which older servers refuse to import.
30.6.1 External-only guests
new <name> --guest-network external-only creates a guest without Tailscale, as above, that is also confined to the internet. The network helper installs these rules before it brings the TAP up, and srv does not start the guest until they are in place:
INPUT,FORWARDandOUTPUTjump to srv-owned chains as their first rule. Rules that other tools later insert ahead of them are detected.- Forwarded guest traffic must come from the guest's single address, not just the guest's
/30. It must not go to private, special-purpose, carrier-grade NAT or tailnet ranges, the VM network, orSRV_EXTERNAL_DENY_CIDRS. It may leave only throughSRV_EXTERNAL_UPLINKS. Everything else is dropped, including traffic that a host route sends to another interface, so a lost uplink fails closed and never falls back to another route. All other internet destinations are allowed. - Nothing may open a connection to the guest: not other VMs, the LAN or the host. The one exception is TCP 22 from the host itself. The guest cannot open connections to any host address, and the host accepts replies from the TAP only from the guest's address.
- IPv6 is disabled on the TAP and dropped in
ip6tables. - No provider, integration or Amp CONNECT gateway is exposed, and
--integrationis refused.
For an image with an OpenSSH server and no Tailscale, see the Debian builder's external-only variant.
The service starts a check of every running external-only guest's rules every 5 seconds. If rules are missing, reordered or behind another tool's rule, or the helper cannot check them, the helper takes the TAP down and srv stops the guest. This is detection, not continuous enforcement. After an external firewall flush or reload, the guest is unconfined until a check detects it. That time has no fixed upper bound: the check interval is only one part of it, alongside helper response time and checks of other guests that run first. Stop external-only guests before you reload the host firewall. A start reinstalls the rules. When srv restarts, it reapplies the current rules to running external-only guests before the first check, so changed SRV_EXTERNAL_UPLINKS and SRV_EXTERNAL_DENY_CIDRS take effect without stopping them. While the srv service is stopped, nothing checks the rules.
Limits:
- srv confines which host interface carries guest traffic. It cannot prove how routers beyond that uplink forward a public address. A public address of your own site, or an internet relay that reaches back into it, is reachable unless you list it in
SRV_EXTERNAL_DENY_CIDRS. - The rules use
iptables/ip6tableson the host. The host must have IPv6 enabled so that the helper can disable it on the TAP. They have been tested withiptables1.8 using the nf_tables backend, not withiptables-legacy. - An imported external-only guest starts only where
SRV_EXTERNAL_UPLINKSis configured.
30.7 Host-side API gateways
srv can also expose host-side HTTP gateways on each VM's gateway IP:
- Provider gateways on
SRV_ZEN_GATEWAY_PORTandSRV_DEEPSEEK_GATEWAY_PORTproxy/v1/...to configured LLM upstreams with host API keys injected. - The generic integration gateway on
SRV_INTEGRATION_GATEWAY_PORTproxies/integrations/<name>/...to operator-defined HTTP integrations with host-managed auth or headers injected. - The Amp CONNECT gateway on
SRV_AMP_CONNECT_GATEWAY_PORT(default3128) provides an HTTP proxy for public HTTPS destinations.inspect --jsonexposes its URL asinstance.amp_connect_gatewaywhile the VM is active.
All gateway types only accept requests from the owning guest IP. See Provider gateways and HTTP integrations.
30.7.1 Amp CONNECT gateway
The CONNECT gateway is intended for an Amp runner whose general HTTPS egress must pass through the per-VM host endpoint. Set both HTTP_PROXY and HTTPS_PROXY in the guest to the URL returned by inspect --json; the bundled Amp runner plugin does this automatically.
This is a tunnel, not a TLS-terminating proxy: srv does not inspect HTTPS payloads or inject credentials. To prevent the proxy from becoming a path into the host or tailnet, it accepts only the CONNECT method, only permits destination port 443, and rejects loopback, link-local, private, carrier-grade NAT, documentation, multicast, other special-use, and host-local addresses. Destinations are checked again after DNS resolution and connection.
Use NO_PROXY for guest-local services, the VM gateway services, tailnet destinations, and other endpoints that should not use public HTTPS proxying. The bundled Amp runner config excludes localhost, MMDS, the tailnet, and the guest gateway, then appends any noProxy entries from ~/.config/amp/srv-runner.json.
31. Provider gateways
When API keys are configured on the host, srv sets up per-instance HTTP proxies that allow guest VMs to reach LLM provider APIs without storing real API keys inside the guest.
31.1 Providers
| Provider | Env var | Default upstream | Gateway port |
|---|---|---|---|
| OpenCode Zen | SRV_ZEN_API_KEY |
https://opencode.ai/zen |
11434 (SRV_ZEN_GATEWAY_PORT) |
| DeepSeek | SRV_DEEPSEEK_API_KEY |
https://api.deepseek.com |
11436 (SRV_DEEPSEEK_GATEWAY_PORT) |
Both gateways share the same architecture. Only providers with a configured API key are enabled.
31.2 How it works
┌───────────────────────────────────────────────────┐│ Host ││ ││ ┌───────────────┐ ┌────────────────────────┐ ││ │ srv control │ │ Provider gateways │ ││ │ plane │ │ :11434 (Zen) │ ││ │ │ │ :11436 (DeepSeek) │ ││ └───────────────┘ │ on gateway IP │ ││ │ │ ││ │ injects API key │ ││ │ into Authorization │ ││ │ header │ ││ └───────────┬────────────┘ ││ │ ││ ┌────────────┴───────────┐ ││ │ upstreams: │ ││ │ opencode.ai/zen/v1 │ ││ │ api.deepseek.com/v1 │ ││ └────────────────────────┘ │└───────────────────────────────────────────────────┘ │ │ /30 network │ ┌─────────┴─────────┐ │ Guest VM │ │ │ │ opencode / pi -> │ │ http://gateway │ │ :11434/v1 (Zen) │ │ :11436/v1 (DS) │ └───────────────────┘
For each VM and each enabled provider, srv binds an HTTP proxy on the VM's host/gateway IP address and the provider's configured port. The proxies:
- Only accept requests from that VM's guest IP
- Forward
/v1/...requests to the upstream API - Inject the host's API key into the
Authorizationheader (Bearer auth) - The real keys never leave the host
DeepSeek uses OpenAI-compatible Bearer auth exclusively. The Zen gateway additionally supports Anthropic (X-API-Key) and Google (X-Goog-Api-Key) auth styles based on request path.
31.3 Guest bootstrap
When any provider gateway is enabled, the guest srv-bootstrap.service writes /root/.config/opencode/opencode.json targeting the per-VM gateways:
{ "$schema": "https://opencode.ai/config.json", "provider": { "opencode": { "options": { "baseURL": "http://:11434/v1", "apiKey": "srv-provider-gateway" } }, "deepseek": { "options": { "baseURL": "http://:11436/v1", "apiKey": "srv-provider-gateway" } } }}
The apiKey is a local placeholder only so the CLIs keep the paid model catalogs visible — the real credentials still live only on the host and are injected by the proxies.
Bootstrap also writes Pi config under /root/.pi/agent/ so the preinstalled pi CLI uses both gateways by default:
{ "providers": { "opencode": { "baseUrl": "http://:11434/v1", "apiKey": "srv-provider-gateway" }, "deepseek": { "baseUrl": "http://:11436/v1", "apiKey": "srv-provider-gateway", "compat": { "supportsDeveloperRole": false, "supportsStore": false } } }}
When all gateways are disabled, bootstrap removes those managed default config files.
31.4 Configuration
| Variable | Default | Description |
|---|---|---|
SRV_ZEN_API_KEY |
(empty) | OpenCode Zen API key |
SRV_ZEN_BASE_URL |
https://opencode.ai/zen |
Upstream Zen API base URL |
SRV_ZEN_GATEWAY_PORT |
11434 |
TCP port for Zen gateway proxy |
SRV_DEEPSEEK_API_KEY |
(empty) | DeepSeek API key |
SRV_DEEPSEEK_BASE_URL |
https://api.deepseek.com |
Upstream DeepSeek API base URL |
SRV_DEEPSEEK_GATEWAY_PORT |
11436 |
TCP port for DeepSeek gateway proxy |
31.5 Using the gateways from the guest
The preinstalled opencode and pi CLIs work out of the box. For other agents or HTTP clients:
# Inside the VM — Zencurl http://$(ip route show default | awk '{print $3}'):11434/v1/models# Inside the VM — DeepSeekcurl http://$(ip route show default | awk '{print $3}'):11436/v1/models
31.6 Disabling gateways
Remove or leave the respective API key env var unset. After the next guest boot, the bootstrap service will remove the managed config files for disabled providers.
32. srv Cheatsheet
Quick reference for the srv control plane.
32.1 Commands (via SSH)
ssh srv -- [--json] [args]
Use --json with the non-streaming instance and backup commands when you need machine-readable output.
| Command | Description |
|---|---|
new <name> |
Create new VM with optional --cpus, --ram, --rootfs-size |
new <name> --image debian-13 |
Create with a registered image (default: arch) |
new <name> --pool <pool> --ram <size> |
Create a pooled VM with elastic memory; idle guest RAM may be reclaimed |
new <name> --integration <name> |
Create a VM and enable one or more existing integrations (admin only) |
list |
Show visible VMs (all for admins, own for regular users) |
top [--interval DURATION] |
Live per-VM CPU, memory, disk, and network view; press q to exit |
status |
Admin-only host capacity and allocation summary |
inspect <name> |
Show VM details and status |
logs <name> |
View serial or firecracker logs |
start <name> [--discard-state] |
Resume saved RAM if present; optionally discard it and cold boot |
stop <name> [--save-state | --cache-state] |
Graceful shutdown, save RAM and stop, or keep RAM only if the host cache has room |
restart <name> |
Restart VM |
fsck <name> |
Force-check and repair stopped VM rootfs |
delete <name> |
Remove VM |
resize <name> |
Resize stopped VM (CPU/RAM up or down, rootfs grow-only) |
backup create <name> |
Create an in-place backup for a stopped VM |
backup list <name> |
List stored backups for a VM |
backup delete <name> <backup-id> |
Permanently delete a stored backup |
restore <name> <backup-id> |
Restore a stopped VM from one of its backups |
Use fixed mode for databases, JVMs, caches, and other memory-sensitive services. Pooled mode is for workloads that tolerate elastic memory.
32.2 Integrations (admin only)
| Command | Description |
|---|---|
integration list |
List configured integrations |
integration add http <name> --target <url> ... |
Create an HTTP integration with host-managed auth or headers |
integration inspect <name> |
Show target, auth mode, headers, and timestamps |
integration enable <vm> <name> |
Enable an integration for a VM |
integration disable <vm> <name> |
Disable an integration for a VM |
integration list-enabled <vm> |
Show integrations enabled for a VM |
32.3 Quick Examples
# Create VMssh srv new demossh srv statusssh srv -- --json inspect demo# With sizingssh srv new demo --cpus 4 --ram 8G --rootfs-size 20G# Integrationsssh srv integration add http openai --target https://api.openai.com/v1 --bearer-env SRV_SECRET_OPENAI_PRODssh srv integration enable demo openaissh srv inspect demo# Resize (must be stopped)ssh srv stop demossh srv resize demo --cpus 4 --ram 8Gssh srv start demo# Force rootfs check (must be stopped)ssh srv stop demossh srv fsck demo && ssh srv start demo# Backup and restore (stop VM first for safety)ssh srv backup create demossh srv backup list demossh srv backup delete demo ssh srv restore demo # View logsssh srv logs demossh srv logs demo serialssh srv logs demo firecrackerssh srv logs -f demo serialssh srv logs -f demo firecracker# Live VM usagessh -t srv topssh -t srv top --interval 2s
32.4 Systemd Management
# Statussudo systemctl status srv srv-net-helper srv-vm-runner# Restartsudo systemctl stop srv srv-net-helper srv-vm-runnersleep 5sudo systemctl start srv-vm-runner srv-net-helper srv# View logssudo journalctl -u srv -fsudo journalctl -u srv-vm-runner -f
32.5 Smoke Test
sudo ./contrib/smoke/host-smoke.sh
32.6 Build Artifacts
# Binariesgo build ./cmd/srvgo build ./cmd/srv-net-helpergo build ./cmd/srv-vm-runner# Guest imagesudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.sh# Installsudo ./contrib/systemd/install.shsudoedit /etc/srv/srv.envsudo ./contrib/systemd/install.sh --enable-now
32.7 Key Env Variables
| Variable | Default | Description |
|---|---|---|
SRV_DATA_DIR |
/var/lib/srv |
btrfs subvolume root on the same filesystem as every base rootfs image; requires btrfs-progs and user_subvol_rm_allowed |
SRV_BASE_KERNEL |
- | Firecracker kernel path |
SRV_BASE_ROOTFS |
- | Base rootfs image on the same btrfs filesystem as SRV_DATA_DIR |
SRV_BASE_INITRD |
- | Optional initrd |
SRV_ALLOWED_USERS |
- | Comma-separated Tailscale allowlist |
SRV_ADMIN_USERS |
- | Cross-instance admin access |
SRV_GUEST_AUTH_TAGS |
- | Tags for guest auth keys |
TS_TAILNET |
- | Tailnet name |
SRV_FIRECRACKER_BIN |
/usr/bin/jailer |
Firecracker binary |
SRV_JAILER_BIN |
/usr/bin/jailer |
Jailer binary |
SRV_INTEGRATION_GATEWAY_PORT |
11435 |
Per-VM host-side HTTP integration gateway port |
SRV_SECRET_* |
- | Host-managed integration secret values referenced by name from the SSH API |
32.8 Backup & Restore
Stop every VM and Orb first. Follow the operations runbook for metadata and runner receipts: tar does not preserve subvolume boundaries or readonly properties, which must be restored before starting services. Prefer host snapshot bundles for btrfs backup and restore.
# Backupsudo systemctl stop srv srv-net-helper srv-vm-runnersudo tar -czf backup.tar.gz /etc/srv /var/lib/srv# Restoresudo ./contrib/systemd/install.sh# restore /etc/srv/srv.env and /var/lib/srvsudo systemctl daemon-reloadsudo systemctl enable --now srv-vm-runner srv-net-helper srvsudo ./contrib/smoke/host-smoke.sh
32.9 Debug Commands
# VM inspectionssh srv inspect # Recent logsssh srv logs serial ssh srv logs firecracker # System logsjournalctl -u srv-vm-runner | tail# Check cgroupscat /sys/fs/cgroup/firecracker-vms//cpu.max cat /sys/fs/cgroup/firecracker-vms//memory.max
32.10 Notes
- VM and Orb disks at:
SRV_DATA_DIR/instances/<name>/disk/rootfs.img, in a dedicateddisksubvolume - Legacy stopped instances migrate automatically on start with a durable journal; non-btrfs hosts require an offline storage migration
- VM backups live at:
SRV_DATA_DIR/backups/<name>/<backup-id>/ - Resize requires a stopped VM; CPU and RAM can go up or down within limits, but rootfs shrink is rejected
- Resize and fsck only work on stopped VMs
- Backup and restore only work on stopped VMs and only restore onto the original VM record, not a newly recreated VM with the same name
- Creators manage their own VMs; admins manage all VMs
- Integration commands are admin-only, and integration secrets are referenced by host env name rather than passed as raw SSH arguments
- Warm start/restart reuses tailscaled state
- Host reboot auto-restarts active VMs
33. Appendices
33.1 Command index
Command examples extracted from the docs. Each entry links back to the sections where it appears.
cat /sys/fs/cgroup/firecracker-vms/<name>/cpu.maxSeen in Isolated service, srv Cheatsheet, Troubleshootingcat /sys/fs/cgroup/firecracker-vms/<name>/memory.maxSeen in Isolated service, srv Cheatsheet, Troubleshootingcat /sys/fs/cgroup/firecracker-vms/<name>/memory.swap.maxSeen in Isolated service, Troubleshootingcat /sys/fs/cgroup/firecracker-vms/<name>/pids.maxSeen in Isolated service, Troubleshootingcat demo-backup.tar | ssh srv importSeen in Export and importcurl http://$(ip route show default | awk '{print $3}'):11434/v1/modelsSeen in Provider gatewayscurl http://$(ip route show default | awk '{print $3}'):11435/integrations/openai/modelsSeen in HTTP integrationscurl http://$(ip route show default | awk '{print $3}'):11435/integrations/vendor/pingSeen in HTTP integrationscurl http://$(ip route show default | awk '{print $3}'):11436/v1/modelsSeen in Provider gatewaysdf -hSeen in Troubleshootingdf -h /var/lib/srvSeen in Troubleshootingdocker compose up -dSeen in Isolated servicedocker run ...Seen in Isolated servicego build -o /tmp/srv-cold-store ./cmd/srv-cold-storeSeen in Testinggo build -o /tmp/srv-orb-dispatch ./cmd/srv-orb-dispatchSeen in Self-hosted Amp orbs on srvgo build -o /tmp/srv-vm-runner ./cmd/srv-vm-runnerSeen in Testinggo build -o srv-front ./cmd/srv-frontSeen in Multi-host frontendgo build ./cmd/srvSeen in Installation, srv Cheatsheetgo build ./cmd/srv-net-helperSeen in Installation, srv Cheatsheetgo build ./cmd/srv-vm-runnerSeen in Installation, srv Cheatsheetgo test -c -o /tmp/srv-service.test ./internal/serviceSeen in Testinggo test -run='^$' -fuzz='^FuzzSetupHandler$' -fuzztime=20s ./internal/nethelperSeen in Testinggo test ./...Seen in Testinggo test ./cmd/srv-orb-dispatch ./internal/store ./internal/service ./internal/provision ./internal/front ./internal/vmrunner ./internal/nethelper ./internal/orbguestSeen in Self-hosted Amp orbs on srvgo test ./internal/coldstore -run TestBtrfsTwoFilesystems -count=1 -vSeen in Operations runbookgo test ./internal/provision -run '^TestProvisionPolicyMatrix$' -count=1Seen in Testinggo test ./internal/service -run '^TestConcurrentCacheStopLifecycle$' -count=1Seen in Testinggo test ./internal/store -run '^TestLifecycleStateMachine$' -count=1Seen in Testinggo vet ./...Seen in TestingGORACE=atexit_sleep_ms=0 go test -race -count=1 -timeout=15m ./...Seen in Testingjournalctl -u srv-orb-bootstrap.serviceSeen in Self-hosted Amp orbs on srvjournalctl -u srv-vm-runner | tailSeen in srv Cheatsheetln -sf "$PWD/contrib/amp/plugins/srv-runner.ts" ~/.config/amp/plugins/srv-runner.tsSeen in Amp runners on srv, Sandboxed AI coding agentmake benchSeen in Testingmkdir -p ~/.config/amp/pluginsSeen in Amp runners on srv, Sandboxed AI coding agentOUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.shSeen in Build a custom guest image, Installationpacman -S nodejs npmSeen in Dev/test environmentpacman -S postgresqlSeen in Isolated servicepacman -Sy --noconfirm archlinux-keyringSeen in Build a custom guest image, Installationpacman -SyuSeen in Dev/test environmentpacman -Syu --noconfirm arch-install-scripts base-devel bc e2fsprogs rsync curl systemdSeen in Build a custom guest image, Installationpython3 - <<'PYTHON'Seen in Self-hosted Amp orbs on srvROOTFS_SIZE=20G sudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.shSeen in Build a custom guest imagessh -t srv topSeen in srv Cheatsheetssh -t srv top --interval 2sSeen in srv Cheatsheetssh backup-host "sudo btrfs receive /backup/srv/.incomplete-$ID"Seen in Host snapshot bundlesssh root@<vm-name>Seen in Amp runners on srvssh root@agent-1Seen in Sandboxed AI coding agentssh root@builderSeen in Isolated servicessh root@dbSeen in Isolated servicessh root@debug-vmSeen in Throwaway debug VMssh root@demoSeen in Walkthroughssh root@demo # install packages, configure servicesSeen in Backup and restoressh root@devSeen in Dev/test environmentssh srv -- --json inspect <name>Seen in Instance lifecyclessh srv -- --json inspect demoSeen in srv Cheatsheet, SSH command reference, Walkthroughssh srv -- --json inspect demo --host a > demo-before-delete.json &&Seen in SSH command referencessh srv -- --json listSeen in Multi-host frontend, SSH command reference, Walkthroughssh srv -- --json node listSeen in Multi-host frontendssh srv -- --json statusSeen in SSH command referencessh srv -- [--json] <command> [args]Seen in srv Cheatsheetssh srv <command> [args]Seen in SSH command referencessh srv backup create demoSeen in Backup and restore, srv Cheatsheet, Walkthroughssh srv backup create devSeen in Dev/test environmentssh srv backup create dev # backup 1: cleanSeen in Dev/test environmentssh srv backup create dev # backup 2: with toolchainSeen in Dev/test environmentssh srv backup delete demo <backup-id>Seen in Backup and restore, srv Cheatsheetssh srv backup list demoSeen in Backup and restore, srv Cheatsheet, Walkthroughssh srv backup list devSeen in Dev/test environmentssh srv cleanup-receipt "$(cat demo-delete-request.txt)" --host aSeen in SSH command referencessh srv cleanup-receipt --instance "$id" --host aSeen in SSH command referencessh srv delete "$name" --host a --expect "$request" "$id" "$created" "$backend" "$image"Seen in SSH command referencessh srv delete <name>Seen in Instance lifecyclessh srv delete a/demoSeen in Multi-host frontendssh srv delete agent-1Seen in Sandboxed AI coding agentssh srv delete dbSeen in Isolated servicessh srv delete debug-vmSeen in Throwaway debug VMssh srv delete demoSeen in Walkthroughssh srv delete demo --host aSeen in SSH command referencessh srv disk hydrate demo # restores without booting; must be stoppedSeen in Operations runbookssh srv disk offload demoSeen in Operations runbookssh srv disk purge demo # removes retained remote generation; local disk requiredSeen in Operations runbookssh srv disk status demoSeen in Operations runbookssh srv export demoSeen in Export and importssh srv export demo > demo-backup.tarSeen in Export and importssh srv fsck <name> && ssh srv start <name>Seen in Instance lifecyclessh srv fsck demo && ssh srv start demoSeen in srv Cheatsheetssh srv inspect <name>Seen in Instance lifecycle, srv Cheatsheet, Troubleshootingssh srv inspect agent-1Seen in Sandboxed AI coding agentssh srv inspect debug-vmSeen in Throwaway debug VMssh srv inspect demoSeen in HTTP integrations, Multi-host frontend, srv Cheatsheet, Walkthroughssh srv integration add http openai --target https://api.openai.com/v1 --bearer-env SRV_SECRET_OPENAI_PRODSeen in HTTP integrations, srv Cheatsheetssh srv integration add http vendor --target https://vendor.example/api --header-env X-API-Key:SRV_SECRET_VENDOR_API_KEYSeen in HTTP integrationsssh srv integration disable demo openai --host aSeen in Multi-host frontendssh srv integration enable demo openaiSeen in HTTP integrations, srv Cheatsheetssh srv integration enable demo openai --host bSeen in Multi-host frontendssh srv integration enable demo vendorSeen in HTTP integrationsssh srv listSeen in Instance lifecycle, Multi-host frontend, Walkthroughssh srv list # ordinary VMs onlySeen in Self-hosted Amp orbs on srvssh srv list --all # both, with their kindSeen in Self-hosted Amp orbs on srvssh srv logs -f <name> firecrackerSeen in Instance lifecyclessh srv logs -f <name> serialSeen in Instance lifecyclessh srv logs -f a/demo serialSeen in Multi-host frontendssh srv logs -f debug-vm serialSeen in Throwaway debug VMssh srv logs -f demo firecrackerSeen in srv Cheatsheet, View logsssh srv logs -f demo serialSeen in srv Cheatsheet, View logs, Walkthroughssh srv logs <name>Seen in Instance lifecyclessh srv logs <name> firecrackerSeen in Instance lifecycle, srv Cheatsheet, Troubleshootingssh srv logs <name> serialSeen in Instance lifecycle, srv Cheatsheet, Troubleshootingssh srv logs demoSeen in srv Cheatsheet, View logs, Walkthroughssh srv logs demo firecrackerSeen in srv Cheatsheet, View logs, Walkthroughssh srv logs demo serialSeen in srv Cheatsheet, View logs, Walkthroughssh srv migrate a/demo --to bSeen in Multi-host frontendssh srv migrate a/demo --to b --fixed-memorySeen in Multi-host frontendssh srv migrate a/demo --to b --pool sharedSeen in Multi-host frontendssh srv new <name>Seen in Instance lifecyclessh srv new <name> --cpus <n> --ram <size> --rootfs-size <size>Seen in Instance lifecyclessh srv new agent-1 --cpus 4 --ram 8G --rootfs-size 30GSeen in Sandboxed AI coding agentssh srv new agent-2 --cpus 2 --ram 4GSeen in Sandboxed AI coding agentssh srv new agent-3 --cpus 2 --ram 4GSeen in Sandboxed AI coding agentssh srv new builder --cpus 4 --ram 8G --rootfs-size 40GSeen in Isolated servicessh srv new db --cpus 2 --ram 4G --rootfs-size 20GSeen in Isolated servicessh srv new debian-vm --image debian-13Seen in Instance lifecyclessh srv new debug-vmSeen in Throwaway debug VMssh srv new debug-vm --cpus 2 --ram 4G --rootfs-size 30GSeen in Throwaway debug VMssh srv new demoSeen in Backup and restore, Introduction to srv, srv Cheatsheet, Walkthroughssh srv new demo --cpus 4 --ram 8G --rootfs-size 20GSeen in srv Cheatsheet, Walkthroughssh srv new demo --ram 8G --rootfs-size 20GSeen in Multi-host frontendssh srv new dev --cpus 4 --ram 8G --rootfs-size 30GSeen in Dev/test environmentssh srv new other --host bSeen in Multi-host frontendssh srv node listSeen in Multi-host frontendssh srv orb list # Orbs onlySeen in Self-hosted Amp orbs on srvssh srv orb new demo --image amp-orbSeen in Self-hosted Amp orbs on srvssh srv orb new demo --image amp-orb-desktopSeen in Self-hosted Amp orbs on srvssh srv pool list --host aSeen in Multi-host frontendssh srv resize <name> --rootfs-size 20GSeen in Troubleshootingssh srv resize demo --cpus 4 --ram 8GSeen in srv Cheatsheetssh srv resize demo --cpus 4 --ram 8G --rootfs-size 20GSeen in Resize a VM, Walkthroughssh srv resize demo --fixed-memorySeen in Resize a VMssh srv resize demo --pool sharedSeen in Resize a VMssh srv resize demo --ram 16GSeen in Resize a VMssh srv restart <name>Seen in Instance lifecyclessh srv restart demoSeen in Walkthroughssh srv restore demo <backup-id>Seen in Backup and restore, srv Cheatsheet, Walkthroughssh srv restore dev <backup-id>Seen in Dev/test environmentssh srv snapshot createSeen in Operations runbookssh srv start <name>Seen in Instance lifecycle, Troubleshootingssh srv start <name> --discard-stateSeen in Instance lifecyclessh srv start demoSeen in Backup and restore, Resize a VM, srv Cheatsheet, Walkthroughssh srv start demo # restores first if coldSeen in Operations runbookssh srv start devSeen in Dev/test environmentssh srv statusSeen in Instance lifecycle, Multi-host frontend, srv Cheatsheetssh srv stop <name>Seen in Instance lifecycle, Troubleshootingssh srv stop <name> --cache-stateSeen in Instance lifecyclessh srv stop <name> --save-stateSeen in Instance lifecyclessh srv stop a/demoSeen in Multi-host frontendssh srv stop demoSeen in Backup and restore, Export and import, Resize a VM, srv Cheatsheet, Walkthroughssh srv stop devSeen in Dev/test environmentssh srv-a -- --json inspect demo > demo-before-delete.json &&Seen in SSH command referencessh srv-a -- --json inspect ORB_NAMESeen in Self-hosted Amp orbs on srvssh srv-a -- --json migration status demoSeen in Multi-host frontendssh srv-a cleanup-receipt "$(cat demo-delete-request.txt)"Seen in SSH command referencessh srv-a cleanup-receipt --instance "$(jq -er '.instance.id' demo-before-delete.json)"Seen in SSH command referencessh srv-a delete "$name" --expect "$request" "$id" "$created" "$backend" "$image"Seen in SSH command referencessh srv-a delete demoSeen in SSH command referencessh srv-a delete dev-orbSeen in SSH command referencessh srv-a delete ORB_NAMESeen in Self-hosted Amp orbs on srvssh srv-a export demo | ssh srv-b importSeen in Export and import, Operations runbook, Walkthroughssh srv-a migration abort demo TOKEN --confirm-destination-destroyedSeen in Multi-host frontendssh srv-a orb listSeen in Self-hosted Amp orbs on srvssh srv-b -- --json migration receipt demoSeen in Multi-host frontendssh srv-b inspect demoSeen in Multi-host frontendssh srv-b start demoSeen in Export and importssh srv-front -- --json orb new NEW_ORB_NAME --image amp-orb --template TEMPLATE_ID --host aSeen in Self-hosted Amp orbs on srvssh srv-front -- --json project-template create ORB_VM_NAME TEMPLATE_ID --host aSeen in Self-hosted Amp orbs on srvsudo -u srv-orbs env SRV_ORB_ENDPOINT=srv SRV_ORB_STATE_DIR=/var/lib/srv-orbs/dispatch /usr/local/bin/srv-orb-dispatch initSeen in Self-hosted Amp orbs on srvsudo ./contrib/smoke/host-smoke.shSeen in Installation, Operations runbook, Running as a daemon, srv Cheatsheet, Troubleshootingsudo ./contrib/systemd/install.shSeen in Installation, Operations runbook, srv Cheatsheetsudo ./contrib/systemd/install.sh --enable-nowSeen in Installation, srv Cheatsheetsudo btrfs send "$BUNDLE/$component" |Seen in Host snapshot bundlessudo btrfs subvolume show /var/lib/srvSeen in Manuelle DRBD-Übernahme mit srvsudo drbdadm primary srvSeen in Manuelle DRBD-Übernahme mit srvsudo drbdadm status srvSeen in Manuelle DRBD-Übernahme mit srvsudo install -D -m 0644 contrib/systemd/drbd-mount.conf "/etc/systemd/system/$unit.d/drbd-mount.conf"Seen in Manuelle DRBD-Übernahme mit srvsudo install -m 0644 contrib/amp/orbs/srv-orb-snapshot-gc.{service,timer} /etc/systemd/system/Seen in Self-hosted Amp orbs on srvsudo install -m 0644 contrib/amp/orbs/srv-orbs.service /etc/systemd/system/Seen in Self-hosted Amp orbs on srvsudo install -m 0644 contrib/systemd/srv-front.service /etc/systemd/system/Seen in Multi-host frontendsudo install -m 0755 /tmp/srv-orb-dispatch /usr/local/bin/srv-orb-dispatchSeen in Self-hosted Amp orbs on srvsudo install -m 0755 srv-front /usr/local/bin/srv-frontSeen in Multi-host frontendsudo iptables -L FORWARD -nSeen in Troubleshootingsudo iptables -t nat -L -nSeen in Troubleshootingsudo journalctl -u srv -b --no-pager | grep 'ssh host key'Seen in Multi-host frontendsudo journalctl -u srv -fSeen in Running as a daemon, srv Cheatsheet, View logssudo journalctl -u srv-frontSeen in Multi-host frontendsudo journalctl -u srv-net-helper -fSeen in View logssudo journalctl -u srv-orbs -fSeen in Self-hosted Amp orbs on srvsudo journalctl -u srv-vm-runner -fSeen in Running as a daemon, srv Cheatsheet, Troubleshooting, View logssudo KERNEL_JOBS=2 OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.shSeen in Build a custom guest imagesudo KERNEL_VERSION=6.1.167 OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.shSeen in Build a custom guest imagesudo mount /var/lib/srvSeen in Manuelle DRBD-Übernahme mit srvsudo OUTPUT_DIR=/var/lib/srv/images/arch-base ./images/arch-base/build.shSeen in Build a custom guest image, Installation, srv Cheatsheetsudo podman run --rm --privileged --network host -v "$PWD":/work -v /var/lib/srv/images/arch-base:/var/lib/srv/images/arch-base -w /work docker.io/library/archlinux:latest bash -lc 'Seen in Build a custom guest image, Installationsudo python3 contrib/amp/orbs/probe_guest_systemd.py --runtime-layer /tmp/amp-runtime.tar.gzSeen in Self-hosted Amp orbs on srvsudo python3 test/firecracker_orb_ram_cache.py --runner /tmp/srv-vm-runner --cold-store /tmp/srv-cold-store --firecracker /path/to/firecracker --jailer /path/to/jailer --kernel /path/to/vmlinux --rootfs /path/to/rootfs.img --service-recovery /tmp/srv-service.testSeen in Testingsudo sysctl --systemSeen in Installation, Networking overview, Operations runbooksudo sysctl -w net.ipv4.ip_forward=1Seen in Troubleshootingsudo systemctl daemon-reloadSeen in Manuelle DRBD-Übernahme mit srv, Multi-host frontend, Operations runbook, Self-hosted Amp orbs on srv, srv Cheatsheetsudo systemctl disable srv.service srv-vm-runner.service srv-net-helper.serviceSeen in Manuelle DRBD-Übernahme mit srvsudo systemctl enable --now srv-frontSeen in Multi-host frontendsudo systemctl enable --now srv-orb-snapshot-gc.timerSeen in Self-hosted Amp orbs on srvsudo systemctl enable --now srv-orbsSeen in Self-hosted Amp orbs on srvsudo systemctl enable --now srv-vm-runner srv-net-helper srvSeen in Operations runbook, srv Cheatsheetsudo systemctl start srv-vm-runner srv-net-helper srvSeen in Operations runbook, Running as a daemon, srv Cheatsheetsudo systemctl start srv.service &&Seen in Manuelle DRBD-Übernahme mit srvsudo systemctl status srv srv-net-helper srv-vm-runnerSeen in Running as a daemon, srv Cheatsheetsudo systemctl status srv-net-helperSeen in Troubleshootingsudo systemctl stop srv srv-net-helper srv-vm-runnerSeen in Operations runbook, Running as a daemon, srv Cheatsheetsudo tar --xattrs --acls --numeric-owner --ignore-failed-read -C / -czf /var/tmp/srv-backup-$(date -u +%Y%m%dT%H%M%SZ).tar.gz etc/srv var/lib/srv etc/systemd/system/srv.service.d etc/systemd/system/srv-net-helper.service.d etc/systemd/system/srv-vm-runner.service.d etc/systemd/system.controlSeen in Operations runbooksudo tar -czf backup.tar.gz /etc/srv /var/lib/srvSeen in srv Cheatsheetsudo tee /etc/sysctl.d/90-srv-ip-forward.conf >/dev/null <<'EOF'Seen in Installation, Networking overview, Operations runbooksudoedit /etc/srv/srv.envSeen in Installation, srv Cheatsheetsysctl net.ipv4.ip_forwardSeen in Troubleshootingsystemctl is-active srv-net-helper.serviceSeen in Manuelle DRBD-Übernahme mit srvsystemctl is-active srv-vm-runner.service &&Seen in Manuelle DRBD-Übernahme mit srvsystemctl is-active srv.service &&Seen in Manuelle DRBD-Übernahme mit srvsystemctl status srv-orb-bootstrap.serviceSeen in Self-hosted Amp orbs on srvsystemctl status srv-orb-guest.serviceSeen in Self-hosted Amp orbs on srv
33.2 Environment variables
Environment variables and build-time overrides mentioned across the handbook, indexed back to the sections that reference them.
AMP_ORB_PROVIDER_TOKENSeen in Self-hosted Amp orbs on srvAMP_ORB_WORKLOAD_SLICESeen in Self-hosted Amp orbs on srvAMP_RUNTIME_LAYERSeen in Self-hosted Amp orbs on srvAMP_URLSeen in Self-hosted Amp orbs on srvARTIFACT_ROOTSeen in TroubleshootingBACKEND_IDSeen in Self-hosted Amp orbs on srv, SSH command referenceCOLDSTORE_TEST_REMOTESeen in Operations runbookCOLDSTORE_TEST_SOURCESeen in Operations runbookCREATED_ATSeen in Self-hosted Amp orbs on srv, SSH command referenceENV_PATHSeen in Running as a daemon, TroubleshootingGUEST_SSH_READY_TIMEOUTSeen in TroubleshootingHEGEL_STATISTICSSeen in TestingHTTP_PROXYSeen in Networking overviewHTTPS_PROXYSeen in Networking overviewINSTANCE_NAMESeen in Running as a daemon, TroubleshootingKEEP_FAILEDSeen in Running as a daemon, TroubleshootingKERNEL_JOBSSeen in Build a custom guest imageKERNEL_VERSIONSeen in Build a custom guest image, TestingLAYER_URLSeen in Self-hosted Amp orbs on srvLD_LIBRARY_PATHSeen in Self-hosted Amp orbs on srvNEW_ORB_NAMESeen in Self-hosted Amp orbs on srvNO_PROXYSeen in Amp runners on srv, Networking overview, Sandboxed AI coding agent, Self-hosted Amp orbs on srvORB_IDSeen in Self-hosted Amp orbs on srvORB_IMAGESeen in Self-hosted Amp orbs on srvORB_NAMESeen in Self-hosted Amp orbs on srvORB_SNAPSHOT_IDSeen in Self-hosted Amp orbs on srvORB_TYPESeen in Self-hosted Amp orbs on srvORB_VM_NAMESeen in Self-hosted Amp orbs on srvOUTPUT_DIRSeen in Build a custom guest image, Installation, srv CheatsheetREADY_TIMEOUT_SECONDSSeen in Running as a daemon, TroubleshootingREPLACE_WITH_HOST_A_PUBLIC_KEYSeen in Multi-host frontendREPLACE_WITH_HOST_B_PUBLIC_KEYSeen in Multi-host frontendREQUEST_IDSeen in Self-hosted Amp orbs on srv, SSH command referenceROOTFS_SIZESeen in Build a custom guest imageSMOKE_SSH_HOSTSeen in Running as a daemon, TroubleshootingSNAPSHOT_IDSeen in Self-hosted Amp orbs on srvSRV_ADMIN_USERSSeen in Authorization, Configuration reference, Multi-host frontend, srv CheatsheetSRV_ADVERTISE_TAGSSeen in Multi-host frontendSRV_ALLOWED_USERSSeen in Authorization, Configuration reference, Multi-host frontend, Self-hosted Amp orbs on srv, srv CheatsheetSRV_AMP_CONNECT_GATEWAY_PORTSeen in Configuration reference, Networking overviewSRV_AMP_ORBSeen in Self-hosted Amp orbs on srvSRV_BASE_INITRDSeen in Configuration reference, Export and import, Operations runbook, srv CheatsheetSRV_BASE_KERNELSeen in Configuration reference, Export and import, Installation, Operations runbook, srv CheatsheetSRV_BASE_ROOTFSSeen in Build a custom guest image, Configuration reference, Installation, Operations runbook, srv CheatsheetSRV_COLD_STORAGE_AFTER_STOPSeen in Configuration reference, Operations runbook, Self-hosted Amp orbs on srvSRV_COLD_STORAGE_HOSTSeen in Configuration reference, Operations runbookSRV_COLD_STORAGE_KEYSeen in Configuration reference, Operations runbookSRV_COLD_STORAGE_KNOWN_HOSTSSeen in Configuration reference, Operations runbookSRV_COLD_STORAGE_RETENTIONSeen in Configuration reference, Operations runbook, Self-hosted Amp orbs on srvSRV_DATA_DIRSeen in Architecture, Backup and restore, Configuration reference, Host snapshot bundles, Installation, Introduction to srv, Manuelle DRBD-Übernahme mit srv, Multi-host frontend, Networking overview, Operations runbook, srv Cheatsheet, Troubleshooting, View logsSRV_DEEPSEEK_API_KEYSeen in Architecture, Configuration reference, Provider gateways, Sandboxed AI coding agentSRV_DEEPSEEK_BASE_URLSeen in Configuration reference, Provider gatewaysSRV_DEEPSEEK_GATEWAY_PORTSeen in Architecture, Configuration reference, Networking overview, Provider gatewaysSRV_DRBD_DISPOSABLE_PILOTSeen in DRBD real-system pilotSRV_EXTERNAL_DENY_CIDRSSeen in Configuration reference, Networking overviewSRV_EXTERNAL_UPLINKSSeen in Configuration reference, Networking overview, SSH command referenceSRV_EXTRA_KERNEL_ARGSSeen in Configuration referenceSRV_FIRECRACKER_BINSeen in Configuration reference, DRBD real-system pilot, Operations runbook, Running as a daemon, srv CheatsheetSRV_GUEST_AUTH_EXPIRYSeen in Configuration referenceSRV_GUEST_AUTH_TAGSSeen in Configuration reference, Installation, srv Cheatsheet, TroubleshootingSRV_GUEST_READY_TIMEOUTSeen in Configuration reference, DRBD real-system pilot, TroubleshootingSRV_GUEST_TAILSCALE_CONTROL_URLSeen in Configuration referenceSRV_GUEST_USER_AUTH_TAGSSeen in Authorization, Configuration referenceSRV_HOSTNAMESeen in Architecture, Configuration reference, Multi-host frontendSRV_IMAGES_DIRSeen in Configuration reference, Operations runbookSRV_IMAGES_FILESeen in Configuration reference, Self-hosted Amp orbs on srvSRV_INTEGRATION_GATEWAY_PORTSeen in Configuration reference, HTTP integrations, Networking overview, srv CheatsheetSRV_JAILER_BASE_DIRSeen in Configuration reference, Operations runbook, Self-hosted Amp orbs on srv, TroubleshootingSRV_JAILER_BINSeen in Configuration reference, Operations runbook, Running as a daemon, srv CheatsheetSRV_LISTEN_ADDRSeen in Architecture, Configuration referenceSRV_LOG_LEVELSeen in Configuration referenceSRV_MIGRATION_STORESeen in Multi-host frontendSRV_NET_HELPER_SOCKETSeen in Configuration referenceSRV_ORB_CPUSSeen in Self-hosted Amp orbs on srvSRV_ORB_DISKSeen in Self-hosted Amp orbs on srvSRV_ORB_ENDPOINTSeen in Self-hosted Amp orbs on srvSRV_ORB_HOSTSeen in Self-hosted Amp orbs on srvSRV_ORB_IMAGESeen in Self-hosted Amp orbs on srvSRV_ORB_POOLSeen in Self-hosted Amp orbs on srvSRV_ORB_PROXY_BYPASSSeen in Self-hosted Amp orbs on srvSRV_ORB_RAMSeen in Self-hosted Amp orbs on srvSRV_ORB_RAM_CACHESeen in Instance lifecycle, Self-hosted Amp orbs on srvSRV_ORB_SNAPSHOT_GC_OLDER_THANSeen in Self-hosted Amp orbs on srvSRV_ORB_STATE_DIRSeen in Self-hosted Amp orbs on srvSRV_ORB_TYPES_FILESeen in Self-hosted Amp orbs on srvSRV_OUTBOUND_IFACESeen in Configuration reference, Networking overviewSRV_PROVIDER_NODESSeen in Authorization, Configuration reference, Self-hosted Amp orbs on srvSRV_RAM_CACHE_SIZESeen in Configuration reference, Instance lifecycle, Self-hosted Amp orbs on srvSRV_SECRET_Seen in Configuration reference, HTTP integrations, srv CheatsheetSRV_SECRET_BARSeen in HTTP integrations, SSH command referenceSRV_SECRET_FOOSeen in HTTP integrations, SSH command referenceSRV_SECRET_OPENAI_PRODSeen in Configuration reference, HTTP integrations, srv CheatsheetSRV_SECRET_VENDOR_API_KEYSeen in HTTP integrationsSRV_TAILSCALE_PORTSeen in Configuration referenceSRV_TRUSTED_FRONTENDSSeen in Authorization, Configuration reference, Multi-host frontendSRV_VM_DNSSeen in Configuration reference, Networking overviewSRV_VM_MEMORY_MIBSeen in Configuration referenceSRV_VM_NETWORK_CIDRSeen in Configuration reference, Networking overviewSRV_VM_PIDS_MAXSeen in Configuration reference, Isolated service, Sandboxed AI coding agentSRV_VM_RUNNER_SOCKETSeen in Configuration reference, Operations runbookSRV_VM_VCPUSSeen in Configuration referenceSRV_ZEN_API_KEYSeen in Architecture, Configuration reference, Provider gateways, Sandboxed AI coding agentSRV_ZEN_BASE_URLSeen in Configuration reference, Provider gatewaysSRV_ZEN_GATEWAY_PORTSeen in Architecture, Configuration reference, Networking overview, Provider gatewaysSSH_ORIGINAL_COMMANDSeen in Operations runbookTEMPLATE_IDSeen in Self-hosted Amp orbs on srvTS_API_BASE_URLSeen in Configuration referenceTS_AUTHKEYSeen in Configuration reference, Installation, Multi-host frontendTS_CLIENT_IDSeen in Configuration reference, Installation, Multi-host frontendTS_CLIENT_SECRETSeen in Configuration reference, Installation, Multi-host frontendTS_CONTROL_URLSeen in Configuration reference, Multi-host frontendTS_TAILNETSeen in Configuration reference, Installation, srv CheatsheetYOUR_PROVIDER_NAMESeen in Self-hosted Amp orbs on srv