CLI Contracts
15 minute read
Every barn command follows the same output, prompt, and exit-code rules, so a script can handle all of them the same way. This page defines those rules; per-command syntax and flags are in the Command Reference, and native Mac VM contracts in Mac Reference.
Each command page lists its short aliases (barn st is barn status); the network group also answers to n and net.
Output modes
Results go to stdout and everything else to stderr, so redirecting stdout captures only the result.
| Mode | stdout | stderr |
|---|---|---|
| Text (default) | Results and follow-up hints (connect:, retry:, next:) | Live progress, prompts, error: lines |
--json or --yaml | One JSON or YAML document: the command’s report or a failure object | Progress and diagnostics |
-v, --verbose | Unchanged | Adds bounded diagnostic logs |
In text mode, an operation that runs for a second or longer on a terminal redraws one live table on stderr (NAME ADDRESS STATE MESSAGE, ITEM STATE MESSAGE, or IMAGE STATE MESSAGE) above a completion line ending in [DONE], [FAILED], or [CANCELLED]. When stdout and stderr are both terminals and --verbose is off, the finished table stays in place and stdout adds only the follow-up hints.
Two cases differ: logs --follow streams NDJSON with --json or a YAML document stream with --yaml, and structured interactive ssh sends the session to stderr and only its final report to stdout.
--json and --yaml are long-form only and mutually exclusive; BARN_OUTPUT sets the default. Presentation flags may come before or after the command but must precede the -- that starts a remote command. barn --json with no command returns suggested next commands in actions[].
Exit codes
Check the exit code first, then parse the output.
| Code | error | Meaning |
|---|---|---|
0 | Success (including ready guests with non-fatal warnings[] or repairs[]) | |
1 | runtime | Operation executed and failed (external tool, download, or guest failure) |
2 | usage | Invalid CLI syntax, missing inventory file, or invalid configuration/image selector |
3 | capability | Host lacks a required dependency, active Barn network, or privilege |
4 | conflict | Operation conflicts with current deployment state or another active barn process |
5 | partial | Node-level batch failure; inspect failures[] (successful peer nodes remain intact) |
6 | resource | Host IP address, port, subnet, or disk path is already in use |
7 | integrity | Digest, catalog signature or signed revision, instance identity, or file ownership verification failed |
130 | cancelled | Interrupted by SIGINT/SIGTERM or interactive confirmation declined |
sshandexecreturn the remote command’s exit code verbatim, so text output, JSONexit_code, and the process status agree.255can mean either an OpenSSH transport failure or a remote command that exited255.- Deployment lock: When another
barnprocess holds the deployment, mutating commands wait up to 10 minutes while naming the holder, then exit4withreason: "deployment_busy". Read-only and access commands (status,ssh,exec,ssh-config,hosts) do not wait;statusshows the last committed state and names the active operation innote. - Catalog trust: A missing or invalid catalog signature fails with
reason: "catalog_signature"; a catalog that reuses an accepted or embedded revision number with different bytes fails withreason: "catalog_equivocation". Permission and I/O errors while reading a cached signature are runtime failures (exit1).
Structured failures
With --json or --yaml, commands that have their own report schema — doctor, network, provision, lifecycle commands, and ssh/exec — write that report even when they fail; exec, for example, returns success, exit_code, stdout, and stderr. A command that fails before it has a report writes one failure object instead:
| Field | Present | Meaning |
|---|---|---|
error | Always | Error class from the exit code table |
message | Always | Human-readable summary |
reason | When known | Stable snake_case cause for automation |
next | When known | Suggested next command |
operation_id | When assigned | Correlates with barn logs --source events |
command | An external program failed | name, argv, exit_status, signal, timed_out, stderr |
failures, rolled_back | Exit 5 from a lifecycle batch | Failed nodes and rolled-back preparations, as in Lifecycle results |
Common reason values on Linux commands:
reason | error | Cause and usual next step |
|---|---|---|
no_inventory | usage | No inventory in the current directory: barn init, or pass -f |
unknown_node | usage | A selector is not a node name in the inventory or deployment |
unknown_image | usage | The image selector is not in the active catalog |
qemu_missing | capability | QEMU is missing or unusable; next names the fix |
network_absent | capability | The Barn network is not installed: barn setup |
sudo_unavailable | capability | sudo failed, or needs a password while stdin is not a terminal |
no_deployment | conflict | BARN_HOME holds no applied deployment: barn up |
node_not_running | conflict | The node is stopped: barn start <node> |
resize_required | conflict | Drift that barn resize applies |
recreate_required | conflict | Drift that needs barn plan, then barn recreate <node> |
nodes_removed | conflict | The inventory omits existing nodes; see Lifecycle results |
deployment_changed | conflict | Applied state changed during recreate preflight; review and retry |
deployment_busy | conflict | Another command held the lock for 10 minutes |
interrupted_transition | conflict | A node is still mid-transition after an interrupted command; run the next command |
hosts_name_taken | conflict | /etc/hosts maps a Barn name outside the Barn-owned block |
disk_full | resource | The host disk ran out of space |
image_integrity | integrity | A cached or downloaded image failed verification |
Errors in the command line itself, such as an unknown flag or a command group without a subcommand (barn image), exit 2 with error: "usage".
In text mode, a failure prints error: <message> on stderr, then the last stderr lines of any failed external program and a next: command when one is known. When a remote command under ssh or exec fails, only its own output appears, without an error: line. The design rationale is in CLI contracts.
Prompts and scripts
Commands that change the host or delete data ask for confirmation when stdin is a terminal, and never wait for input in a script:
| Command | stdin is a terminal | stdin is not a terminal |
|---|---|---|
recreate, destroy | Lists the nodes to replace or remove and asks you to type the command name; anything else cancels with exit 130. --yes or --force skips the prompt | Exit 2 unless --yes or --force is given (there is no -y) |
setup | Shows the plan and asks once | Requires --yes, else exit 2; --dry-run previews and cannot be combined with --yes |
network, hosts install/uninstall | Shows the privileged plan and asks (install defaults to yes, uninstall to no); with --json/--yaml it only previews | Prints the plan and exits 0 without applying; pass --yes, or check applied in the report |
up, start, restart, reload with a host dependency or the network missing | Shows the host-preparation plan and asks once, as setup does; an interactive up with neither an inventory nor a deployment also generates meta | Reports what is missing; run barn setup --yes first |
Privileged steps run through sudo, which may still ask for your password; when it needs one and stdin is not a terminal, the command fails with sudo_unavailable. On Linux, network uninstall keeps the global networkd unit state when other host links exist or exclusive Barn use cannot be established: the plan reports preserve_networkd, and the applied report explains the decision in checks.networkd.
barn purge never asks unless you pass --ask, which shows the nodes and deletion scope and accepts y/yes; n/no, an empty line, or EOF cancels with exit 130. It accepts no --yes, -y, or --force. With no deployment, purge and whole-deployment destroy succeed cleanly, and purge still removes retained persistent disks whose Barn ownership metadata is intact; unverifiable retained directories block deletion. If deployment state is missing, destroy --force --delete-persistent and destroy --force --purge direct you to barn purge.
Flag conventions
- On Linux commands,
-fmeans--file(exceptbarn logs -f, which is--follow),-nmeans--no-wait(barn mac logs -nsets the line count), and-dmeans--dry-run. - Safety and repository flags are long-form only:
--ask,--mirror,--force,--rollback,--remove,--allow-downgrade,--sudo,--delete-persistent,--purge. -yexists only where a command’s option table lists it; ondestroyandrecreate,--yesis the same as--force.- Path arguments such as
-f,--script, a local--repo,image importsources, andreporoots accept relative paths,~/, and symlinks. - Specification flags (
-I,-A,-C,-M,-S,-D) and their environment variables follow Specification overrides.
Lifecycle results
Without node arguments, lifecycle commands act on every managed node; ssh, exec, and per-node logs default to the prepared control node, or the first prepared node if the control node is not ready. Selectors are resolved node names such as meta, not IP addresses, group names, or vm_alias entries. Which inventory a command reads is defined in Discovery.
Lifecycle commands (up, start, stop, restart, reload, resize, recreate, status, destroy, purge) return one report:
| Field | Contents |
|---|---|
nodes[] | Per node: name, address, state (such as running or stopped), ready, image, cpus, memory_bytes, root_disk_bytes, runtime, guest_arch, accelerator, ssh_host, ssh_port, pid, error |
nodes[].warnings[] | Non-fatal guest problems, each with stage and detail |
nodes[].repairs[] | Recovery actions Barn completed, such as resetting a corrupted data disk |
warnings[] | Deployment-level warnings with code (ssh_config, time_sync, guest_metadata, event_log), message, detail, next |
failures[] | Failed nodes with node, stage, error, and optional reason |
rolled_back[] | Nodes whose uncommitted preparation files --rollback removed |
resources[] | Per node: base_cpu, base_memory_bytes, scale, root_disk_bytes, effective cpus and memory_bytes, and each value’s sources |
operation_id, spec_hash, note, ssh_config | Event-log correlation, applied specification hash, concurrent-operation note, SSH fragment result |
What each command changes is in Linux Lifecycle, and which change needs which command in Drift. When drift needs a destructive change, up and reload exit 4 (conflict) and point to barn plan and then barn recreate <node> or barn destroy <node>. A whole-deployment recreate refuses an inventory that omits an existing node before any VM stops (reason: "nodes_removed", exit 4): remove the node with barn destroy <node> or add it back. Barn checks the scope again under the destruction lock; if applied state changed meanwhile, recreate exits with reason: "deployment_changed".
Destroying the control node makes the first remaining node the control node. Point admin_ip at it and run barn up to install its control SSH access (--no-wait defers this); until then, an inventory that still names the deleted node as control is role drift, which up refuses. To bring the old node back, add it as a regular node. Barn refuses, before deleting anything, to destroy the control node when the successor has an unfinished prepare record that cannot be completed, and names the successor.
Planning
barn plan is read-only and exits 0 even when its action is resize, recreate, or blocked-removal. Scripts should read action, the create, resize, recreate, start, and missing arrays, and the optional blocked explanation. Plans never download images; catalog images need only local metadata, while local-* images are also checked with qemu-img.
Readiness
Barn reads /var/lib/barn/ready.json over management SSH. A Linux guest is ready when its node name, generation and spec hash match the expected values. During startup on up, start, restart, reload, and recreate, Barn also corrects guest clocks more than 2 seconds off the host, reporting a failure as a time_sync warning. Non-fatal problems go to nodes[].warnings and completed recovery actions to nodes[].repairs; the command still exits 0. Re-running barn up retries unfinished guest setup on running VMs without restarting them, and gives existing guests the current recovery helper.
--no-wait returns once QEMU is running and defers SSH readiness, clock correction, data-disk recovery, and guest /etc/hosts updates to the next barn up. Which disk problems Barn repairs and which it only reports is described in Storage.
Node failures
When some nodes fail in a batch, Barn keeps the nodes that succeeded, exits 5, and summarizes each failure as N of M node(s) failed: <node> (<stage>: <error>); .... Stages include prepare, start, readiness, bootstrap, guest-setup, stop, and status. For readiness or bootstrap failures, read barn logs <node> and see A node did not become ready.
Status
barn status reads recorded state plus live QEMU process identity: running means the process is alive, not that guest SSH answers. It flags TCG emulation, and on Apple Silicon appends mac: <names>; barn mac ls when Mac VMs exist. --verbose adds forwarded SSH ports, architecture, accelerator, and QEMU PID. A degraded node, including an online resize interrupted after hot-plugging (stage: "resize", reason: "resize_incomplete"), still lists its healthy peers, fills failures[], and exits 5.
SSH configuration
up and recreate rewrite Barn’s host SSH fragment (~/.ssh/barn_config), guest /etc/hosts, and control-node SSH entries; start and restart refresh SSH aliases; per-node destroy removes that node’s entry; whole-deployment destroy removes the fragment. If ~/.ssh/config cannot be updated, or is a symlink or hard link (which Barn never edits), Barn still writes ~/.ssh/barn_config, prints the Include line to add yourself, records an ssh_config warning, and exits 0; barn ssh keeps working. On the control node, Barn-managed entries accept replacement host keys without writing known_hosts, so recreated nodes stay reachable, and your own SSH entries are kept.
Lifecycle concurrency
up, start, stop, restart, reload, recreate, destroy, and purge work on up to max(1, logical CPUs - 2) nodes at once (1.2.0+; 1.1.0 used at most four workers). --parallel/-p changes that for one invocation:
The limit applies to disk preparation, startup, and shutdown; state commits and artifact removal keep their order, and disk preparation finishes before startup begins. A startup worker stays busy until its guest passes SSH readiness, or with --no-wait until QEMU starts and its process identity is verified. Values above 16 are accepted, values above the node count add no workers, negative values are rejected, and suggested retry commands keep the value, including 0. provision --parallel has its own default of 1.
Root disk growth
-D is an absolute target. Growth needs downtime: running nodes return to running, and stopped nodes boot temporarily for checks and expansion, then stop again. Repeating a completed target changes nothing and does not restart the VM; a smaller target fails. The root must use 512-byte logical sectors and a last plain ext4/XFS partition in a GPT or primary MBR layout; LVM, encrypted devices, later partitions, and missing guest tools fail before the image is modified. Root data, VM UUIDs, and SSH keys are kept; data disks are not resized.
Barn records recovery stages and checks image, guest disk, partition, and filesystem sizes before finishing. After a failure, status shows a root-resize warning: fix the reported problem and repeat the same resize -D target. A grown image is never shrunk to undo an incomplete expansion. Update vm_disk to keep the new size, or the next run reports drift. Implementation and measurements: root growth acceptance.
SPEC display
Node tables show effective CPU and memory in a SPEC column such as 1c2g, 2c4g, or 8c16g: c is vCPUs and g is GiB, so 1536 MiB is 1.5g and 512 MiB is 0.5g. Memory that is not a whole number of MiB shows its exact byte count with b, and an unknown specification shows -. Plans show changes as 2c4g → 4c8g and root capacity in a separate ROOT column.
status and completion results show applied resources; plan, validate, and setup show desired ones. When scale is not 1, output explains the base, multiplier, result, and sources; --verbose explains it at scale 1 too. JSON keeps numeric CPU counts and byte sizes in resources[], so scripts never parse SPEC. The flags that set these values are in Specification overrides.
Interruption and recovery
- Cancellation: On cancellation Barn sends SIGTERM to the external program it is running (
sudoforwards it to the privileged command) and waits at most 10 seconds for that process and its inherited output pipes. Descendants that ignore SIGTERM need outside supervision. - Fault isolation: During
uporstart, a missing host share or a failed new-node preparation affects only that node; independent stopped nodes still start, and the command exits5with a retry command that keeps your-f,--repo, and other flags. - Interrupted transitions: A QEMU PID reused by an unrelated process marks the node
stopped; astopinterrupted while the VM kept running marks itrunning. After an onlineresizeinterrupted mid-change,statusreportsresize_incomplete: retrybarn resize <node>or runbarn restart <node>. Other interrupted transitions print the recovery command (destroyresolves them directly), and the next run after a failed initialuprolls back uncommitted journal artifacts automatically. - Event log:
setupand the lifecycle run that follows share oneoperation_id. Even if setup fails before a deployment exists,barn logs --source events --jsonshows the bounded phase log, without sensitive arguments or credentials;setup --dry-runwrites none. - Retained persistent disks: Disks left by a previously removed node do not block destroying the remaining nodes; delete them with
destroy --delete-persistentorpurge. - macOS setup:
setupfinishes Homebrew discovery or installation and the pinnedsocket_vmnetdownload before asking for administrator privileges, so a slow download cannot expire an earliersudotoken and a failed download never prompts for a password.
Logs and environment
barn logs reads the guest serial console by default; --source qemu selects QEMU diagnostics and --source events the deployment-wide event log. --follow streams raw bytes in text mode, NDJSON with --json, and YAML documents with --yaml. QEMU argv appears only with --verbose.
| Environment variable | Purpose |
|---|---|
BARN_HOME | Private state directory (default ~/.barn), one Linux deployment each; accepts relative paths, ~/, and directory symlinks, but not / or the home root. Prefer an absolute path across working directories |
BARN_IMAGE/BARN_ARCH/BARN_CPU/BARN_MEM/BARN_SCALE/BARN_DISK | VM specification overrides; CLI takes priority. Read only by commands accepting each field; see specification overrides |
BARN_REPO | Default image repository URL or path; overridden by --mirror and --repo |
BARN_OUTPUT | Default output format (text, json, or yaml); overridden by --json/--yaml |
BARN_VERBOSE | Boolean default for diagnostic output; overridden by -v/--verbose |
BARN_VMNET_ARCHIVE | Path to a local pinned socket_vmnet archive for macOS setup; accepts relative paths, ~/, and symlinks (SHA-256 verification still applies) |
NO_COLOR | Any non-empty value disables ANSI color output |
An invalid BARN_OUTPUT or BARN_VERBOSE makes every command exit 2 (usage) unless the matching flag overrides it; --help always works.
SSH passthrough and completion
barn ssh and barn exec take Barn flags and an optional node name, then --, then the remote command, and exit with the remote command’s status. ssh hands the guest shell one string; exec passes the program and its arguments unchanged. The full rule, with examples, is in Remote commands and --.
barn completion bash|zsh|fish|powershell prints a completion script (for Bash, reload it after upgrades with source <(barn completion bash)). It completes commands, aliases, templates, image aliases, enumerated flag values, YAML files for -f, and node names from the current inventory or applied state, and stops suggesting Barn flags after --.