Atlas guest agent plan

One small Go program inside each VM gives Metal what the hypervisor cannot see: guest load, free memory and disk use. This plan adds four guest jobs to it. For each job it shows the methods on each side, the timeouts and the fallback when the agent is missing or stops.

Context

Metal runs each VM in Firecracker. From the host, Metal can read CPU time and disk counters from the VM cgroup. It cannot read the guest load average, the guest page cache or how full the guest file system is. Those values exist only inside the guest kernel.

The guest agent is one static binary, atlas-guest-agent. The image builder installs it in every Atlas image. Because it is static, it does not depend on the guest distribution or on Python. It also replaces the two Python guest scripts: the metadata service poller and the SSH key lookup.

The agent never starts work by itself, except the metadata poller. Metal asks, the agent answers, and Metal always has a fallback when there is no answer.

One transport for all jobs

Metal talks to the agent over vsock. vsock is a socket between a VM and its host. It does not use the guest network, so a guest firewall, Docker rules or a broken network configuration cannot block it. Only the host can open a connection to the guest, so the agent needs no token.

Firecracker exposes the vsock device as a Unix socket in the VM jail. metald dials a short link to it, /run/metal/<vm-id>.vsock, because a jail path can be longer than the 108-byte Unix socket limit. metald sends CONNECT <port>, and Firecracker answers OK <host port> when the guest accepts.

In the guest, systemd holds one socket for each job (socket activation). systemd starts one short agent process for each connection. No agent daemon runs between requests, and no unit blocks boot.

Each job has its own port. A port above 65535 cannot clash with a service that reuses a TCP port number.

PortJobAgent commandGuest units
100000Usage reportreport-usageatlas-guest-agent-usage.socket
100001Freeze file systemsfreeze-filesystemsatlas-guest-agent-freeze.socket
100002Grow root file systemgrow-root-filesystematlas-guest-agent-grow.socket
100003Clean stoprebootatlas-guest-agent-reboot.socket
An old agent does not listen on a new port, so the guest refuses the connection at once. metald reads that refusal as "this agent cannot do this job" and uses the fallback. No version field and no protocol change are necessary.

Shared metald transport

// firecracker/guest_agent.go
func (runtime *Runtime) dialGuestAgent(ctx context.Context, vmID string, port uint32) (*guestAgentConnection, error)
type guestAgentConnection struct { net.Conn; reader *bufio.Reader }
func (connection *guestAgentConnection) readLine(timeout time.Duration) (string, error)

Each caller sets its own deadline. Every error, such as no socket, a refused port, a timeout or a bad reply, means "agent unavailable" for that call.

Usage report built and tested on a development host

The metrics sampler reads one JSON line every 10 seconds from each running VM. metald does not ask a paused VM, because a paused guest cannot answer.

{"load_average":[0.42,0.31,0.25],
 "memory":{"total_bytes":..,"free_bytes":..,"available_bytes":..,"cached_bytes":..,"swap_total_bytes":..,"swap_free_bytes":..},
 "root_filesystem":{"size_bytes":..,"used_bytes":..,"inodes_total":..,"inodes_used":..},
 "system_state":"running"}

The metrics store and the Metal metrics API carry it as an optional guest object. system_state is new in this plan, see clean stop and boot state.

FailureResult
No agent, old image, or no vsock deviceguest is absent. The rest of the sample is unchanged.
Guest does not answer in 1 secondguest is absent for this sample only.
Reply over 64 KiB or not valid JSONguest is absent. The guest controls the reply, so metald limits its size and time.

Freeze for clean snapshots

Problem. To capture a running VM, Metal pauses the vCPUs, takes a ZFS snapshot and resumes. The image is crash-consistent: it is equal to a disk after a power loss. Writes that the guest still holds in its page cache are not in the image, and the first boot replays the file system journal.

Change. Before the pause, the agent asks the guest kernel to freeze each file system. A freeze writes all cached data and the journal to disk, then blocks new writes. After the snapshot, the agent thaws the file systems and writes continue.

Methods

// guest side: guestagent/freeze.go
func FreezeFilesystems(connection io.ReadWriter) error

// host side: firecracker/guest_agent.go
func (runtime *Runtime) FreezeGuestFilesystems(ctx context.Context, machine vm.RuntimeMachine) (thaw func())

// vm.Runtime interface: same signature. Caller: vm.Manager.CreateSnapshot

Agent behavior

  1. Read /proc/self/mounts. Select each writable mount on a /dev/ block device. Freeze each device only once, because a bind mount shares the same file system.
  2. Freeze in mount order with the FIFREEZE ioctl. If one freeze fails, thaw the ones that are frozen and reply error <reason>.
  3. Reply frozen. Then wait until metald closes the connection, or 30 seconds, whichever comes first.
  4. Thaw in reverse order with FITHAW. The thaw also runs on SIGTERM.
  5. Start the thaw timer before the first freeze. A freeze can block while the kernel writes cached data, so a watchdog thaws the frozen file systems also when a later freeze is still in progress.
  6. Write no log line while frozen. A log write to a frozen disk would block the agent.

Fallbacks

CaseWhat happens
No agent, or the guest refuses port 100001thaw is a no-op. The snapshot continues as today: pause and snapshot, crash-consistent.
Agent replies errorSame as above. metald logs one warning with the reason.
No frozen reply in 10 secondsmetald closes the connection, which thaws anything that is frozen, and continues without a freeze.
metald stops or the host connection dropsFirecracker resets the guest connection. The agent reads end of file and thaws.
The reset does not reach the guestThe agent thaws after 30 seconds by itself.
VM is paused or stoppedmetald does not freeze. A stopped disk is already clean.

Not in scope: live migration with a memory snapshot does not need a freeze, because memory and disk move together.

Grow the root file system

Problem. Atlas can make a VM disk larger while the VM runs. The guest kernel sees the larger disk, but the root file system keeps its old size until a reboot.

Change. After metald applies a new disk size to a running VM, it asks the agent to grow the root file system online.

Methods

// guest side: guestagent/root_filesystem.go
func GrowRootFilesystem(ctx context.Context) error

// host side
func (runtime *Runtime) GrowGuestRootFilesystem(ctx context.Context, machine vm.RuntimeMachine) error

// vm.Runtime interface: same signature.
// Caller: vm.Manager.applyDesiredSpecification, after RefreshDisk, only when the VM is running.

Agent behavior

  1. Find the root mount in /proc/self/mountinfo. Read its device number and file system type. /proc/mounts can show /dev/root, which has no device file, so the agent uses /dev/block/<major>:<minor>.
  2. Run resize2fs for ext4, or xfs_growfs / for XFS. A disk that is already full size is a quick no-op.
  3. Reply ok, or error <reason> for another file system type or a failed command.

Fallbacks

CaseWhat happens
No agent, error reply or no reply in 30 secondsmetald logs a warning. The disk change still succeeds. The file system grows at the next boot, when cloud-init runs its resize step.
The resize takes too longThe agent stops the command after 25 seconds, before metald stops waiting. An online grow is safe to run again.

The 30-second limit keeps the reconcile pass short, because it runs while metald holds the VM operation lock.

Clean stop and boot state

Clean stop

Today. To stop a VM, metald sends Ctrl-Alt-Del. systemd in the guest shuts down the services, then reboots. Firecracker exits on a guest reboot, because it has no power-off. After a timeout, metald kills the process.

Gap. An image can mask ctrl-alt-del.target. Then Ctrl-Alt-Del does nothing and every stop waits for the full timeout, then kills the guest.

Change. metald asks the agent first. The agent runs systemctl reboot --no-block, then replies ok. The command only queues the reboot, so the reply comes before the shutdown. If systemd refuses, the agent replies error and metald sends Ctrl-Alt-Del.

// guest side
func RequestReboot(ctx context.Context, connection io.Writer) error

// host side, firecracker/machine.go
func (m *machine) shutdownGuest(ctx context.Context) error
    // 1. agent reboot request, 2 second limit
    // 2. if that fails: Ctrl-Alt-Del, as today
    // 3. wait for the process to exit, up to stopTimeout
    // 4. SIGKILL, as today

Boot state

The usage report adds system_state, the output of systemctl is-system-running. Values include starting, running and degraded. It shows when the guest finished boot, and whether a unit failed.

If the command fails or takes more than 0.5 seconds, the field is empty and the rest of the report is unchanged. In this plan, metald only reports the value. It does not change any decision, such as the SSH check after a migration. That can follow when the value proves reliable.

Upgrades

The agent ships inside the image. A new image gives new VMs a new agent. A running VM keeps its agent until it is rebuilt from a new image. There is no self-update.

This is safe because the contract only grows. New fields in the usage report are optional, and each new job uses a new port. So any metald works with any agent version, and an old agent only misses the newer jobs.

All methods

OwnerMethodReturns on failure
guestagentReadUsage(procRoot string) (Usage, error)error, process exits 1
guestagentFreezeFilesystems(connection io.ReadWriter) errorthaws, replies error
guestagentGrowRootFilesystem(ctx context.Context) errorreplies error
guestagentRequestReboot(ctx context.Context, connection io.Writer) errorerror, process exits 1
guestagentRunMetadata(ctx context.Context)never returns early
guestagentWriteAuthorizedKeys(ctx context.Context, writer io.Writer) errorerror, sshd uses no keys
firecracker.RuntimeGetGuestUsage(ctx, machine) *guestagent.Usagenil
firecracker.RuntimeFreezeGuestFilesystems(ctx, machine) (thaw func())no-op thaw
firecracker.RuntimeGrowGuestRootFilesystem(ctx, machine) errorerror, caller logs only
firecracker machineshutdownGuest(ctx), agent firstCtrl-Alt-Del, then SIGKILL
vm.ManagerCreateSnapshot, applyDesiredSpecification, Metricswork as today without an agent
Metal APImetrics sample: optional guest objectfield absent

Timeouts: nothing waits forever

WaitLimitAfter the limit
Usage reply1 sno guest in this sample
frozen reply10 sclose, snapshot without freeze
Frozen time in the guest30 sagent thaws by itself
Grow reply30 slog warning, grow at next boot
Reboot request reply2 sCtrl-Alt-Del
Guest exit after a stopstopTimeout (existing)SIGKILL
systemctl is-system-running0.5 sempty system_state
MMDS request3 snext poll in 250 ms

No metald call to the agent holds a database lock. The freeze and the grow run inside the VM operation lock, so each has a fixed limit.

Compatibility

metaldGuestResult
NewOld image, no agentAll features use their fallback. Metrics have no guest.
NewVM not cold-booted since the vsock device was addedNo vsock socket. Same as no agent until the next cold boot.
NewAgent from an earlier releaseJobs the agent has work. New jobs see a refused port and fall back.
OldNew imagemetald never connects. The agent still does metadata and SSH keys. Socket units wait without cost.

The Metal API change adds one optional field. The usage JSON only gets new optional fields. No stored record changes shape, so no metald patch is needed.

Tests and rollout

Focused tests

Development host checks

  1. Build an Ubuntu 24.04 image from the branch. Create a VM.
  2. Machine image of a running VM: check frozen in the guest journal, and a clean mount without journal replay.
  3. Kill metald during a freeze: the guest thaws within 30 seconds.
  4. Grow the disk of a running VM: df / shows the new size without a reboot.
  5. Mask ctrl-alt-del.target, then stop the VM: it stops before the timeout.
  6. Live migration with a memory snapshot: the usage report continues on the destination.

Rollout

  1. Upgrade metald. Nothing changes for running VMs.
  2. Rebuild images. New VMs get the agent. Existing VMs get the vsock device at their next cold boot.

Decisions

  1. Agent upgrades only through a new image. No self-update.
  2. Ports 100000 to 100003, one systemd socket for each job.
  3. Timeouts in the table above, especially the 30-second automatic thaw.

References: Firecracker vsock · systemd.socket · fsfreeze(8) · Firecracker MMDS