Architecture overview
How vz is put together: the layers of the Swift package, the two processes that run a lab, and how switches, links and addresses work. Read this before you change code.
Goals and non-goals
vz describes infrastructure in one YAML file: virtual machines, the switches and cables between them, their disks and devices. It builds that infrastructure with Apple's Virtualization, vmnet and DiskImageKit frameworks on macOS 27.
| vz does | vz does not |
|---|---|
| Create VMs, vmnet switches and point-to-point links | Configure anything inside the guests |
| Download and verify OS cloud disks and installer ISOs | Run a hypervisor of its own |
Give each node stable MAC addresses and a stable cloud-init instance-id | Manage packages, services or users in the guest |
| Attach a cloud-init seed that you write | Generate guest configuration for you |
| Change a running lab: cables, ports, USB media, memory | Need root, a daemon or a kernel extension |
The only thing vz puts inside a guest is the optional first-boot data from the node's init key, and that is your own file: a cloud-init seed on generic nodes, or the account macOS creates on apple nodes.
Layers
The package has five targets. Each one depends only on the targets below it.
| Target | Owns | Must not |
|---|---|---|
LabCore | The Lab model, YAML loading (Yams), validation, state directory, control protocol types, address discovery | Import Virtualization, vmnet or any Apple VM API |
LabImages | Downloads, checksum lists, unpackers (tar.xz, qcow2, xz) | Depend on any other vz target |
LabRuntime | The engine: Virtualization, vmnet, DiskImageKit, AppKit windows, Accessory Access | Contain code for a specific OS |
LabOS | Platforms/: one adapter per machine type (GenericPlatform, ApplePlatform) and the PlatformTable. Images/: one image maker per catalog image (what to fetch and how to prepare it) | Check a platform or OS outside its adapter; let image makers import or call each other |
vz | Commands, terminal and JSON output, and Composition.swift | Leak concrete platforms or image makers into the layers below |
IMPORTANT
The engine never asks which OS or machine type a node runs. It receives a MachinePlan from an injected MachinePlanner: the PlatformTable, which looks up the node's platform and asks that platform's adapter. See VM assembly for how that works, and keep new code on the right side of this line.
Composition.swift is the composition root. It is the only place that knows the concrete platforms (StandardPlatforms.all), the image makers (StandardImages.all) and the image fetcher. Its validate runs the lab file rules, then PlatformTable.validate. Commands ask it for what they need.
Two processes
A running lab is two kinds of process.
The CLI process is every command you type. It loads and validates the lab file, then either does the work itself (validate, image pull, topology, reset) or sends one request to the lab process.
The lab process is vz __run-lab, a hidden command. It owns every VM, switch and cable of one lab, and serves the other commands on a Unix socket. A VZVirtualMachine cannot move between processes, so everything that touches a VM (consoles, display windows, cable changes) happens here.
How the lab process is started and kept alive (DetachedProcess.swift, Tools.swift, main.swift):
vz upstarts it withposix_spawnandPOSIX_SPAWN_SETSID, so it has its own session and closing the terminal does not stop the VMs.forkis not used because it is unsafe in Swift.- Its stdin is
/dev/null. Its stdout and stderr go to<state>/lab.log. Its working directory is the lab file's folder. main.swiftruns__run-labinsideNSApplication.run(), as an accessory app with no Dock icon. AppKit windows (forvz node display) only work when the app loop owns the main thread from the start. Every other command runs on a plainCFRunLoopRun().SIGHUPandSIGPIPEare ignored. A client that goes away mid-write (Ctrl-C on a command, a closed console window, a dropped port forward) must only end that connection, not every VM.SIGINTandSIGTERMstart a graceful ACPI shutdown. A second signal powers the VMs off.- It writes its pid to
<state>/lab.pidand registers itself in~/.vz/labs/<hash>.jsonforvz ls. Both are removed on exit.
NOTE
A pid only counts as "this lab" while lab.pid still contains it and the process is alive. A recycled pid cannot be mistaken for a running lab. vz ls drops registry entries that fail this check.
Starting a lab
If the child exits, up prints the last 40 lines of lab.log. If a node reports stopped or error during startup, up sends SIGTERM to the lab process and fails. After 180 seconds it gives up and points at the log.
A runtime command
Every command after up is one request and one response. vz link down a-b looks like this:
vz down sends down with no nodes. When every VM has stopped, the runner calls onIdle, the server stops listening, and the process unregisters, removes lab.pid and control.sock, and exits. The protocol itself is in Control protocol.
Switches and links
A lab has two kinds of network. They are built in SwitchBuilder.swift and LinkBuilder.swift.
| Switch | Link | |
|---|---|---|
| Backed by | A vmnet_network_ref from vmnet_network_create | A socketpair(AF_UNIX, SOCK_DGRAM) |
| NIC attachment | VZVmnetNetworkDeviceAttachment | VZFileHandleNetworkDeviceAttachment, one end per NIC |
| Members | Any number of NICs, and the Mac | Exactly two NICs on two different nodes |
| Services | DHCP, DNS proxy, IPv6 router advertisement, NAT, port forwarding | None: frames pass unchanged |
| Mode | VMNET_SHARED_MODE when nat4 or nat6 is true, else VMNET_HOST_MODE | Not applicable |
A switch configuration starts from the mode and then turns off what the lab file turns off (disable_nat44, disable_nat66, disable_dhcp, disable_dns_proxy, disable_router_advertisement). The MTU, IPv4 subnet (the Mac gets the first host address), IPv6 prefix, DHCP reservations and port forwarding rules are added before vmnet_network_create. The network lives only inside the lab process, as long as the reference is held.
A link sets SO_SNDBUF to the link's buffer (default 4 MiB) and SO_RCVBUF to twice that, as Apple recommends. Frames move between the two VMs inside the kernel. No vz code runs in the data path.
port down and link down work by setting a NIC's attachment to nil; up puts the saved attachment back. The attachment is created even for interfaces with connected: false, so it can be plugged in later.
Localhost port forwarding
vmnet's NAT port forwarding is not reachable on the loopback interface. For each TCP rule, LocalForwarder.swift also listens on 127.0.0.1 and ::1 and splices each connection to the guest. If the port is already taken on loopback, it logs that and leaves the address to vmnet. UDP rules stay with vmnet only.
Address discovery
vz node ls shows the address each NIC actually uses. vmnet hands out addresses with the macOS DHCP server, so AddressDiscovery.swift reads /etc/bootptab (the reservations bootpd holds) and /var/db/dhcpd_leases once per status request:
| Source | Evidence | Notes |
|---|---|---|
reservation | /etc/bootptab holds this MAC with an address in the switch subnet | bootpd writes no lease for a reservation, so an older pool lease for the same MAC can stay in the lease file. The reservation wins over it |
lease | A lease whose client id is this MAC | Newest lease wins |
hostname | The newest lease in the switch subnet with the node's name | For guests that send a DUID instead of their MAC (Debian). Only used when the subnet is known, so another lab with the same node names does not match |
reserved | The lab file's reservation, not in /etc/bootptab, and no lease | Shown with a warning in node ls: macOS dropped the reservation |
Why the main actor
LabRunner, ControlServer, the machine parts and DisplayHost are @MainActor. A VZVirtualMachine belongs to the queue that created it, and AppKit windows belong to the main thread. Keeping all VM work on the main actor means there is one queue and no locking around VM state. Blocking work (accepting on the socket, reading a request line, pumping console bytes, forwarding TCP) is moved to background queues or threads and hops back with continuations.
Where things live on disk
The state directory and ~/.vz layouts are documented for users in Files and environment. In code they are StateDirectory.swift and DataHome.swift.