Skip to content

vm: virtual machine manager ​

For Go code, follow the repository Go anti-pattern rules.

Metal specification · overview: Metal reconciliation

Purpose ​

This package owns VM records, state transitions, and reconciliation. Host packages implement runtime, network, storage, and snapshot operations through small interfaces declared here.

Request flow ​

Flow diagram
Loading diagram...
  • The desired generation rises only for a real desired change.
  • The restart generation rises for each accepted restart.

Records ​

text
machines/<id>/config.json   desired state and specification
machines/<id>/status.json   observed state and operation progress
machines/<id>/metrics/     seven days of daily VM usage files
  • The create fingerprint excludes signed image URLs.
  • A firewall change increases the specification generation.
  • cpu_millicores accepts 100 through 32000. Firecracker receives ceil(cpu_millicores / 1000) vCPUs.
  • A sleep_after_idle_seconds change does not change SpecificationGeneration.
  • Every read and write validates a record. An unreadable record takes only its own VM out of management; List returns its identifier separately. metald does not repair or remove an invalid record.
  • A record format change ships a patch in internal/patches. See Change stored state with a patch.

Reconciliation ​

Desired power stateAction
runningStart, resume, or restore. Stop after idle when configured.
pausedStart or restore, then pause.
stoppedHard stop and delete saved state.
destroyedRemove runtime, network, storage, and records.

Idle behavior is in Sleepy VMs.

wake_admission.go checks host memory before a sleeping VM wakes. ManagerDependencies.AvailableMemory supplies the memory, from host.Service.AvailableMemoryMiB. The wakeAdmission mutex orders checks. It owns two in-memory maps. One holds admitted wakes that have not written their awake state. The other holds early sleep requests, until stopAfterIdle saves the VM or keeps it awake. A held wake does not change the desired record, so its pending change stays. See wake memory check.

sleep_state.go owns machines/<id>/sleep-state.json, a mode 0600 record for one upload checkpoint and its artifact URLs. sleep_transfer.go uploads artifacts through a separate eight-worker reconciler and evicts local data only for the matching sleeping checkpoint. It persists the remote sleep state before eviction.

A per-VM transfer lock serializes uploads. The operation lock protects staging and status updates, and is released while upload bytes move. Wake holds the operation lock through download and restore. Reconciliation skips a busy VM instead of waiting for its lock. restoreSavedState prepares remote artifacts for both deep sleep and coma before runtime restore. See offloaded wake.

OffloadSleepArtifacts runs under the daemon-owned upload pool. RestoreSleepState reconciles sleeping VMs in a separate eight-worker pool. Normal VM reconciliation does not wait for either pool. Sleep reconciliation preserves upload phases while the checkpoint still matches. A stop, restart, shape change, or destruction can proceed without acquiring the transfer lock. A late upload failure cannot replace a wake or stop result.

Upload completion cannot evict artifacts after migration takes the VM's source lock.

Start and traffic requests increase the desired generation for a sleeping VM. A pending generation prevents further offload and tells reconciliation to restore instead of rearming sleep. The request survives daemon restart. Duplicate pending starts do not wait for the restore lock or add another generation.

The existing VM response adds optional upload_percent to each artifact under observed.sleep_snapshot.memory and .disk. It is absent before HTTP upload and after a failed transfer ends. Active uploads report 0 through 99 from compressed bytes read by HTTP. Only an acknowledged artifact reports 100.

SleepUploadProgress counters belong to the active transfer, reset on each retry, and are never written to records. observed.phase distinguishes prepare-sleep-memory, compress-sleep-memory, and upload-sleep-memory, with matching disk phases. Live progress does not replace a wake operation's phase.

Sleep-state tests check partial selection, eviction retries, a wake during upload, request-triggered wake, and URL refresh after a failed download.

  • A valid saved state is authoritative when Firecracker is stopped.
  • A saved state beside a running Firecracker process is stale and is deleted.
  • Wake restore failures reuse recoverFailedRestore in migration_state.go. sleep_restore_test.go checks fallback, cancellation, missing disks, and retries after daemon restart. See wake recovery.
  • A restart or machine shape change deletes the saved state.
  • Traffic restore takes the per-VM lock. A stale or duplicate event has no effect.
  • The phase and operation ID are written before each host call.
  • Destroy records progress per resource, so an interrupted destroy resumes.

Rescue mode ​

The handbook owns rescue mode. Specification.RescueImage selects the next cold boot. ObservedRecord.IsInRescueMode reports the last boot, from Runtime.IsInRescueMode. Manager methods call assertNotInRescueMode for each change that the mode rejects.

Migration ​

The migration lifecycle lives in internal/vm/migration/SPEC.md. This package does not import that package.

  • The daemon injects a MigrationGuard with SetMigrationGuard.
  • Without a guard, no VM is migrating.
  • migration_sleep.go exposes SleepMigration and captures and applies an acknowledged checkpoint without runtime calls. SleepCheckpoint.SourceUserID supplies the original identity for installation on a later wake.

Boundaries ​

  • Host packages implement Runtime, Network, Storage, and Snapshots.
  • RuntimeUsage carries a runtime's CPU time, memory, and disk I/O to the VM metrics sampler.
  • Specification.CPUBurst holds the CPU burst settings. Like the idle timeout, a change does not raise SpecificationGeneration. The fields are omitted when empty, so records of other VMs do not change.
  • sliding_window_usage.go owns Manager.RecordMetrics and the in-memory average. Each burstable VM has a fixed-size ring sized for its own window. The metrics sampler calls RecordMetrics after each stored record. It adds the sample to the ring, or fills the ring from the optional ManagerDependencies.Metrics store after a metald restart or a window change. A fill reads from one sample interval before the window start. The average reads only memory. One mutex guards all rings and is never held during a disk read. A VM that stops being burstable or has no desired record loses its ring at the next sweep. Destroy and MigrationHost.RemoveVirtualMachineRecords drop it at once. See average CPU use over a window. sliding_window_usage_test.go checks the ring order, the pair rules, the window filter, idle missing history and down time, the fill from the store, and window changes.
  • cpu_burst.go owns Manager.LimitCPUBursts. It sets the runtime CPU limit of each running burstable VM from its sliding window average. It takes the VM operation lock with TryLock and skips a migrating VM. The runtime CPU quota is the limit state. A VM without samples in memory keeps its limit. Manager.ResetCPUBurst stores DesiredRecord.CPUBurstResetAt, and the average ignores older samples. Manager.CPUBurstStatus reads the settings, the average, and the runtime limit without a lock. See set CPU burst. cpu_burst_test.go checks the limit rule, the job, resets, and the status.
  • The daemon traffic listener passes each traffic.Event to Manager.RestoreAfterTraffic, then wakes the restore reconciler.
  • WarmImageBuilder creates shared start artifacts. It does not use the saved state of an idle VM.

AGPL-3.0