diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 8c3a450f4..a9a6e45b1 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -271,6 +271,7 @@ The server will start on port 4973 (configurable via `port` in config.yaml). ### Shared-Machine Local Config When developing on a shared host, avoid global paths like `/etc/hypeman` and `/var/lib/hypeman`. +Only one API process can use a data directory at a time. Stop the old process before upgrading or downgrading; older versions do not take the directory lock. Use a workspace-local config and data directory instead: ```bash diff --git a/cmd/api/data_dir_lock.go b/cmd/api/data_dir_lock.go new file mode 100644 index 000000000..014c5eba2 --- /dev/null +++ b/cmd/api/data_dir_lock.go @@ -0,0 +1,28 @@ +package main + +import ( + "errors" + "fmt" + "os" + "syscall" +) + +// Instance metadata locks are process-local. Hold the directory inode locked +// until shutdown, before any startup scan can read and write instance records. +func lockDataDir(path string) (*os.File, error) { + if err := os.MkdirAll(path, 0755); err != nil { + return nil, err + } + dir, err := os.Open(path) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(dir.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + dir.Close() + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil, fmt.Errorf("another Hypeman process is using this directory: %w", err) + } + return nil, err + } + return dir, nil +} diff --git a/cmd/api/data_dir_lock_test.go b/cmd/api/data_dir_lock_test.go new file mode 100644 index 000000000..a7986ac3e --- /dev/null +++ b/cmd/api/data_dir_lock_test.go @@ -0,0 +1,41 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) { + const subprocess = "HYPEMAN_TEST_LOCKED_STARTUP" + if os.Getenv(subprocess) == "1" { + require.ErrorIs(t, run(), syscall.EWOULDBLOCK) + return + } + + path := filepath.Join(t.TempDir(), "data") + owner, err := lockDataDir(path) + require.NoError(t, err) + t.Cleanup(func() { owner.Close() }) + + alias := filepath.Join(t.TempDir(), "same-data") + require.NoError(t, os.Symlink(path, alias)) + cfg := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(cfg, []byte("data_dir: "+alias+"\njwt_secret: local-test-secret-for-data-dir-lock\n"), 0600)) + cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestServerRefusesSecondWriterBeforeStartup$") + cmd.Env = append(os.Environ(), subprocess+"=1", "CONFIG_PATH="+cfg, "DATA_DIR="+alias) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + entries, err := os.ReadDir(path) + require.NoError(t, err) + require.Empty(t, entries, "the second API must not initialize or recover anything") + + require.NoError(t, owner.Close()) + next, err := lockDataDir(alias) + require.NoError(t, err) + require.NoError(t, next.Close()) +} diff --git a/cmd/api/main.go b/cmd/api/main.go index 320a3adf7..36f0d25a3 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -37,6 +37,7 @@ import ( "github.com/kernel/hypeman/lib/ocicachegc" "github.com/kernel/hypeman/lib/otel" "github.com/kernel/hypeman/lib/paths" + "github.com/kernel/hypeman/lib/providers" "github.com/kernel/hypeman/lib/registry" "github.com/kernel/hypeman/lib/scopes" "github.com/kernel/hypeman/lib/tokenrevocation" @@ -164,17 +165,19 @@ func run() error { startupStarted := time.Now() slog.Info("starting hypeman initialization") - // Load config early for OTel initialization - // Config path can be specified via CONFIG_PATH env var or defaults to platform-specific locations - configPath := os.Getenv("CONFIG_PATH") - cfg, err := config.Load(configPath) + cfg, err := providers.ServerConfig() if err != nil { - return fmt.Errorf("failed to load config: %w", err) + return err } - - // Validate configuration before proceeding - if err := cfg.Validate(); err != nil { - return fmt.Errorf("invalid configuration: %w", err) + dataDir, err := lockDataDir(cfg.DataDir) + if err != nil { + return fmt.Errorf("lock data directory %q: %w", cfg.DataDir, err) + } + defer dataDir.Close() + // A source that cannot be put back is left as it is and never resolves + // to another guest, so the rest of the host starts without it. + if err := instances.RecoverParkedForkSources(paths.New(cfg.DataDir)); err != nil { + slog.Error("failed to recover parked fork sources; they are left as they are until repaired", "error", err) } // Configure GPU profile cache TTL @@ -365,6 +368,15 @@ func run() error { return fmt.Errorf("reconcile device state: %w", err) } + // A fork that a crash cut short still holds its VMM, memory and vGPU. + // Delete those before the vGPU reconciler counts their claims. + logger.Info("Recovering interrupted forks...") + if r, ok := app.InstanceManager.(interface{ RecoverInterruptedForks(context.Context) }); ok { + r.RecoverInterruptedForks(app.Ctx) + } else { + logger.Warn("instance manager does not implement RecoverInterruptedForks") + } + logger.Info("Reconciling vGPU devices...") if r, ok := app.InstanceManager.(interface{ StartVGPUReconciler(context.Context) }); ok { r.StartVGPUReconciler(ctx) diff --git a/lib/devices/manager.go b/lib/devices/manager.go index 30763c04d..b05914346 100644 --- a/lib/devices/manager.go +++ b/lib/devices/manager.go @@ -3,6 +3,7 @@ package devices import ( "context" "encoding/json" + "errors" "fmt" "os" "runtime" @@ -65,6 +66,12 @@ type Manager interface { // MarkDetached marks a device as detached from an instance MarkDetached(ctx context.Context, deviceID string) error + // ReleaseInstanceDevice detaches and unbinds a passthrough device only if this instance owns it. + ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error + + // DetachInstanceDevice clears the attachment without unbinding, only if this instance owns it. + DetachInstanceDevice(ctx context.Context, deviceID, instanceID string) error + // ReconcileDevices cleans up stale device state on startup. // It detects devices with AttachedTo referencing non-existent instances // and clears the orphaned attachment state. @@ -75,9 +82,21 @@ type Manager interface { SetLivenessChecker(checker InstanceLivenessChecker) } +type deviceBinder interface { + deviceBoundToVFIO(string) (bool, error) + IsDeviceBoundToVFIO(string) bool + BindToVFIO(string) error + UnbindFromVFIO(string) error + CheckIOMMUGroupSafe(string, []string) error + unbindFromDriver(string, string) error + setDriverOverride(string, string) error + triggerDriverProbe(string) error + startNvidiaPersistenced() error +} + type manager struct { paths *paths.Paths - vfioBinder *VFIOBinder + vfioBinder deviceBinder livenessChecker InstanceLivenessChecker mu sync.RWMutex } @@ -322,8 +341,6 @@ func (m *manager) BindToVFIO(ctx context.Context, id string) error { } func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error { - log := logger.FromContext(ctx) - m.mu.Lock() defer m.mu.Unlock() @@ -341,8 +358,8 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error { return ErrInUse } - // Unbind from VFIO - if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil { + log := logger.FromContext(ctx) + if err := m.unbindAndVerify(device.PCIAddress); err != nil { return err } @@ -397,11 +414,68 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error { return m.saveDevice(device) } +// The driver probe can bind the device straight back to vfio-pci. Check +// sysfs before recording the release or dropping the owner that can retry it. +func (m *manager) unbindAndVerify(pciAddress string) error { + if err := m.vfioBinder.UnbindFromVFIO(pciAddress); err != nil { + return err + } + bound, err := m.vfioBinder.deviceBoundToVFIO(pciAddress) + if err != nil { + return fmt.Errorf("verify VFIO release of %s: %w", pciAddress, err) + } + if bound { + return fmt.Errorf("device %s is still bound to vfio-pci", pciAddress) + } + return nil +} + +// ReleaseInstanceDevice checks the recorded owner under the same lock as the unbind. +// A fork's device list can name a passthrough device still owned by its source. +func (m *manager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error { + m.mu.Lock() + defer m.mu.Unlock() + device, err := m.loadDevice(deviceID) + if err != nil { + return err + } + if device.AttachedTo == nil || *device.AttachedTo != instanceID { + return nil + } + // A retry after the unbind but before the save sees ErrNotBound. + if err := m.unbindAndVerify(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) { + return err + } + device.AttachedTo = nil + device.BoundToVFIO = false + return m.saveDevice(device) +} + +// DetachInstanceDevice frees a device whose owner is being deleted after its +// release failed. Nothing retries a release once the owner is gone, and +// nothing but a restart clears an attachment to a missing instance. +func (m *manager) DetachInstanceDevice(ctx context.Context, deviceID, instanceID string) error { + m.mu.Lock() + defer m.mu.Unlock() + device, err := m.loadDevice(deviceID) + if err != nil { + return err + } + if device.AttachedTo == nil || *device.AttachedTo != instanceID { + return nil + } + device.AttachedTo = nil + // The failed release may or may not have unbound the device, and the next + // attach binds it only if this says it is unbound. + device.BoundToVFIO = m.vfioBinder.IsDeviceBoundToVFIO(device.PCIAddress) + return m.saveDevice(device) +} + // ReconcileDevices cleans up stale device state on startup. // It performs safe-by-default reconciliation: // 1. Detects orphaned device attachments (instance missing or not running) -// 2. Clears orphaned AttachedTo metadata -// 3. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver) +// 2. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver) +// 3. Clears the attachment once the device is no longer bound to VFIO // 4. Logs mismatches between instance→device and device→instance references // 5. Detects suspicious cloud-hypervisor processes func (m *manager) ReconcileDevices(ctx context.Context) error { @@ -471,19 +545,6 @@ func (m *manager) ReconcileDevices(ctx context.Context) error { "orphaned_instance_id", instanceID, ) - // Clear the orphaned attachment - device.AttachedTo = nil - if err := m.saveDevice(device); err != nil { - log.ErrorContext(ctx, "failed to save device after clearing attachment", - "device_id", device.Id, - "error", err, - ) - stats.errors++ - continue - } - stats.orphanedCleared++ - - // Run GPU-reset-lite for orphaned device m.resetOrphanedDevice(ctx, device, &stats) } } @@ -695,30 +756,22 @@ func (m *manager) resetOrphanedDevice(ctx context.Context, device *Device, stats } // Verify the device is now unbound from VFIO - stillBoundToVFIO := m.vfioBinder.IsDeviceBoundToVFIO(device.PCIAddress) - if stillBoundToVFIO { - log.WarnContext(ctx, "device still bound to VFIO after reset-lite", - "device_id", device.Id, - "pci_address", device.PCIAddress, - ) + bound, err := m.vfioBinder.deviceBoundToVFIO(device.PCIAddress) + if err != nil || bound { + log.WarnContext(ctx, "cannot confirm device was unbound after reset-lite; keeping attachment", + "device_id", device.Id, "pci_address", device.PCIAddress, "bound_to_vfio", bound, "error", err) stats.resetFailed++ - } else { - log.InfoContext(ctx, "GPU-reset-lite completed for orphaned device", - "device_id", device.Id, - "device_name", device.Name, - "pci_address", device.PCIAddress, - ) - stats.resetSucceeded++ + return } - - // Update device metadata to reflect new VFIO state - device.BoundToVFIO = stillBoundToVFIO + stats.resetSucceeded++ + device.AttachedTo = nil + device.BoundToVFIO = false if err := m.saveDevice(device); err != nil { - log.WarnContext(ctx, "failed to save device after reset-lite", - "device_id", device.Id, - "error", err, - ) + log.WarnContext(ctx, "failed to save device after reset-lite", "device_id", device.Id, "error", err) + stats.errors++ + return } + stats.orphanedCleared++ } // Helper methods diff --git a/lib/devices/manager_test.go b/lib/devices/manager_test.go index 3c429f7e0..fc1d3488d 100644 --- a/lib/devices/manager_test.go +++ b/lib/devices/manager_test.go @@ -2,6 +2,7 @@ package devices import ( "context" + "errors" "os" "path/filepath" "testing" @@ -182,6 +183,82 @@ func TestDeviceLookupAndDeleteRejectPathTraversal(t *testing.T) { require.FileExists(t, marker) } +type releaseTestBinder struct { + *VFIOBinder + unbind func(string) error + bound bool + inspectErr error +} + +func (b *releaseTestBinder) UnbindFromVFIO(addr string) error { return b.unbind(addr) } +func (b *releaseTestBinder) deviceBoundToVFIO(string) (bool, error) { + return b.bound, b.inspectErr +} + +func TestReleaseInstanceDeviceKeepsOwnerUntilUnbound(t *testing.T) { + for _, tc := range []struct { + name string + unbindErr error + bound bool + inspectErr error + retryResult error + }{ + {name: "unbind failed", unbindErr: errors.New("device busy")}, + {name: "rebound after probe", bound: true}, + {name: "binding unreadable", inspectErr: errors.New("sysfs unavailable"), retryResult: ErrNotBound}, + } { + t.Run(tc.name, func(t *testing.T) { + m, p, _ := setupTestManager(t) + owner := "fork" + device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner, BoundToVFIO: true} + createTestDevice(t, p, device) + result := tc.unbindErr + var calls int + binder := &releaseTestBinder{bound: tc.bound, inspectErr: tc.inspectErr, unbind: func(addr string) error { + calls++ + require.Equal(t, device.PCIAddress, addr) + stored, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Equal(t, &owner, stored.AttachedTo) + return result + }} + + m.vfioBinder = binder + require.Error(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner)) + kept, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Equal(t, &owner, kept.AttachedTo) + require.True(t, kept.BoundToVFIO) + + result, binder.bound, binder.inspectErr = tc.retryResult, false, nil + require.NoError(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner)) + require.Equal(t, 2, calls) + got, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Nil(t, got.AttachedTo) + require.False(t, got.BoundToVFIO) + }) + } +} + +func TestDetachInstanceDeviceFreesOnlyItsOwnersDevice(t *testing.T) { + m, p, _ := setupTestManager(t) + owner := "deleted" + device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner, BoundToVFIO: true} + createTestDevice(t, p, device) + + require.NoError(t, m.DetachInstanceDevice(t.Context(), device.Id, "fork")) + got, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Equal(t, &owner, got.AttachedTo) + + require.NoError(t, m.DetachInstanceDevice(t.Context(), device.Id, owner)) + got, err = m.loadDevice(device.Id) + require.NoError(t, err) + require.Nil(t, got.AttachedTo) + require.False(t, got.BoundToVFIO, "the device is not bound, so the next attach must bind it") +} + func TestSaveLoadDevice_MetadataRoundTrip(t *testing.T) { p := paths.New(t.TempDir()) mgr := &manager{ diff --git a/lib/devices/reconcile_test.go b/lib/devices/reconcile_test.go index 98db94703..3442d8802 100644 --- a/lib/devices/reconcile_test.go +++ b/lib/devices/reconcile_test.go @@ -86,6 +86,25 @@ func createTestInstanceDir(t *testing.T, p *paths.Paths, instanceID string) { require.NoError(t, os.MkdirAll(instanceDir, 0755)) } +type boundAfterReset struct{ *VFIOBinder } + +func (boundAfterReset) deviceBoundToVFIO(string) (bool, error) { return true, nil } +func (boundAfterReset) setDriverOverride(string, string) error { return nil } +func (boundAfterReset) triggerDriverProbe(string) error { return nil } + +func TestReconcileDevicesKeepsOwnerIfStillBound(t *testing.T) { + m, p, _ := setupTestManager(t) + owner := "missing" + device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner} + createTestDevice(t, p, device) + m.vfioBinder = boundAfterReset{NewVFIOBinder()} + + require.NoError(t, m.ReconcileDevices(t.Context())) + got, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Equal(t, &owner, got.AttachedTo) +} + func TestReconcileDevices_NoDevices(t *testing.T) { mgr, _, _ := setupTestManager(t) ctx := context.Background() diff --git a/lib/devices/vfio_darwin.go b/lib/devices/vfio_darwin.go index ae47cbcde..93967f046 100644 --- a/lib/devices/vfio_darwin.go +++ b/lib/devices/vfio_darwin.go @@ -28,6 +28,10 @@ func (v *VFIOBinder) IsDeviceBoundToVFIO(pciAddress string) bool { return false } +func (v *VFIOBinder) deviceBoundToVFIO(pciAddress string) (bool, error) { + return false, nil +} + // BindToVFIO returns an error on macOS as VFIO is not supported. func (v *VFIOBinder) BindToVFIO(pciAddress string) error { return ErrVFIONotSupportedOnMacOS diff --git a/lib/devices/vfio_linux.go b/lib/devices/vfio_linux.go index fdd0c6820..b2e7ac838 100644 --- a/lib/devices/vfio_linux.go +++ b/lib/devices/vfio_linux.go @@ -34,8 +34,16 @@ func (v *VFIOBinder) IsVFIOAvailable() bool { // IsDeviceBoundToVFIO checks if a device is currently bound to vfio-pci func (v *VFIOBinder) IsDeviceBoundToVFIO(pciAddress string) bool { - driver := readCurrentDriver(pciAddress) - return driver != nil && *driver == "vfio-pci" + bound, _ := v.deviceBoundToVFIO(pciAddress) + return bound +} + +func (v *VFIOBinder) deviceBoundToVFIO(pciAddress string) (bool, error) { + target, err := os.Readlink(filepath.Join(sysfsDevicesPath, pciAddress, "driver")) + if os.IsNotExist(err) { + return false, nil + } + return filepath.Base(target) == "vfio-pci", err } // BindToVFIO binds a PCI device to the vfio-pci driver @@ -104,7 +112,11 @@ func (v *VFIOBinder) BindToVFIO(pciAddress string) error { // UnbindFromVFIO unbinds a device from vfio-pci and restores the original driver func (v *VFIOBinder) UnbindFromVFIO(pciAddress string) error { - if !v.IsDeviceBoundToVFIO(pciAddress) { + bound, err := v.deviceBoundToVFIO(pciAddress) + if err != nil { + return err + } + if !bound { return ErrNotBound } @@ -117,7 +129,7 @@ func (v *VFIOBinder) UnbindFromVFIO(pciAddress string) error { // Clear driver override first if err := v.setDriverOverride(pciAddress, ""); err != nil { - // Non-fatal, continue with unbind + return fmt.Errorf("clear VFIO driver override: %w", err) } // Unbind from vfio-pci diff --git a/lib/hypervisor/firecracker/process.go b/lib/hypervisor/firecracker/process.go index 443a398b5..eb30a7283 100644 --- a/lib/hypervisor/firecracker/process.go +++ b/lib/hypervisor/firecracker/process.go @@ -216,6 +216,18 @@ func cleanupFailedRestore(pid int, socketPath string) { _ = os.Remove(socketPath) } +// ForkBackupSeparator separates a parked snapshot source from its UnixNano suffix. +const ForkBackupSeparator = ".fork-bak." + +// SnapshotSourceAlias returns the source path recorded for the fallback, if any. +func SnapshotSourceAlias(instanceDir string) (string, error) { + meta, err := loadRestoreMetadata(instanceDir) + if err != nil { + return "", err + } + return meta.SnapshotSourceDataDir, nil +} + func withSnapshotSourceDirAlias(meta *restoreMetadata, targetDataDir string, run func() error) error { if meta == nil || meta.SnapshotSourceDataDir == "" { return run() @@ -239,12 +251,19 @@ func withSnapshotSourceDirAlias(meta *restoreMetadata, targetDataDir string, run backupDataDir := "" if _, err := os.Stat(sourceDataDir); err == nil { - backupDataDir = fmt.Sprintf("%s.fork-bak.%d", sourceDataDir, time.Now().UnixNano()) + backupDataDir = fmt.Sprintf("%s%s%d", sourceDataDir, ForkBackupSeparator, time.Now().UnixNano()) if err := os.Rename(sourceDataDir, backupDataDir); err != nil { return fmt.Errorf("backup snapshot source data dir: %w", err) } } else if !os.IsNotExist(err) { return fmt.Errorf("stat snapshot source data dir: %w", err) + } else { + // A restore killed while its source directory did not exist leaves its + // link here, and the link dangles once that fork is deleted. Stat + // follows links, so anything still at this path is such a link. + if err := os.Remove(sourceDataDir); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove dangling snapshot source alias: %w", err) + } } if err := os.Symlink(targetDataDir, sourceDataDir); err != nil { diff --git a/lib/hypervisor/firecracker/process_test.go b/lib/hypervisor/firecracker/process_test.go index 98c6d4150..919b73b08 100644 --- a/lib/hypervisor/firecracker/process_test.go +++ b/lib/hypervisor/firecracker/process_test.go @@ -82,6 +82,30 @@ func TestWithSnapshotSourceDirAlias_RestoresSourceDirOnRunError(t *testing.T) { require.NoError(t, statErr) } +func TestWithSnapshotSourceDirAlias_ReplacesDanglingAlias(t *testing.T) { + tmp := t.TempDir() + sourceDir := filepath.Join(tmp, "source") + targetDir := filepath.Join(tmp, "target") + + require.NoError(t, os.MkdirAll(targetDir, 0755)) + // Left by a restore that was killed. The fork it pointed at has been deleted. + require.NoError(t, os.Symlink(filepath.Join(tmp, "deleted-fork"), sourceDir)) + + ran := false + err := withSnapshotSourceDirAlias(&restoreMetadata{SnapshotSourceDataDir: sourceDir}, targetDir, func() error { + ran = true + linkTarget, err := os.Readlink(sourceDir) + require.NoError(t, err) + assert.Equal(t, targetDir, linkTarget) + return nil + }) + require.NoError(t, err) + assert.True(t, ran) + + _, err = os.Lstat(sourceDir) + assert.ErrorIs(t, err, os.ErrNotExist) +} + func TestWithSnapshotSourceDirAlias_RejectsNestedPaths(t *testing.T) { tmp := t.TempDir() sourceDir := filepath.Join(tmp, "source") diff --git a/lib/hypervisor/vz_shim_pids.go b/lib/hypervisor/vz_shim_pids.go index f89fbb7a1..e0236c431 100644 --- a/lib/hypervisor/vz_shim_pids.go +++ b/lib/hypervisor/vz_shim_pids.go @@ -6,18 +6,29 @@ import ( "strings" ) -// vzShimPIDsFromPS returns the PIDs in `ps -o pid=,command=` output whose -// vz-shim configuration names socketPath as its control socket. +// Match the kernel's process name as well as the control socket in the +// shim's -config argument. Other processes can mention that socket in argv. func vzShimPIDsFromPS(out []byte, socketPath string) []int { - quoted, _ := json.Marshal(socketPath) // a string always marshals - marker := `"control_socket":` + string(quoted) var pids []int for _, line := range strings.Split(string(out), "\n") { - fields := strings.Fields(line) - if len(fields) < 2 || !strings.Contains(line, " -config ") || !strings.Contains(line, marker) { + command, arg, ok := strings.Cut(line, " -config ") + if !ok { continue } - if pid, err := strconv.Atoi(fields[0]); err == nil { + fields := strings.Fields(command) + if len(fields) < 3 { + continue + } + if name := fields[1]; name != "vz-shim" && !strings.HasPrefix(name, "vz-shim-") { + continue + } + var config struct { + ControlSocket string `json:"control_socket"` + } + if err := json.Unmarshal([]byte(arg), &config); err != nil || config.ControlSocket != socketPath { + continue + } + if pid, err := strconv.Atoi(fields[0]); err == nil && pid > 0 { pids = append(pids, pid) } } diff --git a/lib/hypervisor/vz_shim_pids_darwin.go b/lib/hypervisor/vz_shim_pids_darwin.go index 35063e7bc..bb8fef244 100644 --- a/lib/hypervisor/vz_shim_pids_darwin.go +++ b/lib/hypervisor/vz_shim_pids_darwin.go @@ -15,7 +15,7 @@ import ( func VZShimPIDs(socketPath string) ([]int, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - out, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,command=").Output() + out, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,ucomm=,command=").Output() if err != nil { return nil, fmt.Errorf("list processes: %w", err) } diff --git a/lib/hypervisor/vz_shim_pids_test.go b/lib/hypervisor/vz_shim_pids_test.go index 043eeefb8..0cbf3f052 100644 --- a/lib/hypervisor/vz_shim_pids_test.go +++ b/lib/hypervisor/vz_shim_pids_test.go @@ -13,10 +13,11 @@ func TestVZShimPIDsFromPS(t *testing.T) { require.NoError(t, err) return string(data) } - out := " 101 /tmp/vz-shim-1 -config " + config("/data/guests/a/vz.sock") + "\n" + - " 202 /tmp/vz-shim-2 -config " + config("/data/guests/b/vz.sock") + "\n" + - " 303 grep control_socket\n" + - " 404 /tmp/vz-shim-3 -config " + config("/data/guests/a/vz.sock") + "\n" + out := " 101 vz-shim-1 /tmp/with spaces/vz-shim-1 -config " + config("/data/guests/a/vz.sock") + "\n" + + " 202 vz-shim-2 /tmp/vz-shim-2 -config " + config("/data/guests/b/vz.sock") + "\n" + + " 303 editor editor -config " + config("/data/guests/a/vz.sock") + "\n" + + " 404 vz-shim /tmp/vz-shim -config " + config("/data/guests/a/vz.sock") + "\n" + + ` 505 vz-shim-4 /tmp/vz-shim-4 -config {"nested":{"control_socket":"/data/guests/a/vz.sock"}}` require.Equal(t, []int{101, 404}, vzShimPIDsFromPS([]byte(out), "/data/guests/a/vz.sock")) require.Empty(t, vzShimPIDsFromPS([]byte(out), "/data/guests/c/vz.sock")) require.Empty(t, vzShimPIDsFromPS([]byte(out), "/data/guests/a/vz"), "a socket path prefix does not match") diff --git a/lib/instances/delete.go b/lib/instances/delete.go index 37fd908ca..6915420e4 100644 --- a/lib/instances/delete.go +++ b/lib/instances/delete.go @@ -2,11 +2,13 @@ package instances import ( "context" + "errors" "fmt" "os" "syscall" "time" + "github.com/kernel/hypeman/lib/devices" "github.com/kernel/hypeman/lib/guest" "github.com/kernel/hypeman/lib/hypervisor" "github.com/kernel/hypeman/lib/logger" @@ -84,6 +86,9 @@ func (m *manager) deleteInstanceWithOptions( } } + // A fork restore can create the TAP before it saves the IP and MAC. + releaseTAPByID := inst.usesLinuxNetwork() && stored.ForkPending != nil && networkAlloc == nil + // 3. Close exec gRPC connection before killing hypervisor to prevent panic if dialer, err := hypervisor.NewVsockDialer(inst.HypervisorType, inst.VsockSocket, inst.VsockCID); err == nil { guest.CloseConn(dialer.Key()) @@ -125,7 +130,7 @@ func (m *manager) deleteInstanceWithOptions( // 5. If hypervisor might be running, force kill it // Also attempt kill for StateUnknown since we can't be sure if hypervisor is running - if !gracefulShutdown && (inst.State.RequiresVMM() || inst.State == StateUnknown) { + if !gracefulShutdown && (inst.State.RequiresVMM() || inst.State == StateUnknown || releaseTAPByID) { log.DebugContext(ctx, "stopping hypervisor", "instance_id", id, "state", inst.State) killCtx, killSpanEnd := m.startLifecycleStep(ctx, "force_kill_hypervisor", attribute.String("instance_id", id), @@ -161,10 +166,14 @@ func (m *manager) deleteInstanceWithOptions( attribute.String("hypervisor", string(stored.HypervisorType)), attribute.String("operation", "release_network"), ) - err := m.networkManager.ReleaseAllocation(releaseNetworkCtx, networkAlloc) + if releaseTAPByID { + err = m.networkManager.ReleaseByInstanceID(releaseNetworkCtx, id) + } else { + err = m.networkManager.ReleaseAllocation(releaseNetworkCtx, networkAlloc) + } releaseNetworkSpanEnd(err) if err != nil { - // Log error but continue with cleanup + // The TAP reconciler deletes a TAP that no live instance claims. log.WarnContext(ctx, "failed to release network, continuing with cleanup", "instance_id", id, "error", err) } } @@ -173,15 +182,15 @@ func (m *manager) deleteInstanceWithOptions( if len(inst.Devices) > 0 && m.deviceManager != nil { for _, deviceID := range inst.Devices { log.DebugContext(ctx, "detaching device", "id", id, "device", deviceID) - // Mark device as detached - if err := m.deviceManager.MarkDetached(ctx, deviceID); err != nil { - log.WarnContext(ctx, "failed to mark device as detached", "id", id, "device", deviceID, "error", err) - } - // Auto-unbind from VFIO so native driver can reclaim it - log.InfoContext(ctx, "auto-unbinding device from VFIO", "id", id, "device", deviceID) - if err := m.deviceManager.UnbindFromVFIO(ctx, deviceID); err != nil { - // Log but continue - device might already be unbound or in use by another instance - log.WarnContext(ctx, "failed to unbind device from VFIO", "id", id, "device", deviceID, "error", err) + if err := m.deviceManager.ReleaseInstanceDevice(ctx, deviceID, id); err != nil { + if stored.ForkPending != nil && !errors.Is(err, devices.ErrNotFound) { + return fmt.Errorf("release fork PCI device %s: %w", deviceID, err) + } + log.WarnContext(ctx, "failed to release passthrough device", "instance_id", id, "device", deviceID, "error", err) + // Nothing retries the release once this instance is gone. + if err := m.deviceManager.DetachInstanceDevice(ctx, deviceID, id); err != nil && !errors.Is(err, devices.ErrNotFound) { + log.WarnContext(ctx, "failed to detach passthrough device", "instance_id", id, "device", deviceID, "error", err) + } } } } diff --git a/lib/instances/fork.go b/lib/instances/fork.go index 94e2a2132..4e42526da 100644 --- a/lib/instances/fork.go +++ b/lib/instances/fork.go @@ -7,7 +7,9 @@ import ( "fmt" "hash/crc32" "os" + "path/filepath" "strings" + "sync/atomic" "time" "github.com/kernel/hypeman/lib/guest" @@ -19,6 +21,7 @@ import ( "github.com/nrednav/cuid2" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" + "golang.org/x/sync/errgroup" "gvisor.dev/gvisor/pkg/cleanup" ) @@ -101,24 +104,8 @@ func (m *manager) forkInstance(ctx context.Context, id string, req ForkInstanceR } log.InfoContext(ctx, "restoring source instance after running fork", "source_instance_id", id) - restoredSource, restoreErr := m.restoreInstance(ctx, id) - - if restoreErr != nil { - if forkErr != nil { - return nil, "", false, fmt.Errorf("fork failed: %v; additionally failed to restore source instance: %w", forkErr, restoreErr) - } - return nil, "", false, fmt.Errorf("restore source instance after fork: %w", restoreErr) - } - if restoredSource != nil && !restoredSource.NetworkEnabled && (restoredSource.State == StateRunning || restoredSource.State == StateInitializing) { - if err := ensureGuestAgentReadyForForkPhase(ctx, &restoredSource.StoredMetadata, "after restoring running fork source"); err != nil { - if forkErr != nil { - return nil, "", false, fmt.Errorf("fork failed: %v; additionally restored source guest agent was not ready: %w", forkErr, err) - } - return nil, "", false, fmt.Errorf("wait for restored source guest agent readiness: %w", err) - } - } - if forkErr != nil { - return nil, "", false, forkErr + if err := m.restoreSourceAfterRunningFork(ctx, id, forked, forkErr); err != nil { + return nil, "", false, err } return forked, targetState, false, nil case StateStopped, StateStandby: @@ -132,6 +119,33 @@ func (m *manager) forkInstance(ctx context.Context, id string, req ForkInstanceR } } +// restoreSourceAfterRunningFork brings the source of a running fork back up. +// If it does not come back the request fails, so the fork it made is deleted +// instead of staying up under the requested name. +func (m *manager) restoreSourceAfterRunningFork(ctx context.Context, sourceID string, forked *Instance, forkErr error) error { + err := m.restoreRunningForkSource(ctx, sourceID) + if err == nil { + return forkErr + } + if forkErr != nil { + return fmt.Errorf("fork failed: %v; additionally failed to %w", forkErr, err) + } + return m.discardFork(ctx, forked.Id, err) +} + +func (m *manager) restoreRunningForkSource(ctx context.Context, sourceID string) error { + restoredSource, err := m.restoreInstance(ctx, sourceID) + if err != nil { + return fmt.Errorf("restore source instance after fork: %w", err) + } + if restoredSource != nil && !restoredSource.NetworkEnabled && (restoredSource.State == StateRunning || restoredSource.State == StateInitializing) { + if err := ensureGuestAgentReadyForForkPhase(ctx, &restoredSource.StoredMetadata, "after restoring running fork source"); err != nil { + return fmt.Errorf("wait for restored source guest agent readiness: %w", err) + } + } + return nil +} + func ensureGuestAgentReadyForRunningFork(ctx context.Context, source *StoredMetadata) error { return ensureGuestAgentReadyForForkPhase(ctx, source, "before running fork") } @@ -364,6 +378,7 @@ func (m *manager) forkInstanceFromStoppedOrStandby(ctx context.Context, id strin restoreNeedsSourceLock = prepareResult.RequiresSnapshotSourceAlias } + forkMeta.ForkPending = currentForkOwner() newMeta := &metadata{StoredMetadata: forkMeta} if err := m.saveForkMetadata(ctx, newMeta); err != nil { return nil, false, err @@ -561,12 +576,217 @@ func forkReturnNeedsGuestAgentReady(inst *Instance, guestReady bool) bool { return inst != nil && (inst.State == StateRunning || inst.State == StateInitializing) && !guestReady } +// completeFork clears the pending mark of a fork that reached its target +// state. The clear is synced to disk before the request succeeds: if a host +// crash undid it, the next start would delete a fork whose caller got a +// success. +func (m *manager) completeFork(inst *Instance) error { + lock := m.getInstanceLock(inst.Id) + lock.Lock() + defer lock.Unlock() + + meta, err := m.loadMetadata(inst.Id) + if err != nil { + return fmt.Errorf("load completed fork metadata: %w", err) + } + if pending := meta.ForkPending; pending != nil { + meta.ForkPending = nil + if err := m.saveMetadataDurably(meta); err != nil { + // The cleared metadata can already be in place. The request fails + // from here, so mark the fork again: if it cannot be deleted + // either, the next start still has to find it. + meta.ForkPending = pending + if markErr := m.saveMetadata(meta); markErr != nil { + return fmt.Errorf("save completed fork metadata: %w; additionally failed to mark the fork pending again: %v", err, markErr) + } + return fmt.Errorf("save completed fork metadata: %w", err) + } + } + inst.ForkPending = nil + return nil +} + +// ForkOwner identifies the API process that is making a fork, across PID reuse +// and host reboots. +type ForkOwner struct { + PID int `json:"pid"` + StartTime uint64 `json:"start_time,omitempty"` // from /proc//stat; 0 = unknown + BootID string `json:"boot_id,omitempty"` // Linux boot ID; empty = unknown +} + +func currentForkOwner() *ForkOwner { + pid := os.Getpid() + return &ForkOwner{PID: pid, StartTime: processStartTime(pid), BootID: hostBootID()} +} + +// gone reports whether the process that was making the fork no longer exists. +// When that cannot be told the owner counts as running, so a fork that another +// live API process is still working on is never deleted. +func (o ForkOwner) gone() bool { + if bootID := hostBootID(); o.BootID != "" && bootID != "" && o.BootID != bootID { + return true + } + if !ProcessExists(o.PID) { + return true + } + // The PID is in use. A different start time means it was recycled. + startTime := processStartTime(o.PID) + return o.StartTime != 0 && startTime != 0 && o.StartTime != startTime +} + +func (m *manager) forkOwnerGone(owner ForkOwner) bool { + if m.forkOwnerGoneFn != nil { + return m.forkOwnerGoneFn(owner) + } + return owner.gone() +} + +// Public boot requests must not take over a fork that can still be discarded. +// The fork's own start/restore transitions use refuseAbandonedFork instead. +func (m *manager) loadMetadataForBootRequest(id string) (*metadata, error) { + meta, err := m.loadMetadata(id) + if err != nil { + return nil, err + } + if meta.ForkPending == nil { + return meta, nil + } + if err := m.refuseAbandonedFork(&meta.StoredMetadata); err != nil { + return nil, err + } + return nil, fmt.Errorf("%w: fork request has not completed", ErrInvalidState) +} + +// refuseAbandonedFork keeps a fork that is waiting to be deleted from being +// brought up. Such a fork is still marked, so the next start deletes it, and +// until then it looks like any other instance under the name its caller asked +// for. A fork whose owner is still running is being made and passes. +func (m *manager) refuseAbandonedFork(stored *StoredMetadata) error { + if stored.ForkPending == nil || !m.forkOwnerGone(*stored.ForkPending) { + return nil + } + return fmt.Errorf("%w: instance is a fork whose request did not complete and is waiting to be deleted", ErrInvalidState) +} + +// abandonFork marks a fork that its own request failed to delete as having no +// owner, so it is refused like a fork interrupted by a restart. The zero +// ForkOwner names no process and always counts as gone. +func (m *manager) abandonFork(ctx context.Context, forkID string) { + lock := m.getInstanceLock(forkID) + lock.Lock() + defer lock.Unlock() + + meta, err := m.loadMetadata(forkID) + if err != nil { + return + } + meta.ForkPending = &ForkOwner{} + if err := m.saveMetadata(meta); err != nil { + logger.FromContext(ctx).WarnContext(ctx, "failed to mark undeleted fork as abandoned", "instance_id", forkID, "error", err) + } +} + +// interruptedForkMaxConcurrentDeletes bounds how many interrupted forks +// startup deletes at once. +const interruptedForkMaxConcurrentDeletes = 8 + +// RecoverInterruptedForks deletes the forks whose API process died before they +// reached their target state. Nothing else does: such a fork looks like an +// ordinary standby or paused instance, and a restore that was cut short keeps +// its VMM, its memory and its vGPU. Call it once at startup, before requests +// are served. +func (m *manager) RecoverInterruptedForks(ctx context.Context) { + log := logger.FromContext(ctx) + start := time.Now() + files, statErrs, err := m.walkMetadataFiles(nil) + if err != nil { + log.ErrorContext(ctx, "failed to list instances while recovering interrupted forks", "error", err) + return + } + if len(statErrs) > 0 { + log.WarnContext(ctx, "cannot tell whether some instances are interrupted forks: their metadata is unreadable", "error", errors.Join(statErrs...)) + } + // Each delete waits on its VMM to exit, and on its guest to shut down + // first when the guest holds a passthrough device. + var deletes errgroup.Group + deletes.SetLimit(interruptedForkMaxConcurrentDeletes) + var deleted, failed atomic.Int64 + ownerRunning := 0 + for _, file := range files { + id := filepath.Base(filepath.Dir(file)) + meta, err := m.loadMetadata(id) + if err != nil { + log.WarnContext(ctx, "cannot tell whether instance is an interrupted fork: its metadata is unreadable", "instance_id", id, "error", err) + continue + } + if meta.ForkPending == nil { + continue + } + owner := *meta.ForkPending + if !m.forkOwnerGone(owner) { + log.WarnContext(ctx, "not deleting pending fork: the process making it is still running", "instance_id", id, "instance_name", meta.Name, "owner_pid", owner.PID) + ownerRunning++ + m.recordInterruptedFork(ctx, "owner_running") + continue + } + // The owner may have finished the fork and exited since the mark was + // read. Now that it is gone the mark cannot change, so read it again. + meta, err = m.loadMetadata(id) + if err != nil { + if !errors.Is(err, ErrNotFound) { + log.WarnContext(ctx, "cannot tell whether instance is an interrupted fork: its metadata is unreadable", "instance_id", id, "error", err) + } + continue + } + if meta.ForkPending == nil || *meta.ForkPending != owner { + continue + } + name := meta.Name + // Nobody was given this guest, so it is shut down cleanly only when a + // passthrough device needs its driver unloaded. + options := DeleteInstanceOptions{SkipGracefulShutdown: !hasVFIODevices(&meta.StoredMetadata)} + deletes.Go(func() error { + if err := m.deleteFork(ctx, id, options); err != nil { + log.ErrorContext(ctx, "failed to delete interrupted fork; it stays until it is deleted", "instance_id", id, "instance_name", name, "error", err) + failed.Add(1) + m.recordInterruptedFork(ctx, "delete_failed") + return nil + } + log.WarnContext(ctx, "deleted fork interrupted by a restart", "instance_id", id, "instance_name", name) + deleted.Add(1) + m.recordInterruptedFork(ctx, "deleted") + return nil + }) + } + _ = deletes.Wait() + log.InfoContext(ctx, "recovered interrupted forks", "deleted", deleted.Load(), "failed", failed.Load(), "owner_running", ownerRunning, "duration", time.Since(start)) +} + +// discardFork deletes a fork whose request is failing with cause. +func (m *manager) discardFork(ctx context.Context, forkID string, cause error) error { + if err := m.cleanupForkInstanceOnError(ctx, forkID); err != nil { + return fmt.Errorf("%w; additionally failed to cleanup forked instance %s: %v", cause, forkID, err) + } + return cause +} + func (m *manager) cleanupForkInstanceOnError(ctx context.Context, forkID string) error { + err := m.deleteFork(ctx, forkID, DeleteInstanceOptions{}) + if err != nil { + m.abandonFork(ctx, forkID) + } + return err +} + +func (m *manager) deleteFork(ctx context.Context, forkID string, options DeleteInstanceOptions) error { + // The request may be failing because its caller went away. The fork must + // still be deleted, or it stays up marked until the next start. + ctx = context.WithoutCancel(ctx) lock := m.getInstanceLock(forkID) lock.Lock() defer lock.Unlock() - err := m.deleteInstance(ctx, forkID) + err := m.deleteInstanceWithOptions(ctx, forkID, options) if err == nil || errors.Is(err, ErrNotFound) { m.instanceLocks.Delete(forkID) return nil @@ -648,6 +868,10 @@ func cloneStoredMetadata(src StoredMetadata) StoredMetadata { gpuClaimedAt := *src.GPUClaimedAt dst.GPUClaimedAt = &gpuClaimedAt } + if src.ForkPending != nil { + forkPending := *src.ForkPending + dst.ForkPending = &forkPending + } if src.ExitCode != nil { exitCode := *src.ExitCode dst.ExitCode = &exitCode @@ -666,5 +890,8 @@ func cloneStoredMetadataWithoutPendingStandbyCompression(src StoredMetadata) Sto func cloneStoredMetadataForSnapshot(src StoredMetadata) StoredMetadata { dst := cloneStoredMetadataWithoutPendingStandbyCompression(src) dst.ExpiresAt = nil + // The mark belongs to the fork request, not to what is later made from + // a snapshot of its instance. + dst.ForkPending = nil return dst } diff --git a/lib/instances/fork_alias_recovery.go b/lib/instances/fork_alias_recovery.go new file mode 100644 index 000000000..ed663cf11 --- /dev/null +++ b/lib/instances/fork_alias_recovery.go @@ -0,0 +1,177 @@ +package instances + +import ( + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/kernel/hypeman/lib/hypervisor" + "github.com/kernel/hypeman/lib/hypervisor/firecracker" + "github.com/kernel/hypeman/lib/paths" +) + +// RecoverParkedForkSources puts back directories renamed by Firecracker's +// snapshot alias fallback and removes verified aliases whose sources no longer +// exist. A source it cannot recover is left exactly as it is and named in the +// returned error, and the rest are still recovered. Leaving one in place +// affects no other guest: the metadata loader rejects a directory holding +// another guest's metadata, so a link left at a source's path resolves to +// nothing. Call under the data directory lock, before listing instances. +func RecoverParkedForkSources(p *paths.Paths) error { + entries, err := os.ReadDir(p.GuestsDir()) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + var errs []error + backups := make(map[string]string) + ambiguous := make(map[string]bool) + for _, entry := range entries { + id, stamp, found := strings.Cut(entry.Name(), firecracker.ForkBackupSeparator) + if !found || !entry.IsDir() { + continue + } + if _, err := strconv.ParseUint(stamp, 10, 63); err != nil { + continue + } + if err := paths.ValidatePathComponent(id); err != nil { + errs = append(errs, fmt.Errorf("invalid source ID in backup %q", entry.Name())) + continue + } + if other, ok := backups[id]; ok { + errs = append(errs, fmt.Errorf("ambiguous backups for %q: %q and %q", id, other, entry.Name())) + ambiguous[id] = true + continue + } + backups[id] = entry.Name() + } + changed := false + for id, backup := range backups { + if ambiguous[id] { + continue + } + if err := restoreParkedForkSource(p, id, backup); err != nil { + errs = append(errs, fmt.Errorf("restore %s from %s: %w", id, backup, err)) + continue + } + changed = true + } + // A link whose source has a backup was handled above or is left with it. + for _, entry := range entries { + if entry.Type()&os.ModeSymlink == 0 || backups[entry.Name()] != "" { + continue + } + removed, err := removeUnparkedForkAlias(p, p.InstanceDir(entry.Name())) + if err != nil { + errs = append(errs, fmt.Errorf("remove source alias %s: %w", entry.Name(), err)) + continue + } + changed = changed || removed + } + if changed { + if err := syncDir(p.GuestsDir()); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +func removeUnparkedForkAlias(p *paths.Paths, source string) (bool, error) { + link, err := os.Readlink(source) + if err != nil { + return false, err + } + // Without a backup we need the target itself to prove this is a restore alias. + if err := verifyForkAlias(p, source, link, false); err != nil { + slog.Warn("leaving unverified source alias", "path", source, "error", err) + return false, nil + } + err = os.Remove(source) + return err == nil, err +} + +func restoreParkedForkSource(p *paths.Paths, id, backup string) error { + parked, err := readForkRecoveryMetadata(p, backup, id) + if err != nil { + return err + } + if parked.ForkPending != nil && !parked.ForkPending.gone() { + return fmt.Errorf("parked source has a live fork owner") + } + source := p.InstanceDir(id) + link, err := os.Readlink(source) + switch { + case err == nil: + if err := verifyForkAlias(p, source, link, true); err != nil { + return err + } + if err := os.Remove(source); err != nil { + return err + } + case os.IsNotExist(err): + // A kill before creating the link or after removing it leaves only the backup. + default: + // Never replace an ordinary source directory. + return fmt.Errorf("source path exists but is not an alias link: %w", err) + } + return os.Rename(p.InstanceDir(backup), source) +} + +func verifyForkAlias(p *paths.Paths, source, link string, allowDangling bool) error { + if !filepath.IsAbs(link) { + link = filepath.Join(p.GuestsDir(), link) + } + id := filepath.Base(link) + if link != p.InstanceDir(id) || link == source { + return fmt.Errorf("unexpected source alias target %q", link) + } + info, err := os.Lstat(link) + if allowDangling && os.IsNotExist(err) { + // The fork the link pointed at has been deleted, which an older + // binary allows. Nothing can be read through a link that dangles. + return nil + } + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("alias target %q is not a guest directory", link) + } + target, err := readForkRecoveryMetadata(p, id, id) + if err != nil { + return err + } + if target.HypervisorType != hypervisor.TypeFirecracker || (target.ForkPending != nil && !target.ForkPending.gone()) { + return fmt.Errorf("alias target %q is not an abandoned Firecracker restore", link) + } + recorded, err := firecracker.SnapshotSourceAlias(link) + if err != nil { + return err + } + if filepath.Clean(recorded) != source { + return fmt.Errorf("target records source %q, not %q", recorded, source) + } + return nil +} + +func readForkRecoveryMetadata(p *paths.Paths, dirID, expectedID string) (*StoredMetadata, error) { + data, err := os.ReadFile(p.InstanceMetadata(dirID)) + if err != nil { + return nil, err + } + var meta StoredMetadata + if err := json.Unmarshal(data, &meta); err != nil { + return nil, err + } + if meta.Id != expectedID { + return nil, fmt.Errorf("metadata in %q names %q, expected %q", dirID, meta.Id, expectedID) + } + return &meta, nil +} diff --git a/lib/instances/fork_pending_linux_test.go b/lib/instances/fork_pending_linux_test.go new file mode 100644 index 000000000..2f30dd4e5 --- /dev/null +++ b/lib/instances/fork_pending_linux_test.go @@ -0,0 +1,66 @@ +//go:build linux + +package instances + +import ( + "context" + "syscall" + "testing" + "time" + + "github.com/kernel/hypeman/lib/hypervisor" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A PID alone does not identify the process that was making a fork: it is +// handed out again after the process exits, and after a reboot. +func TestForkOwnerIsGoneWhenItsPIDBelongsToAnotherProcess(t *testing.T) { + current := *currentForkOwner() + require.NotZero(t, current.StartTime) + require.NotEmpty(t, current.BootID) + + recycled := current + recycled.StartTime++ + assert.True(t, recycled.gone(), "same PID, started at another time") + + beforeReboot := current + beforeReboot.BootID = "00000000-0000-0000-0000-000000000000" + assert.True(t, beforeReboot.gone(), "same PID and start time, recorded in an earlier boot") +} + +// Nobody was given an interrupted fork, and the API does not listen until +// recovery returns, so recovery waits for a guest to shut down only when a +// passthrough device needs it to. +func TestRecoverInterruptedForksShutsDownOnlyGuestsWithPassthroughDevices(t *testing.T) { + for _, tc := range []struct { + name string + devices []string + shutdowns int + }{ + {"no device", nil, 0}, + {"passthrough device", []string{"dev-1"}, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + m.deviceManager = &recordingDeviceManager{} + pid, identity := startTrapProcess(t, "exit 0") + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.HypervisorProcessIdentity = identity + meta.Devices = tc.devices + meta.ForkPending = exitedProcessOwner(t) + require.NoError(t, m.saveMetadata(meta)) + shutdowns := 0 + m.shutdownGuestFn = func(context.Context, hypervisor.VsockDialer, int32) error { + shutdowns++ + return syscall.Kill(pid, syscall.SIGKILL) + } + + m.RecoverInterruptedForks(t.Context()) + assert.Equal(t, tc.shutdowns, shutdowns) + assert.False(t, ProcessExists(pid)) + assert.NoDirExists(t, m.paths.InstanceDir(id)) + }) + } +} diff --git a/lib/instances/fork_pending_test.go b/lib/instances/fork_pending_test.go new file mode 100644 index 000000000..deb64d812 --- /dev/null +++ b/lib/instances/fork_pending_test.go @@ -0,0 +1,470 @@ +package instances + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "log/slog" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/kernel/hypeman/lib/devices" + "github.com/kernel/hypeman/lib/forkvm" + "github.com/kernel/hypeman/lib/hypervisor" + "github.com/kernel/hypeman/lib/logger" + snapshotstore "github.com/kernel/hypeman/lib/snapshot" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + otelmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/metric/metricdata" +) + +// exitedProcessOwner names a process that has already exited, the way a fork +// names the API process that crashed while making it. +func exitedProcessOwner(t *testing.T) *ForkOwner { + t.Helper() + process := exec.Command("true") + require.NoError(t, process.Start()) + owner := &ForkOwner{PID: process.Process.Pid, StartTime: processStartTime(process.Process.Pid), BootID: hostBootID()} + require.NoError(t, process.Wait()) + return owner +} + +func TestForkIsPendingOnlyUntilItsRequestSucceeds(t *testing.T) { + mgr, _ := setupTestManager(t) + ctx := context.Background() + + sourceID := "fork-pending-source" + createStoppedSnapshotSourceFixture(t, mgr, sourceID, sourceID, mgr.defaultHypervisor) + + // What a crash between saving the fork and finishing it leaves behind. + interrupted, _, err := mgr.forkInstanceFromStoppedOrStandby(ctx, sourceID, ForkInstanceRequest{Name: "fork-pending-interrupted"}, false) + require.NoError(t, err) + stored, err := mgr.loadMetadata(interrupted.Id) + require.NoError(t, err) + require.NotNil(t, stored.ForkPending) + assert.Equal(t, os.Getpid(), stored.ForkPending.PID, "the mark must name the process making the fork") + + // A snapshot of it must not pass the mark on to what is restored from it. + ofInterrupted, err := mgr.CreateSnapshot(ctx, interrupted.Id, CreateSnapshotRequest{Kind: SnapshotKindStopped, Name: "fork-pending-of-interrupted"}) + require.NoError(t, err) + record, err := mgr.loadSnapshotRecord(ofInterrupted.Id) + require.NoError(t, err) + assert.Nil(t, record.StoredMetadata.ForkPending) + // A restore cut short leaves the payload's copy as the instance's metadata. + data, err := os.ReadFile(filepath.Join(mgr.paths.SnapshotGuestDir(ofInterrupted.Id), "metadata.json")) + require.NoError(t, err) + var copied metadata + require.NoError(t, json.Unmarshal(data, &copied)) + assert.Equal(t, interrupted.Id, copied.Id) + assert.Nil(t, copied.ForkPending) + + fromInstance, err := mgr.ForkInstance(ctx, sourceID, ForkInstanceRequest{Name: "fork-pending-from-instance"}) + require.NoError(t, err) + snapshot, err := mgr.CreateSnapshot(ctx, sourceID, CreateSnapshotRequest{Kind: SnapshotKindStopped, Name: "fork-pending-snapshot"}) + require.NoError(t, err) + fromSnapshot, err := mgr.ForkSnapshot(ctx, snapshot.Id, ForkSnapshotRequest{Name: "fork-pending-from-snapshot", TargetState: StateStopped}) + require.NoError(t, err) + + for _, fork := range []*Instance{fromInstance, fromSnapshot} { + assert.Nil(t, fork.ForkPending, fork.Name) + stored, err := mgr.loadMetadata(fork.Id) + require.NoError(t, err) + assert.Nil(t, stored.ForkPending, fork.Name) + } +} + +func TestRecoverInterruptedForksDeletesOnlyForksWhoseProcessIsGone(t *testing.T) { + mgr, _ := setupTestManager(t) + ctx := context.Background() + + save := func(id string, pending *ForkOwner) { + require.NoError(t, mgr.ensureDirectories(id)) + now := time.Now() + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: id, + Name: id, + Image: integrationTestImageRef(t, "docker.io/library/alpine:latest"), + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + HypervisorVersion: "test", + SocketPath: mgr.paths.InstanceSocket(id, "cloud-hypervisor.sock"), + DataDir: mgr.paths.InstanceDir(id), + VsockCID: generateVsockCID(id), + VsockSocket: mgr.paths.InstanceVsockSocket(id), + ForkPending: pending, + }})) + } + save("fork-recover-interrupted", exitedProcessOwner(t)) + // Another API process on the same data directory is still making this one. + save("fork-recover-in-flight", currentForkOwner()) + save("fork-recover-finished", nil) + // Whether these two are interrupted forks cannot be told. A + // self-referential symlink fails stat with ELOOP, for root too. + require.NoError(t, mgr.ensureDirectories("fork-recover-no-stat")) + noStat := mgr.paths.InstanceMetadata("fork-recover-no-stat") + require.NoError(t, os.Symlink(filepath.Base(noStat), noStat)) + require.NoError(t, mgr.ensureDirectories("fork-recover-corrupt")) + require.NoError(t, os.WriteFile(mgr.paths.InstanceMetadata("fork-recover-corrupt"), []byte("{"), 0o644)) + + reader := otelmetric.NewManualReader() + metrics, err := newInstanceMetrics(otelmetric.NewMeterProvider(otelmetric.WithReader(reader)).Meter("test"), nil, mgr) + require.NoError(t, err) + mgr.metrics = metrics + + var logs bytes.Buffer + mgr.RecoverInterruptedForks(logger.AddToContext(ctx, slog.New(slog.NewTextHandler(&logs, nil)))) + + _, err = mgr.loadMetadata("fork-recover-interrupted") + require.ErrorIs(t, err, ErrNotFound) + assert.NoDirExists(t, mgr.paths.InstanceDir("fork-recover-interrupted")) + + inFlight, err := mgr.loadMetadata("fork-recover-in-flight") + require.NoError(t, err, "a fork whose process is still running must be left alone") + assert.NotNil(t, inFlight.ForkPending) + + _, err = mgr.loadMetadata("fork-recover-finished") + require.NoError(t, err) + + assert.Contains(t, logs.String(), "deleted=1 failed=0 owner_running=1") + for _, id := range []string{"fork-recover-no-stat", "fork-recover-corrupt"} { + assert.DirExists(t, mgr.paths.InstanceDir(id)) + assert.Contains(t, logs.String(), id, "an instance recovery cannot read must be logged") + } + + var rm metricdata.ResourceMetrics + require.NoError(t, reader.Collect(ctx, &rm)) + counted, ok := findMetric(t, rm, "hypeman_instances_interrupted_forks_total").Data.(metricdata.Sum[int64]) + require.True(t, ok) + byStatus := map[string]int64{} + for _, point := range counted.DataPoints { + byStatus[metricLabel(t, point.Attributes, "status")] = point.Value + } + assert.Equal(t, map[string]int64{"deleted": 1, "owner_running": 1}, byStatus) +} + +// A directory sync can take as long as the disk does. A restore waiting to +// alias a source directory must not wait on it: while it waits, no metadata +// on the host can be read. +func TestDurableMetadataSaveSyncsWithoutAliasLock(t *testing.T) { + mgr, _ := setupTestManager(t) + + id := "fork-sync-unlocked" + createStoppedSnapshotSourceFixture(t, mgr, id, id, mgr.defaultHypervisor) + meta, err := mgr.loadMetadata(id) + require.NoError(t, err) + + aliased := false + mgr.syncDirFn = func(dir *os.File) error { + taken := make(chan struct{}) + go func() { + hypervisor.LockSnapshotSourceAliasMutation()() + close(taken) + }() + select { + case <-taken: + aliased = true + case <-time.After(5 * time.Second): + } + return dir.Sync() + } + + require.NoError(t, mgr.saveMetadataDurably(meta)) + assert.True(t, aliased, "the alias lock was held across the directory sync") +} + +// Clearing the mark is synced to disk, so a host crash cannot undo it after +// the caller got a success. If it cannot be synced the request fails and the +// fork is deleted. A fork that is not deleted is still marked. +func TestForkFailsWhenClearingItsMarkCannotBeSynced(t *testing.T) { + mgr, _ := setupTestManager(t) + ctx := context.Background() + + sourceID := "fork-sync-source" + createStoppedSnapshotSourceFixture(t, mgr, sourceID, sourceID, mgr.defaultHypervisor) + var synced string + mgr.syncDirFn = func(dir *os.File) error { + synced = dir.Name() + return errors.New("sync failed") + } + + _, err := mgr.ForkInstance(ctx, sourceID, ForkInstanceRequest{Name: "fork-sync-copy"}) + require.ErrorContains(t, err, "save completed fork metadata") + + require.NotEmpty(t, synced, "the fork's directory must be synced") + assert.NoDirExists(t, synced) + + // The cleared metadata is already in place when the sync fails. + kept, _, err := mgr.forkInstanceFromStoppedOrStandby(ctx, sourceID, ForkInstanceRequest{Name: "fork-sync-kept"}, false) + require.NoError(t, err) + require.ErrorContains(t, mgr.completeFork(kept), "save completed fork metadata") + stored, err := mgr.loadMetadata(kept.Id) + require.NoError(t, err) + assert.Equal(t, currentForkOwner(), stored.ForkPending) +} + +// contextRecordingDeviceManager records whether the context a device release +// ran with had been cancelled. +type contextRecordingDeviceManager struct { + devices.Manager + released chan error +} + +func (m contextRecordingDeviceManager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error { + m.released <- ctx.Err() + return nil +} + +// A fork request often fails because its caller went away, which cancels its +// context. The fork must be deleted all the same. +func TestFailedForkIsDeletedAfterItsRequestIsCancelled(t *testing.T) { + mgr, _ := setupTestManager(t) + + recorder := contextRecordingDeviceManager{released: make(chan error, 1)} + mgr.deviceManager = recorder + + id := "fork-cancelled-request" + require.NoError(t, mgr.ensureDirectories(id)) + now := time.Now() + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: id, + Name: id, + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + SocketPath: mgr.paths.InstanceSocket(id, "cloud-hypervisor.sock"), + DataDir: mgr.paths.InstanceDir(id), + Devices: []string{id}, + ForkPending: currentForkOwner(), + }})) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + cause := errors.New("caller went away") + require.Equal(t, cause, mgr.discardFork(ctx, id, cause)) + + require.NoError(t, <-recorder.released, "the delete ran with the cancelled request context") + assert.NoDirExists(t, mgr.paths.InstanceDir(id)) +} + +// A copy cut short before the fork saved its own metadata leaves the source's +// in the fork's directory. Recovery must not delete by it: that metadata names +// the source's guest and what the source holds. +func TestRecoverInterruptedForksLeavesDirectoryHoldingAnotherInstancesMetadata(t *testing.T) { + mgr, _ := setupTestManager(t) + + // The source names itself as its device, so the gate sees a delete that goes by its metadata. + gate := detachGateDeviceManager{arrived: make(chan string, 1), release: make(chan struct{})} + close(gate.release) + mgr.deviceManager = gate + + sourceID := "fork-recover-copied-source" + require.NoError(t, mgr.ensureDirectories(sourceID)) + now := time.Now() + source := &metadata{StoredMetadata: StoredMetadata{ + Id: sourceID, + Name: sourceID, + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + SocketPath: mgr.paths.InstanceSocket(sourceID, "cloud-hypervisor.sock"), + DataDir: mgr.paths.InstanceDir(sourceID), + Devices: []string{sourceID}, + ForkPending: exitedProcessOwner(t), + }} + require.NoError(t, mgr.saveMetadata(source)) + // The source was itself a fork still pending when it was copied, and has finished since. + copyID := "fork-recover-copied" + require.NoError(t, forkvm.CopyGuestDirectory(mgr.paths.InstanceDir(sourceID), mgr.paths.InstanceDir(copyID))) + source.ForkPending = nil + require.NoError(t, mgr.saveMetadata(source)) + + var logs bytes.Buffer + mgr.RecoverInterruptedForks(logger.AddToContext(context.Background(), slog.New(slog.NewTextHandler(&logs, nil)))) + + assert.Empty(t, gate.arrived, "recovery detached the source's device") + assert.DirExists(t, mgr.paths.InstanceDir(copyID)) + assert.Contains(t, logs.String(), "deleted=0 failed=0 owner_running=0") +} + +// The process making a fork can finish it and exit after recovery read its +// mark. Recovery must go by the mark as it is once that process is gone. +func TestRecoverInterruptedForksKeepsForkFinishedSinceItsMarkWasRead(t *testing.T) { + mgr, _ := setupTestManager(t) + + id := "fork-recover-just-finished" + require.NoError(t, mgr.ensureDirectories(id)) + now := time.Now() + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: id, + Name: id, + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + SocketPath: mgr.paths.InstanceSocket(id, "cloud-hypervisor.sock"), + DataDir: mgr.paths.InstanceDir(id), + ForkPending: exitedProcessOwner(t), + }})) + mgr.forkOwnerGoneFn = func(owner ForkOwner) bool { + // Recovery has read the mark. The owner now clears it and exits. + stored, err := mgr.loadMetadata(id) + require.NoError(t, err) + stored.ForkPending = nil + require.NoError(t, mgr.saveMetadata(stored)) + return owner.gone() + } + + mgr.RecoverInterruptedForks(context.Background()) + + stored, err := mgr.loadMetadata(id) + require.NoError(t, err, "a fork that finished must not be deleted") + assert.Nil(t, stored.ForkPending) +} + +// A compression job that ends just as a fork completes must not save a copy +// of the metadata it read before the mark was cleared. +func TestCompressionJobLeavesLockedInstanceMetadataAlone(t *testing.T) { + mgr, _ := setupTestManager(t) + + id := "fork-pending-compressing" + require.NoError(t, mgr.ensureDirectories(id)) + now := time.Now() + policy := snapshotstore.SnapshotCompressionConfig{Enabled: true, Algorithm: snapshotstore.SnapshotCompressionAlgorithmZstd} + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: id, + Name: id, + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + DataDir: mgr.paths.InstanceDir(id), + ForkPending: currentForkOwner(), + PendingStandbyCompression: &PendingStandbyCompression{Policy: policy, NotBefore: now}, + }})) + target := compressionTarget{ + Key: mgr.snapshotJobKeyForInstance(id), + OwnerID: id, + SnapshotDir: t.TempDir(), // nothing to compress: the job ends at once + Source: snapshotCompressionSourceStandby, + Policy: policy, + } + runJob := func() { + mgr.startCompressionJob(context.Background(), target) + require.NoError(t, mgr.waitCompressionJobContext(context.Background(), target.Key)) + } + + // completeFork holds this lock while it clears the mark. + lock := mgr.getInstanceLock(id) + lock.Lock() + runJob() + stored, err := mgr.loadMetadata(id) + lock.Unlock() + require.NoError(t, err) + assert.NotNil(t, stored.PendingStandbyCompression, "the job wrote metadata while the instance was locked") + + runJob() + stored, err = mgr.loadMetadata(id) + require.NoError(t, err) + assert.Nil(t, stored.PendingStandbyCompression) + assert.NotNil(t, stored.ForkPending) +} + +// detachGateDeviceManager holds every device detach until release is closed, +// reporting each one that arrives. +type detachGateDeviceManager struct { + devices.Manager + arrived chan string + release chan struct{} +} + +func (m detachGateDeviceManager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error { + m.arrived <- deviceID + <-m.release + return nil +} + +// A restart that interrupts a burst of forks must not delete them one at a +// time: the API does not listen until recovery returns. +func TestRecoverInterruptedForksDeletesConcurrently(t *testing.T) { + mgr, _ := setupTestManager(t) + + // Each fork names itself as its device, so the gate sees which delete it holds. + forks := []string{"fork-recover-burst-1", "fork-recover-burst-2", "fork-recover-burst-3"} + gate := detachGateDeviceManager{arrived: make(chan string, len(forks)), release: make(chan struct{})} + mgr.deviceManager = gate + + owner := exitedProcessOwner(t) + for _, id := range forks { + require.NoError(t, mgr.ensureDirectories(id)) + now := time.Now() + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: id, + Name: id, + CreatedAt: now, + StoppedAt: &now, + HypervisorType: hypervisor.TypeCloudHypervisor, + SocketPath: mgr.paths.InstanceSocket(id, "cloud-hypervisor.sock"), + DataDir: mgr.paths.InstanceDir(id), + Devices: []string{id}, + ForkPending: owner, + }})) + } + + recovered := make(chan struct{}) + go func() { + defer close(recovered) + mgr.RecoverInterruptedForks(context.Background()) + }() + + var inFlight []string + for range forks { + select { + case id := <-gate.arrived: + inFlight = append(inFlight, id) + case <-time.After(5 * time.Second): + close(gate.release) + <-recovered + t.Fatalf("deletes of %v did not overlap: only %v started", forks, inFlight) + } + } + close(gate.release) + <-recovered + + assert.ElementsMatch(t, forks, inFlight) + for _, id := range forks { + assert.NoDirExists(t, mgr.paths.InstanceDir(id)) + } +} + +// The caller of a running fork gets an error when its source does not come +// back, so the fork must not stay behind under the name it asked for. +func TestRunningForkIsDeletedWhenItsSourceDoesNotComeBack(t *testing.T) { + mgr, _ := setupTestManager(t) + ctx := context.Background() + + // A stopped source has nothing to restore from. + sourceID := "fork-source-not-restored" + createStoppedSnapshotSourceFixture(t, mgr, sourceID, sourceID, mgr.defaultHypervisor) + forked, _, err := mgr.forkInstanceFromStoppedOrStandby(ctx, sourceID, ForkInstanceRequest{Name: "fork-source-not-restored-copy"}, false) + require.NoError(t, err) + + err = mgr.restoreSourceAfterRunningFork(ctx, sourceID, forked, nil) + require.ErrorContains(t, err, "restore source instance after fork") + + _, err = mgr.loadMetadata(forked.Id) + require.ErrorIs(t, err, ErrNotFound) + assert.NoDirExists(t, mgr.paths.InstanceDir(forked.Id)) + _, err = mgr.loadMetadata(sourceID) + require.NoError(t, err) +} + +func TestForkOwnerIsGoneOnlyWhenItsProcessIs(t *testing.T) { + assert.False(t, currentForkOwner().gone(), "a running process") + assert.True(t, exitedProcessOwner(t).gone(), "an exited process") + // Without a start time or boot ID a live PID is all there is to go by. + assert.False(t, ForkOwner{PID: os.Getpid()}.gone(), "a live PID with nothing else recorded") +} diff --git a/lib/instances/fork_recovery_guards_test.go b/lib/instances/fork_recovery_guards_test.go new file mode 100644 index 000000000..de741ae11 --- /dev/null +++ b/lib/instances/fork_recovery_guards_test.go @@ -0,0 +1,401 @@ +package instances + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/kernel/hypeman/lib/devices" + "github.com/kernel/hypeman/lib/forkvm" + "github.com/kernel/hypeman/lib/hypervisor" + "github.com/kernel/hypeman/lib/network" + "github.com/stretchr/testify/require" +) + +func TestRecoveryLeavesInheritedPCIDeviceWithOwner(t *testing.T) { + m, _ := setupTestManager(t) + const owner, fork, dev = "source", "interrupted", "dev-1" + createStoppedSnapshotSourceFixture(t, m, fork, fork, m.defaultHypervisor) + meta, err := m.loadMetadata(fork) + require.NoError(t, err) + meta.ForkPending = exitedProcessOwner(t) + meta.Devices = []string{dev} + require.NoError(t, m.saveMetadata(meta)) + data := writeAttachedTestDevice(t, m, dev, owner) + + m.RecoverInterruptedForks(t.Context()) + require.NoDirExists(t, m.paths.InstanceDir(fork)) + after, err := os.ReadFile(m.paths.DeviceMetadata(dev)) + require.NoError(t, err) + require.JSONEq(t, string(data), string(after)) +} + +func writeAttachedTestDevice(t *testing.T, m *manager, dev, owner string) []byte { + t.Helper() + data, err := json.Marshal(devices.Device{Id: dev, AttachedTo: &owner, BoundToVFIO: true, PCIAddress: "test-device"}) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(m.paths.DeviceDir(dev), 0755)) + require.NoError(t, os.WriteFile(m.paths.DeviceMetadata(dev), data, 0644)) + return data +} + +type busyDevice struct{ devices.Manager } + +func (busyDevice) ReleaseInstanceDevice(context.Context, string, string) error { + return errors.New("device busy") +} + +// Nothing retries a release for an instance that is gone, and a device still +// attached to it cannot be given to another instance until the next start. +func TestDeleteFreesPCIDeviceWhenReleaseFails(t *testing.T) { + m, _ := setupTestManager(t) + const id, dev = "deleted", "dev-1" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.Devices = []string{dev} + require.NoError(t, m.saveMetadata(meta)) + writeAttachedTestDevice(t, m, dev, id) + m.deviceManager = busyDevice{m.deviceManager} + + require.NoError(t, m.deleteInstance(t.Context(), id)) + device, err := m.deviceManager.GetDevice(t.Context(), dev) + require.NoError(t, err) + require.Nil(t, device.AttachedTo) +} + +func TestRecoveryKeepsForkWhenPCIReleaseFails(t *testing.T) { + m, _ := setupTestManager(t) + const id = "pending-pci" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = exitedProcessOwner(t) + meta.Devices = []string{"dev-1"} + require.NoError(t, m.saveMetadata(meta)) + m.deviceManager = busyDevice{m.deviceManager} + + m.RecoverInterruptedForks(t.Context()) + got, err := m.loadMetadata(id) + require.NoError(t, err) + require.Equal(t, meta.ForkPending, got.ForkPending) +} + +func TestRecoveryRemovesOnlyVerifiedAliasesWithoutBackup(t *testing.T) { + m, _ := setupTestManager(t) + const source, fork = "deleted-source", "completed-fork" + createStoppedSnapshotSourceFixture(t, m, fork, fork, m.defaultHypervisor) + meta, err := m.loadMetadata(fork) + require.NoError(t, err) + meta.HypervisorType = hypervisor.TypeFirecracker + require.NoError(t, m.saveMetadata(meta)) + sourceDir, forkDir := m.paths.InstanceDir(source), m.paths.InstanceDir(fork) + data, err := json.Marshal(map[string]string{"snapshot_source_data_dir": sourceDir}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(forkDir, "firecracker-config.json"), data, 0644)) + require.NoError(t, os.Symlink(forkDir, sourceDir)) + // This unverified link is also an ID prefix of the fork. The exact lookup + // must not fall through to prefix resolution. + other := m.paths.InstanceDir("completed") + require.NoError(t, os.Symlink(forkDir, other)) + require.NoError(t, RecoverParkedForkSources(m.paths)) + require.NoError(t, RecoverParkedForkSources(m.paths)) + _, err = os.Lstat(sourceDir) + require.ErrorIs(t, err, os.ErrNotExist) + target, err := os.Readlink(other) + require.NoError(t, err) + require.Equal(t, forkDir, target) + for _, id := range []string{source, "completed"} { + _, err := m.GetInstance(t.Context(), id) + require.ErrorIs(t, err, ErrNotFound) + } + got, err := m.GetInstance(t.Context(), fork) + require.NoError(t, err) + require.Equal(t, fork, got.Id) +} + +func TestForkCopyOmitsSourceMetadata(t *testing.T) { + m, _ := setupTestManager(t) + const source, fork = "source", "fork" + createStoppedSnapshotSourceFixture(t, m, source, source, m.defaultHypervisor) + require.NoError(t, m.cloneGuestDirectoryForFork(t.Context(), m.paths.InstanceDir(source), m.paths.InstanceDir(fork), false)) + require.FileExists(t, m.paths.InstanceOverlay(fork)) + require.NoFileExists(t, m.paths.InstanceMetadata(fork)) +} + +func TestTTLReaperSkipsForeignMetadata(t *testing.T) { + m, _ := setupTestManager(t) + const source, fork = "source", "partial-copy" + past, future := time.Now().Add(-time.Hour), time.Now().Add(time.Hour) + meta := &metadata{StoredMetadata: StoredMetadata{Id: source, ExpiresAt: &past}} + require.NoError(t, m.ensureDirectories(source)) + require.NoError(t, m.saveMetadata(meta)) + // Older fork copies can still contain the source's previous TTL. + require.NoError(t, forkvm.CopyGuestDirectory(m.paths.InstanceDir(source), m.paths.InstanceDir(fork))) + meta.ExpiresAt = &future + require.NoError(t, m.saveMetadata(meta)) + + var deletes []string + m.deleteInstanceFn = func(_ context.Context, id string) error { + deletes = append(deletes, id) + return nil + } + m.reapExpiredInstances(t.Context()) + require.Empty(t, deletes) +} + +type forkTAPRelease struct { + network.Manager + ids []string + err error +} + +func (r *forkTAPRelease) ReleaseByInstanceID(_ context.Context, id string) error { + r.ids = append(r.ids, id) + return r.err +} + +func createPendingForkWithoutAllocation(t *testing.T, m *manager, fork string) { + t.Helper() + createStoppedSnapshotSourceFixture(t, m, fork, fork, m.defaultHypervisor) + meta, err := m.loadMetadata(fork) + require.NoError(t, err) + meta.NetworkEnabled = true + meta.ForkPending = exitedProcessOwner(t) + require.NoError(t, m.saveMetadata(meta)) + alloc, err := m.networkManager.GetAllocation(t.Context(), fork) + require.NoError(t, err) + require.Nil(t, alloc) +} + +// The TAP reconciler deletes a TAP that no live instance claims, so a fork is +// not kept for one that could not be released. +func TestRecoveryDeletesForkWhenTAPReleaseFails(t *testing.T) { + m, _ := setupTestManager(t) + const fork = "fork-no-allocation" + createPendingForkWithoutAllocation(t, m, fork) + release := &forkTAPRelease{Manager: m.networkManager, err: errors.New("TAP busy")} + m.networkManager = release + + m.RecoverInterruptedForks(t.Context()) + require.Equal(t, []string{fork}, release.ids) + require.NoDirExists(t, m.paths.InstanceDir(fork)) +} + +func TestRestoreSnapshotCannotReplacePendingFork(t *testing.T) { + m, _ := setupTestManager(t) + const id = "pending" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = currentForkOwner() + require.NoError(t, m.saveMetadata(meta)) + snap, err := m.CreateSnapshot(t.Context(), id, CreateSnapshotRequest{Kind: SnapshotKindStopped}) + require.NoError(t, err) + keep := filepath.Join(m.paths.InstanceDir(id), "written-after-snapshot") + require.NoError(t, os.WriteFile(keep, nil, 0644)) + + _, err = m.RestoreSnapshot(t.Context(), id, snap.Id, RestoreSnapshotRequest{}) + require.ErrorIs(t, err, ErrInvalidState) + require.FileExists(t, keep) + got, err := m.loadMetadata(id) + require.NoError(t, err) + require.Equal(t, meta.ForkPending, got.ForkPending) +} + +func TestSnapshotPayloadNeverCopiesPendingMark(t *testing.T) { + m, _ := setupTestManager(t) + const id = "pending" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = currentForkOwner() + require.NoError(t, m.saveMetadata(meta)) + // Stop the copy after the walk has visited metadata.json. + require.NoError(t, syscall.Mkfifo(filepath.Join(m.paths.InstanceDir(id), "zz-fifo"), 0600)) + dst := t.TempDir() + require.ErrorContains(t, m.copySnapshotPayload(id, dst), "unsupported file type") + require.NoFileExists(t, filepath.Join(dst, "metadata.json")) +} + +func TestRecoveryRestoresParkedFirecrackerSource(t *testing.T) { + for _, layout := range []string{"link", "source-absent", "dangling-link", "unrelated-link", "live-owner", "existing-directory", "two-backups"} { + t.Run(layout, func(t *testing.T) { + m, _ := setupTestManager(t) + const source, fork = "original", "interrupted" + for _, id := range []string{source, fork} { + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + } + meta, err := m.loadMetadata(fork) + require.NoError(t, err) + meta.HypervisorType = hypervisor.TypeFirecracker + meta.ForkPending = exitedProcessOwner(t) + if layout == "live-owner" { + meta.ForkPending = currentForkOwner() + } + require.NoError(t, m.saveMetadata(meta)) + sourceDir, forkDir := m.paths.InstanceDir(source), m.paths.InstanceDir(fork) + recorded := sourceDir + if layout == "unrelated-link" { + recorded = m.paths.InstanceDir("other") + } + data, err := json.Marshal(map[string]string{"snapshot_source_data_dir": recorded}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(forkDir, "firecracker-config.json"), data, 0644)) + + backup := sourceDir + ".fork-bak.123" + require.NoError(t, os.Rename(sourceDir, backup)) + switch layout { + case "source-absent": + case "existing-directory": + require.NoError(t, os.Mkdir(sourceDir, 0755)) + default: + require.NoError(t, os.Symlink(forkDir, sourceDir)) + } + if layout == "dangling-link" { + // The fork was deleted by a binary that does not recover the link. + require.NoError(t, os.RemoveAll(forkDir)) + } + if layout == "two-backups" { + require.NoError(t, os.Mkdir(sourceDir+".fork-bak.124", 0755)) + } + err = RecoverParkedForkSources(m.paths) + if layout != "link" && layout != "source-absent" && layout != "dangling-link" { + require.Error(t, err) + require.DirExists(t, backup) + require.DirExists(t, forkDir) + if layout == "existing-directory" { + require.ErrorContains(t, err, "is not an alias link") + require.NoFileExists(t, m.paths.InstanceMetadata(source)) + } else { + link, err := os.Readlink(sourceDir) + require.NoError(t, err) + require.Equal(t, forkDir, link) + } + return + } + require.NoError(t, err) + require.NoError(t, RecoverParkedForkSources(m.paths), "repeat startup") + m.RecoverInterruptedForks(t.Context()) + got, err := m.loadMetadata(source) + require.NoError(t, err) + require.Equal(t, source, got.Id) + require.NoDirExists(t, backup) + require.NoDirExists(t, forkDir) + }) + } +} + +// An older fork copy cut short before the fork saved its own metadata holds +// the source's. It cannot have a VMM, so it must not fail the listing that +// vGPU claims and reconciles depend on, whether or not its source still exists. +func TestReconcileListingSkipsDirectoryHoldingAnotherInstancesMetadata(t *testing.T) { + m, _ := setupTestManager(t) + const source, deleted = "source", "deleted-source" + for _, id := range []string{source, deleted} { + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + require.NoError(t, forkvm.CopyGuestDirectory(m.paths.InstanceDir(id), m.paths.InstanceDir(id+"-copy"))) + } + require.NoError(t, os.RemoveAll(m.paths.InstanceDir(deleted))) + + listed, err := m.listMetadataForReconcile() + require.NoError(t, err) + require.Len(t, listed, 1) + require.Equal(t, source, listed[0].Id) +} + +// One source that cannot be recovered must not keep the others parked. +func TestParkedSourceRecoveryGoesOnPastASourceItRefuses(t *testing.T) { + m, _ := setupTestManager(t) + const refused, parked, fork = "refused", "parked", "interrupted" + for _, id := range []string{refused, parked, fork} { + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + } + meta, err := m.loadMetadata(fork) + require.NoError(t, err) + meta.HypervisorType = hypervisor.TypeFirecracker + meta.ForkPending = exitedProcessOwner(t) + require.NoError(t, m.saveMetadata(meta)) + forkDir := m.paths.InstanceDir(fork) + data, err := json.Marshal(map[string]string{"snapshot_source_data_dir": m.paths.InstanceDir(parked)}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(forkDir, "firecracker-config.json"), data, 0644)) + + for _, id := range []string{refused, parked} { + dir := m.paths.InstanceDir(id) + require.NoError(t, os.Rename(dir, dir+".fork-bak.123")) + require.NoError(t, os.Symlink(forkDir, dir)) + } + // The fork records only one of them as its source. + refusedDir := m.paths.InstanceDir(refused) + + err = RecoverParkedForkSources(m.paths) + require.ErrorContains(t, err, "restore "+refused) + require.NotContains(t, err.Error(), "restore "+parked) + + got, err := m.GetInstance(t.Context(), parked) + require.NoError(t, err) + require.Equal(t, parked, got.Id) + link, err := os.Readlink(refusedDir) + require.NoError(t, err) + require.Equal(t, forkDir, link) + require.DirExists(t, refusedDir+".fork-bak.123") + _, err = m.GetInstance(t.Context(), refused) + require.ErrorIs(t, err, ErrNotFound) +} + +func TestAbandonedForkCannotBeStartedOrRestored(t *testing.T) { + m, _ := setupTestManager(t) + const id = "abandoned" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + mark := func(owner *ForkOwner) *StoredMetadata { + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = owner + require.NoError(t, m.saveMetadata(meta)) + return &meta.StoredMetadata + } + + // A finished fork, and one its own request is still bringing up, pass. + require.NoError(t, m.refuseAbandonedFork(mark(nil))) + require.NoError(t, m.refuseAbandonedFork(mark(currentForkOwner()))) + + for name, owner := range map[string]*ForkOwner{"interrupted": exitedProcessOwner(t), "undeleted": {}} { + mark(owner) + _, err := m.StartInstance(t.Context(), id, StartInstanceRequest{}) + require.ErrorIs(t, err, ErrInvalidState, name) + _, err = m.RestoreInstance(t.Context(), id) + require.ErrorIs(t, err, ErrInvalidState, name) + require.ErrorContains(t, err, "waiting to be deleted", name) + } +} + +// A fork its failing request could not delete stays under the requested name. +// It must be refused like an interrupted one, and deleted at the next start. +func TestForkItsRequestCannotDeleteIsAbandoned(t *testing.T) { + m, _ := setupTestManager(t) + const id = "undeleted-fork" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = currentForkOwner() + meta.Devices = []string{"dev-1"} + require.NoError(t, m.saveMetadata(meta)) + devices := m.deviceManager + m.deviceManager = busyDevice{devices} + + require.Error(t, m.discardFork(t.Context(), id, errors.New("fork failed"))) + got, err := m.loadMetadata(id) + require.NoError(t, err) + require.Equal(t, &ForkOwner{}, got.ForkPending) + require.ErrorIs(t, m.refuseAbandonedFork(&got.StoredMetadata), ErrInvalidState) + + m.deviceManager = devices + m.RecoverInterruptedForks(t.Context()) + require.NoDirExists(t, m.paths.InstanceDir(id)) +} diff --git a/lib/instances/fork_recovery_linux_test.go b/lib/instances/fork_recovery_linux_test.go new file mode 100644 index 000000000..f9f67b847 --- /dev/null +++ b/lib/instances/fork_recovery_linux_test.go @@ -0,0 +1,54 @@ +package instances + +import ( + "os" + "testing" + + "github.com/kernel/hypeman/lib/network" + "github.com/nrednav/cuid2" + "github.com/stretchr/testify/require" + "github.com/vishvananda/netlink" +) + +func TestRecoveryRemovesKernelTAPWithoutAllocation(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("creating a TAP requires CAP_NET_ADMIN") + } + if _, err := os.Stat("/dev/net/tun"); os.IsNotExist(err) { + t.Skip("no TUN device") + } + for _, tc := range []struct { + name string + sharedName bool + }{ + {"own name", false}, + {"shared name", true}, + } { + t.Run(tc.name, func(t *testing.T) { + m, _ := setupTestManager(t) + id := cuid2.Generate() + createPendingForkWithoutAllocation(t, m, id) + tap := &netlink.Tuntap{ + LinkAttrs: netlink.LinkAttrs{Name: network.GenerateTAPName(id)}, + Mode: netlink.TUNTAP_MODE_TAP, + } + require.NoError(t, netlink.LinkAdd(tap)) + t.Cleanup(func() { _ = netlink.LinkDel(tap) }) + if tc.sharedName { + // A second guest can share the short TAP name, so the TAP may + // be its own. It is left for the TAP reconciler. + require.NoError(t, os.Mkdir(m.paths.InstanceDir(id+"-other"), 0755)) + } + + m.RecoverInterruptedForks(t.Context()) + require.NoDirExists(t, m.paths.InstanceDir(id)) + _, err := netlink.LinkByName(tap.Name) + if tc.sharedName { + require.NoError(t, err) + return + } + var notFound netlink.LinkNotFoundError + require.ErrorAs(t, err, ¬Found) + }) + } +} diff --git a/lib/instances/fork_test.go b/lib/instances/fork_test.go index 2ce61f3ad..ef94acb0c 100644 --- a/lib/instances/fork_test.go +++ b/lib/instances/fork_test.go @@ -734,6 +734,7 @@ func TestCloneStoredMetadataForFork_DeepCopiesReferenceFields(t *testing.T) { StoppedAt: &stoppedAt, GPUClaimedAt: &gpuClaimedAt, HypervisorProcessIdentity: HypervisorProcessIdentity{HypervisorPID: &pid}, + ForkPending: &ForkOwner{PID: 77}, ExitCode: &exitCode, AutoStandby: &autostandby.Policy{ Enabled: true, @@ -777,6 +778,7 @@ func TestCloneStoredMetadataForFork_DeepCopiesReferenceFields(t *testing.T) { cloned.Entrypoint[0] = "/usr/bin/env" cloned.Cmd[0] = "printf" *cloned.HypervisorPID = 4321 + cloned.ForkPending.PID = 78 *cloned.ExitCode = 42 cloned.AutoStandby.IgnoreSourceCIDRs[0] = "192.168.0.0/16" cloned.AutoStandby.IgnoreDestinationPorts[0] = 443 @@ -797,6 +799,7 @@ func TestCloneStoredMetadataForFork_DeepCopiesReferenceFields(t *testing.T) { require.Equal(t, "/bin/sh", src.Entrypoint[0]) require.Equal(t, "echo", src.Cmd[0]) require.Equal(t, 1234, *src.HypervisorPID) + require.Equal(t, 77, src.ForkPending.PID) require.Equal(t, 17, *src.ExitCode) require.Equal(t, "10.0.0.0/8", src.AutoStandby.IgnoreSourceCIDRs[0]) require.Equal(t, uint16(22), src.AutoStandby.IgnoreDestinationPorts[0]) diff --git a/lib/instances/lifecycle_noop_test.go b/lib/instances/lifecycle_noop_test.go index 4926894cf..3dbe16b09 100644 --- a/lib/instances/lifecycle_noop_test.go +++ b/lib/instances/lifecycle_noop_test.go @@ -144,6 +144,39 @@ func TestLifecycleNoopTransitionsReturnCurrentInstanceWithoutEvent(t *testing.T) } } +func TestPublicBootRejectsPendingForkBeforeFastPaths(t *testing.T) { + for _, state := range []State{StatePaused, StateRunning, StateInitializing} { + for kind, owner := range map[string]*ForkOwner{"in-flight": currentForkOwner(), "abandoned": {}} { + t.Run(string(state)+"/"+kind, func(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, state, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = owner + meta.RestartStatus.BlockedReason = restartpolicy.BlockedReasonManualStop + require.NoError(t, m.saveMetadata(meta)) + events, cancel := m.SubscribeLifecycleEvents(LifecycleEventConsumerWaitForState) + defer cancel() + + _, err = m.RestoreInstance(t.Context(), id) + require.ErrorIs(t, err, ErrInvalidState) + _, err = m.RestartInstance(t.Context(), id) + require.ErrorIs(t, err, ErrInvalidState) + require.ErrorContains(t, err, "fork") + for _, req := range []StartInstanceRequest{{}, {Cmd: []string{"true"}}} { + _, err = m.StartInstance(t.Context(), id, req) + require.ErrorIs(t, err, ErrInvalidState) + require.ErrorContains(t, err, "fork") + } + got, err := m.getInstance(t.Context(), id) + require.NoError(t, err) + require.Equal(t, state, got.State) + require.Equal(t, meta.RestartStatus, got.RestartStatus) + assertNoLifecycleEvent(t, events) + }) + } + } +} + func TestLifecycleNoopStartWithOverridesStillRejectsActiveInstance(t *testing.T) { m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) events, cancel := m.SubscribeLifecycleEvents(LifecycleEventConsumerWaitForState) @@ -356,11 +389,10 @@ func TestStopStoppedInstanceLeavesVGPUForReconcile(t *testing.T) { type recordingDeviceManager struct { devices.Manager detached []string - unbound []string onMarkDetached func() } -func (m *recordingDeviceManager) MarkDetached(ctx context.Context, deviceID string) error { +func (m *recordingDeviceManager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error { m.detached = append(m.detached, deviceID) if m.onMarkDetached != nil { m.onMarkDetached() @@ -368,11 +400,6 @@ func (m *recordingDeviceManager) MarkDetached(ctx context.Context, deviceID stri return nil } -func (m *recordingDeviceManager) UnbindFromVFIO(ctx context.Context, id string) error { - m.unbound = append(m.unbound, id) - return nil -} - func TestLifecycleNoopStandbyRejectsVendorVFIOVGPU(t *testing.T) { m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) meta, err := m.loadMetadata(id) @@ -421,6 +448,8 @@ func newLifecycleNoopManagerWithInstance(t *testing.T, state State, now time.Tim writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StateRunning) case StateInitializing: writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StateRunning) + case StatePaused: + writeLifecycleNoopSocket(t, stored.SocketPath, hypervisor.StatePaused) case StateStandby: writeLifecycleNoopSnapshot(t, p, id) } diff --git a/lib/instances/macos.go b/lib/instances/macos.go index 8c49444a2..65492b884 100644 --- a/lib/instances/macos.go +++ b/lib/instances/macos.go @@ -450,8 +450,7 @@ func sameMACAddress(a, b string) bool { return bytes.Equal(x, y) } -// vzShimOwner finds the vz-shim for socketPath when no live shim PID is recorded, -// as after the API dies mid-boot or mid-restore. More than one is ambiguous. +// vzShimOwner finds the unique vz-shim configured for socketPath, even before it listens. func vzShimOwner(socketPath string) (int, error) { if socketPath == "" { return 0, nil diff --git a/lib/instances/macos_boot_admission_test.go b/lib/instances/macos_boot_admission_test.go index 9f7f448cf..35cd0e866 100644 --- a/lib/instances/macos_boot_admission_test.go +++ b/lib/instances/macos_boot_admission_test.go @@ -31,6 +31,24 @@ func (s *macOSBootAdmissionStarter) StartVM(_ context.Context, _ *paths.Paths, _ return os.Getpid(), lifecycleNoopHypervisor{state: hypervisor.StateRunning}, nil } +func TestMacOSBootAdmissionSkipsOnlyForeignMetadata(t *testing.T) { + p := paths.New(t.TempDir()) + m := &manager{paths: p} + guest := &StoredMetadata{Id: "guest", SocketPath: p.InstanceSocket("guest", "vz.sock"), MacOS: testMacImage().MacOS, NetworkEnabled: true} + require.NoError(t, m.ensureDirectories("partial-copy")) + path := p.InstanceMetadata("partial-copy") + require.NoError(t, os.WriteFile(path, []byte(`{"Id":"old-source","MAC":"02:00:00:00:00:01"}`), 0644)) + require.NoError(t, m.checkMacOSBootAvailable(t.Context(), guest)) + macs, err := m.storedMACs(guest.Id) + require.NoError(t, err) + require.Empty(t, macs) + + for _, invalid := range []string{`{`, `{}`} { + require.NoError(t, os.WriteFile(path, []byte(invalid), 0644)) + require.Error(t, m.checkMacOSBootAvailable(t.Context(), guest)) + } +} + func TestMacOSConcurrentBootsRecheckMACUnderBootLock(t *testing.T) { p := paths.New(t.TempDir()) m := &manager{paths: p} diff --git a/lib/instances/macos_identity.go b/lib/instances/macos_identity.go index b21b56a2f..03a4a0e2d 100644 --- a/lib/instances/macos_identity.go +++ b/lib/instances/macos_identity.go @@ -66,8 +66,8 @@ func prepareMacOSClone(clone *StoredMetadata) error { } // forEachOtherInstance calls fn with the metadata of every stored instance except -// exclude, stopping at fn's first error. Directories without metadata are skipped; -// any other load error is wrapped with loadErrorContext when it is set. +// exclude, stopping at fn's first error. Directories without their own metadata +// are skipped; unreadable records fail admission. func (m *manager) forEachOtherInstance(exclude, loadErrorContext string, fn func(*metadata) error) error { entries, err := os.ReadDir(m.paths.GuestsDir()) if err != nil { @@ -78,8 +78,8 @@ func (m *manager) forEachOtherInstance(exclude, loadErrorContext string, fn func continue } meta, err := m.loadMetadata(entry.Name()) - if errors.Is(err, ErrNotFound) { - // A create in progress or a leftover directory has no instance to admit against. + if errors.Is(err, ErrNotFound) || errors.Is(err, errMetadataIDMismatch) { + // An incomplete copy is not another instance claiming this identity. continue } if err != nil { diff --git a/lib/instances/manager.go b/lib/instances/manager.go index b6e0d879b..22bde2224 100644 --- a/lib/instances/manager.go +++ b/lib/instances/manager.go @@ -181,6 +181,8 @@ type manager struct { now func() time.Time writeFile func(string, []byte, os.FileMode) error deleteInstanceFn func(context.Context, string) error + syncDirFn func(*os.File) error + forkOwnerGoneFn func(ForkOwner) bool discoverVGPU func() (devices.VGPUFramework, []devices.VirtualFunction, error) createVGPU func(context.Context, string, string) (*devices.VGPUDevice, error) configureVGPU func(context.Context, string, string) error @@ -556,12 +558,12 @@ func (m *manager) ForkInstance(ctx context.Context, id string, req ForkInstanceR } else { inst, err = m.applyForkTargetState(ctx, forked.Id, targetState) } - if err != nil { - if cleanupErr := m.cleanupForkInstanceOnError(ctx, forked.Id); cleanupErr != nil { - return nil, fmt.Errorf("apply fork target state: %w; additionally failed to cleanup forked instance %s: %v", err, forked.Id, cleanupErr) - } - return nil, fmt.Errorf("apply fork target state: %w", err) - } + } + if err != nil { + return nil, m.discardFork(ctx, forked.Id, fmt.Errorf("apply fork target state: %w", err)) + } + if err := m.completeFork(inst); err != nil { + return nil, m.discardFork(ctx, forked.Id, err) } m.notifyLifecycleEvent(ctx, LifecycleEventFork, inst) return inst, nil @@ -616,17 +618,18 @@ func (m *manager) RestoreInstance(ctx context.Context, id string) (*Instance, er lock := m.getInstanceLock(id) lock.Lock() defer lock.Unlock() - current, err := m.currentInstanceWithoutHydration(ctx, id) + meta, err := m.loadMetadataForBootRequest(id) if err != nil { return nil, err } + current := m.toInstanceWithoutHydration(ctx, meta) if current.State == StateRunning || current.State == StateInitializing { // A running macOS guest has consumed its checkpoint. One still on disk means an // earlier resume failed before removing it, so finish that resume now. if current.MacOS != nil && current.HasSnapshot { // Initializing without a control socket is a shim still loading the VM. It has // not resumed, so the checkpoint it will consume must stay. - if current.State == StateInitializing && !m.macOSSocketAnswers(ctx, current) { + if current.State == StateInitializing && !m.macOSSocketAnswers(ctx, ¤t) { return nil, fmt.Errorf("%w: macOS restore is still loading the VM; retry shortly", ErrInvalidState) } if err := m.finishMacOSResume(id); err != nil { @@ -634,7 +637,7 @@ func (m *manager) RestoreInstance(ctx context.Context, id string) (*Instance, er } return m.currentInstanceWithoutHydration(ctx, id) } - return current, nil + return ¤t, nil } if current.State == StatePaused { hv, err := m.getHypervisor(current.SocketPath, current.HypervisorType) @@ -656,12 +659,12 @@ func (m *manager) RestoreInstance(ctx context.Context, id string) (*Instance, er return nil, fmt.Errorf("finish resumed restore: %w", err) } } - current, err = m.currentInstanceWithoutHydration(ctx, id) + resumed, err := m.currentInstanceWithoutHydration(ctx, id) if err != nil { return nil, err } - m.notifyLifecycleEvent(ctx, LifecycleEventRestore, current) - return current, nil + m.notifyLifecycleEvent(ctx, LifecycleEventRestore, resumed) + return resumed, nil } inst, err := m.restoreInstance(ctx, id) if err == nil { @@ -715,14 +718,15 @@ func (m *manager) StartInstance(ctx context.Context, id string, req StartInstanc lock := m.getInstanceLock(id) lock.Lock() defer lock.Unlock() - if err := m.clearRestartStatusLocked(ctx, id); err != nil { + meta, err := m.loadMetadataForBootRequest(id) + if err != nil { + return nil, err + } + if err := m.clearRestartStatusLocked(ctx, meta); err != nil { return nil, err } if !startRequestHasOverrides(req) { - current, err := m.currentInstanceWithoutHydration(ctx, id) - if err != nil { - return nil, err - } + current := m.toInstanceWithoutHydration(ctx, meta) if current.State == StateRunning || current.State == StateInitializing { // The API can exit after a clone boots and before its rekey finishes. Finish it // here, or the clone keeps its source's SSH host keys. @@ -732,7 +736,7 @@ func (m *manager) StartInstance(ctx context.Context, id string, req StartInstanc } return m.currentInstanceWithoutHydration(ctx, id) } - return current, nil + return ¤t, nil } } inst, err := m.startInstance(ctx, id, req) @@ -790,7 +794,10 @@ func (m *manager) listMetadataForReconcile() ([]StoredMetadata, error) { id := filepath.Base(filepath.Dir(file)) meta, err := m.loadMetadata(id) if err != nil { - if errors.Is(err, ErrNotFound) { + // A directory holding another guest's metadata is a partial fork + // copy or a parked source. Neither can have a VMM of its own, so + // it holds nothing a reconcile has to account for. + if errors.Is(err, ErrNotFound) || errors.Is(err, errMetadataIDMismatch) { continue } return nil, fmt.Errorf("load metadata for instance %s: %w", id, err) @@ -856,6 +863,11 @@ func (m *manager) getInstanceWithMinIDPrefix(ctx context.Context, idOrName strin return inst, nil } + // An alias or partial copy is not a name/prefix lookup. + if errors.Is(err, errMetadataIDMismatch) { + return nil, ErrNotFound + } + // 2. Resolve exact name or ID prefix from metadata only, then hydrate the // single matched instance. meta, err := m.findInstanceMetadataByNameOrIDPrefix(ctx, idOrName, minPrefixLength) diff --git a/lib/instances/metrics.go b/lib/instances/metrics.go index 02bd0fc8d..517bd0e21 100644 --- a/lib/instances/metrics.go +++ b/lib/instances/metrics.go @@ -103,6 +103,7 @@ type Metrics struct { lifecycleEventsDroppedTotal metric.Int64Counter forkMemFileShareFallbacksTotal metric.Int64Counter ttlReaperDeletionsTotal metric.Int64Counter + interruptedForksTotal metric.Int64Counter vgpuReconcileFailuresTotal metric.Int64Counter vgpuStaleReleaseFailuresTotal metric.Int64Counter vgpuLivenessUncertainTotal metric.Int64Counter @@ -282,6 +283,14 @@ func newInstanceMetrics(meter metric.Meter, tracer trace.Tracer, m *manager) (*M return nil, err } + interruptedForksTotal, err := meter.Int64Counter( + "hypeman_instances_interrupted_forks_total", + metric.WithDescription("Total number of interrupted forks found at startup, by what was done with them"), + ) + if err != nil { + return nil, err + } + vgpuReconcileFailuresTotal, err := meter.Int64Counter( "hypeman_instances_vgpu_reconcile_failures_total", metric.WithDescription("Total number of vGPU reconcile pass stages that failed, leaving stale assignments or device leftovers allocated"), @@ -533,6 +542,7 @@ func newInstanceMetrics(meter metric.Meter, tracer trace.Tracer, m *manager) (*M lifecycleEventsDroppedTotal: lifecycleEventsDroppedTotal, forkMemFileShareFallbacksTotal: forkMemFileShareFallbacksTotal, ttlReaperDeletionsTotal: ttlReaperDeletionsTotal, + interruptedForksTotal: interruptedForksTotal, vgpuReconcileFailuresTotal: vgpuReconcileFailuresTotal, vgpuStaleReleaseFailuresTotal: vgpuStaleReleaseFailuresTotal, vgpuLivenessUncertainTotal: vgpuLivenessUncertainTotal, @@ -644,6 +654,15 @@ func (m *manager) recordVGPUReconcileFailure(ctx context.Context, stage vgpuReco )) } +// recordInterruptedFork counts a fork that startup found still marked pending. +// Any status but "deleted" means the fork is still holding its resources. +func (m *manager) recordInterruptedFork(ctx context.Context, status string) { + if m.metrics == nil { + return + } + m.metrics.interruptedForksTotal.Add(ctx, 1, metric.WithAttributes(attribute.String("status", status))) +} + func (m *manager) recordVGPUStaleReleaseFailure(ctx context.Context) { if m.metrics == nil { return diff --git a/lib/instances/process_identity.go b/lib/instances/process_identity.go index 57aac3af7..47c8f9b72 100644 --- a/lib/instances/process_identity.go +++ b/lib/instances/process_identity.go @@ -145,10 +145,13 @@ func resolveLiveHypervisorPID(id HypervisorProcessIdentity, socketPath string) ( } } if runtime.GOOS != "linux" { - if stored == 0 { - return vzShimOwner(socketPath) + // Darwin has no recorded start time. Never signal a PID based only on + // its continued existence, even when the control socket is stale. + owner, err := vzShimOwner(socketPath) + if err == nil && owner == 0 && stored != 0 { + return 0, fmt.Errorf("cannot confirm stored shim PID %d for socket %q", stored, socketPath) } - return stored, nil + return owner, err } bootID := hostBootID() if stored != 0 && id.HypervisorBootID != "" && bootID != "" && id.HypervisorBootID != bootID { diff --git a/lib/instances/process_identity_darwin_test.go b/lib/instances/process_identity_darwin_test.go new file mode 100644 index 000000000..617619705 --- /dev/null +++ b/lib/instances/process_identity_darwin_test.go @@ -0,0 +1,43 @@ +package instances + +import ( + "errors" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDarwinTeardownRequiresMatchingShim(t *testing.T) { + const socket = "/data/guests/fork/vz.sock" + // The stored PID is live but belongs to this test, not to the guest. + stored := os.Getpid() + identity := HypervisorProcessIdentity{HypervisorPID: &stored} + var matches []int + var lookupErr error + prev := findVZShimPIDs + t.Cleanup(func() { findVZShimPIDs = prev }) + findVZShimPIDs = func(path string) ([]int, error) { + require.Equal(t, socket, path) + return matches, lookupErr + } + + pid, err := resolveLiveHypervisorPID(identity, socket) + require.Error(t, err) + require.Zero(t, pid) + + matches = []int{123, 456} + pid, err = resolveLiveHypervisorPID(identity, socket) + require.Error(t, err) + require.Zero(t, pid) + + matches = []int{123} + pid, err = resolveLiveHypervisorPID(identity, socket) + require.NoError(t, err) + require.Equal(t, matches[0], pid) + + lookupErr = errors.New("cannot inspect processes") + pid, err = resolveLiveHypervisorPID(identity, socket) + require.ErrorIs(t, err, lookupErr) + require.Zero(t, pid) +} diff --git a/lib/instances/restart_policy.go b/lib/instances/restart_policy.go index 227b6c76c..5e8660b29 100644 --- a/lib/instances/restart_policy.go +++ b/lib/instances/restart_policy.go @@ -63,18 +63,13 @@ func (m *manager) markRestartManualStopLocked(ctx context.Context, id string) er return nil } -func (m *manager) clearRestartStatusLocked(ctx context.Context, id string) error { - meta, err := m.loadMetadata(id) - if err != nil { - logger.FromContext(ctx).WarnContext(ctx, "failed to clear restart policy status", "instance_id", id, "error", err) - return err - } +func (m *manager) clearRestartStatusLocked(ctx context.Context, meta *metadata) error { if meta.RestartStatus.IsZero() { return nil } meta.RestartStatus = restartpolicy.Status{} if err := m.saveMetadata(meta); err != nil { - logger.FromContext(ctx).WarnContext(ctx, "failed to clear restart policy status", "instance_id", id, "error", err) + logger.FromContext(ctx).WarnContext(ctx, "failed to clear restart policy status", "instance_id", meta.Id, "error", err) return err } return nil @@ -127,6 +122,9 @@ func (m *manager) RestartInstance(ctx context.Context, id string) (*Instance, er lock.Lock() defer lock.Unlock() + if _, err := m.loadMetadataForBootRequest(id); err != nil { + return nil, err + } inst, err := m.startInstance(ctx, id, StartInstanceRequest{}) if err == nil { m.notifyLifecycleEvent(ctx, LifecycleEventStart, inst) @@ -143,7 +141,7 @@ func (m *manager) HandleHealthCheckUnhealthy(ctx context.Context, id string) err if err != nil { return err } - if current.State != StateRunning { + if current.ForkPending != nil || current.State != StateRunning { return nil } @@ -266,7 +264,7 @@ func (m *manager) reconcileRestartPolicyInstanceID(ctx context.Context, id strin } func (m *manager) reconcileRestartPolicyInstance(ctx context.Context, inst *Instance, log *slog.Logger) error { - if inst == nil { + if inst == nil || inst.ForkPending != nil { return nil } policy, err := restartpolicy.NormalizePolicy(inst.RestartPolicy) diff --git a/lib/instances/restart_policy_test.go b/lib/instances/restart_policy_test.go index 9d90247f4..9472e325a 100644 --- a/lib/instances/restart_policy_test.go +++ b/lib/instances/restart_policy_test.go @@ -183,6 +183,26 @@ func TestStartInstanceClearsRestartStatusWhenAlreadyRunning(t *testing.T) { assert.True(t, loaded.RestartStatus.IsZero()) } +func TestRestartPolicyLeavesPendingForkToItsCreator(t *testing.T) { + for _, state := range []State{StateStopped, StateRunning} { + t.Run(string(state), func(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, state, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.ForkPending = currentForkOwner() + meta.RestartPolicy = &restartpolicy.Policy{Policy: restartpolicy.PolicyAlways} + require.NoError(t, m.saveMetadata(meta)) + + require.NoError(t, m.reconcileRestartPolicyInstanceID(t.Context(), id, slog.Default())) + require.NoError(t, m.HandleHealthCheckUnhealthy(t.Context(), id)) + got, err := m.currentInstanceWithoutHydration(t.Context(), id) + require.NoError(t, err) + require.Equal(t, state, got.State) + require.True(t, got.RestartStatus.IsZero()) + }) + } +} + func TestStartInstanceForRestartPolicyPreservesConcurrentManualStop(t *testing.T) { manager, _ := setupTestManager(t) id := "restart-manual-race" diff --git a/lib/instances/restore.go b/lib/instances/restore.go index ef85b5b14..6bbe5e90c 100644 --- a/lib/instances/restore.go +++ b/lib/instances/restore.go @@ -45,6 +45,9 @@ func (m *manager) restoreInstance( if err := m.admitGuestOperation(&meta.StoredMetadata); err != nil { return nil, err } + if err := m.refuseAbandonedFork(&meta.StoredMetadata); err != nil { + return nil, err + } release, err := m.admitMacOSBoot(ctx, &meta.StoredMetadata) if err != nil { return nil, err diff --git a/lib/instances/snapshot.go b/lib/instances/snapshot.go index dd6f6aead..a9b2f7a6d 100644 --- a/lib/instances/snapshot.go +++ b/lib/instances/snapshot.go @@ -2,9 +2,11 @@ package instances import ( "context" + "encoding/json" "errors" "fmt" "os" + "path/filepath" "time" "github.com/kernel/hypeman/lib/forkvm" @@ -287,6 +289,9 @@ func (m *manager) restoreSnapshot(ctx context.Context, id string, snapshotID str if err != nil { return nil, err } + if sourceMeta.ForkPending != nil { + return nil, fmt.Errorf("%w: cannot restore a snapshot onto a pending fork", ErrInvalidState) + } if err := validateMacOSSnapshotRestore(sourceMeta, rec); err != nil { return nil, err } @@ -558,6 +563,7 @@ func (m *manager) forkSnapshot(ctx context.Context, snapshotID string, req ForkS } } + forkMeta.ForkPending = currentForkOwner() newMeta := &metadata{StoredMetadata: forkMeta} if forkMeta.MacOS != nil { if err := m.saveMacOSSnapshotFork(ctx, newMeta); err != nil { @@ -570,16 +576,24 @@ func (m *manager) forkSnapshot(ctx context.Context, snapshotID string, req ForkS cu.Release() inst, err := m.applyForkTargetState(ctx, forkID, targetState) if err != nil { - if cleanupErr := m.cleanupForkInstanceOnError(ctx, forkID); cleanupErr != nil { - return nil, fmt.Errorf("apply snapshot fork target state: %w; additionally failed to cleanup forked instance %s: %v", err, forkID, cleanupErr) - } - return nil, fmt.Errorf("apply snapshot fork target state: %w", err) + return nil, m.discardFork(ctx, forkID, fmt.Errorf("apply snapshot fork target state: %w", err)) + } + if err := m.completeFork(inst); err != nil { + return nil, m.discardFork(ctx, forkID, err) } return inst, nil } -func (m *manager) copySnapshotPayload(sourceInstanceID, snapshotGuestDir string) error { - err := copyGuestDirectoryWithAliasReadLock(m.paths.InstanceDir(sourceInstanceID), snapshotGuestDir) +func (m *manager) copySnapshotPayload(sourceID, snapshotGuestDir string) error { + // Never put a pending mark in the payload, even partway through a copy. + name := filepath.Base(m.paths.InstanceMetadata(sourceID)) + opts := forkvm.CopyOptions{SkipRelativePaths: map[string]struct{}{name: {}}} + err := withSnapshotSourceAliasReadLock(func() error { + if err := forkvm.CopyGuestDirectoryWithOptions(m.paths.InstanceDir(sourceID), snapshotGuestDir, opts); err != nil { + return err + } + return copySnapshotMetadata(m.paths.InstanceMetadata(sourceID), filepath.Join(snapshotGuestDir, name)) + }) if err != nil { if errors.Is(err, forkvm.ErrSparseCopyUnsupported) { return fmt.Errorf("snapshot requires sparse-capable filesystem (SEEK_DATA/SEEK_HOLE unsupported): %w", err) @@ -589,6 +603,25 @@ func (m *manager) copySnapshotPayload(sourceInstanceID, snapshotGuestDir string) return nil } +func copySnapshotMetadata(src, dst string) error { + data, err := os.ReadFile(src) + if err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if _, marked := fields["fork_pending"]; marked { + delete(fields, "fork_pending") + data, err = json.MarshalIndent(fields, "", " ") + if err != nil { + return err + } + } + return os.WriteFile(dst, data, 0644) +} + func (m *manager) replaceInstanceWithSnapshotPayload(snapshotID, instanceID string) error { instanceDir := m.paths.InstanceDir(instanceID) if err := os.RemoveAll(instanceDir); err != nil { diff --git a/lib/instances/snapshot_alias_lock.go b/lib/instances/snapshot_alias_lock.go index d994bf331..09567aecb 100644 --- a/lib/instances/snapshot_alias_lock.go +++ b/lib/instances/snapshot_alias_lock.go @@ -35,12 +35,6 @@ func prepareForkWithAliasReadLock(ctx context.Context, starter hypervisor.VMStar return result, retErr } -func copyGuestDirectoryWithAliasReadLock(srcDir, dstDir string) error { - return withSnapshotSourceAliasReadLock(func() error { - return forkvm.CopyGuestDirectory(srcDir, dstDir) - }) -} - func (m *manager) copyForkSourceGuestDirectory(ctx context.Context, sourceState State, sourceID string, stored *StoredMetadata, srcDir, dstDir string, shareMemFile bool) error { ctx, span := m.tracerOrDefault().Start(ctx, "instances.fork.copy_guest_directory", trace.WithAttributes( @@ -140,9 +134,10 @@ func (m *manager) cloneGuestDirectoryForFork(ctx context.Context, srcDir, dstDir } } - copyOptions := forkvm.CopyOptions{} + // The fork writes its own metadata after the copy. + copyOptions := forkvm.CopyOptions{SkipRelativePaths: map[string]struct{}{"metadata.json": {}}} if shareMemFile { - copyOptions.SkipRelativePaths = map[string]struct{}{firecrackerSnapshotMemoryRelPath: {}} + copyOptions.SkipRelativePaths[firecrackerSnapshotMemoryRelPath] = struct{}{} } if err := forkvm.CopyGuestDirectoryWithOptions(srcDir, dstDir, copyOptions); err != nil { return err diff --git a/lib/instances/snapshot_compression.go b/lib/instances/snapshot_compression.go index af5fc6cb4..95d5b3119 100644 --- a/lib/instances/snapshot_compression.go +++ b/lib/instances/snapshot_compression.go @@ -317,6 +317,22 @@ func (m *manager) clearPendingStandbyCompression(ctx context.Context, instanceID return nil } +// clearFinishedStandbyCompression clears the plan of a compression job that +// has ended, unless the instance is locked. The job cannot wait for the lock: +// its holder may be waiting for the job to end. Writing without it would put +// back whatever the holder changes in between, such as a fork's pending mark. +// Any holder blocks the clear, readers included, so a plan can outlive its +// job. Nothing acts on a plan except startup recovery, which compresses the +// snapshot if it is still raw and clears the plan otherwise. +func (m *manager) clearFinishedStandbyCompression(ctx context.Context, instanceID string) error { + lock := m.getInstanceLock(instanceID) + if !lock.TryLock() { + return nil + } + defer lock.Unlock() + return m.clearPendingStandbyCompression(ctx, instanceID) +} + func (m *manager) recoverPendingStandbyCompressionJobs(ctx context.Context) error { metaFiles, err := m.listMetadataFiles() if err != nil { @@ -332,6 +348,12 @@ func (m *manager) recoverPendingStandbyCompressionJobs(ctx context.Context) erro continue } + // Startup deletes an interrupted fork, and a fork still being made + // belongs to another process. + if meta.ForkPending != nil { + continue + } + plan := clonePendingStandbyCompression(meta.StoredMetadata.PendingStandbyCompression) if plan == nil { continue @@ -569,7 +591,7 @@ func (m *manager) startCompressionJob(ctx context.Context, target compressionTar defer func() { m.recordSnapshotCompressionJob(metricsCtx, target, result, compressionStart, uncompressedSize, compressedSize) if target.Source == snapshotCompressionSourceStandby && target.SnapshotID == "" { - if err := m.clearPendingStandbyCompression(context.Background(), target.OwnerID); err != nil && !errors.Is(err, ErrNotFound) { + if err := m.clearFinishedStandbyCompression(context.Background(), target.OwnerID); err != nil && !errors.Is(err, ErrNotFound) { log.WarnContext(context.Background(), "failed to clear pending standby compression plan after job completion", "instance_id", target.OwnerID, "error", err) } } diff --git a/lib/instances/snapshot_compression_test.go b/lib/instances/snapshot_compression_test.go index 540bfbda0..8e4c8ea56 100644 --- a/lib/instances/snapshot_compression_test.go +++ b/lib/instances/snapshot_compression_test.go @@ -593,6 +593,50 @@ func TestRecoverPendingStandbyCompressionJobsRequeuesDelayedJob(t *testing.T) { require.NoError(t, err) } +// An interrupted fork is about to be deleted, so compressing its snapshot +// first is wasted work. +func TestRecoverPendingStandbyCompressionJobsSkipsPendingFork(t *testing.T) { + t.Parallel() + + mgr := newSnapshotCompressionTestManager(t) + now := time.Date(2026, time.April, 6, 12, 0, 0, 0, time.UTC) + mgr.now = func() time.Time { return now } + // A job that starts stays queued, so whether one started can be read at once. + mgr.compressionTimerFactory = func(time.Duration) compressionTimer { return newFakeCompressionTimer() } + + const instanceID = "recover-pending-fork" + snapshotDir := mgr.paths.InstanceSnapshotLatest(instanceID) + require.NoError(t, mgr.ensureDirectories(instanceID)) + require.NoError(t, os.MkdirAll(snapshotDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(snapshotDir, "memory"), []byte("interrupted fork snapshot"), 0o644)) + require.NoError(t, mgr.saveMetadata(&metadata{StoredMetadata: StoredMetadata{ + Id: instanceID, + Name: instanceID, + DataDir: mgr.paths.InstanceDir(instanceID), + HypervisorType: hypervisor.TypeCloudHypervisor, + CreatedAt: now, + StoppedAt: &now, + ForkPending: currentForkOwner(), + PendingStandbyCompression: &PendingStandbyCompression{ + Policy: snapshotstore.SnapshotCompressionConfig{ + Enabled: true, + Algorithm: snapshotstore.SnapshotCompressionAlgorithmZstd, + }, + NotBefore: now.Add(time.Minute), + }, + }})) + + require.NoError(t, mgr.recoverPendingStandbyCompressionJobs(context.Background())) + + mgr.compressionMu.Lock() + _, started := mgr.compressionJobs[mgr.snapshotJobKeyForInstance(instanceID)] + mgr.compressionMu.Unlock() + assert.False(t, started) + meta, err := mgr.loadMetadata(instanceID) + require.NoError(t, err) + assert.NotNil(t, meta.PendingStandbyCompression) +} + func TestRecoverPendingStandbyCompressionJobsStartsImmediateCompression(t *testing.T) { t.Parallel() diff --git a/lib/instances/start.go b/lib/instances/start.go index af1f5f3c1..1c1e3fe77 100644 --- a/lib/instances/start.go +++ b/lib/instances/start.go @@ -45,6 +45,9 @@ func (m *manager) startInstance( if err := m.checkMacOSStart(stored, req); err != nil { return nil, err } + if err := m.refuseAbandonedFork(stored); err != nil { + return nil, err + } // 2. Validate state (must be Stopped to start) if inst.State != StateStopped { diff --git a/lib/instances/storage.go b/lib/instances/storage.go index 2e7440e3a..a1a05085c 100644 --- a/lib/instances/storage.go +++ b/lib/instances/storage.go @@ -63,6 +63,8 @@ func (m *manager) ensureDirectories(id string) error { return nil } +var errMetadataIDMismatch = errors.New("instance metadata ID mismatch") + // loadMetadata loads instance metadata from disk func (m *manager) loadMetadata(id string) (*metadata, error) { return m.loadMetadataTimed(id, nil) @@ -97,16 +99,32 @@ func (m *manager) loadMetadataTimed(id string, timings *metadataScanTimings) (*m return nil, fmt.Errorf("unmarshal metadata: %w", err) } + if meta.Id != id { + if err := paths.ValidatePathComponent(meta.Id); err != nil { + return nil, fmt.Errorf("invalid instance ID %q in %s: %w", meta.Id, metaPath, err) + } + return nil, fmt.Errorf("%w: directory %q contains metadata for %q", errMetadataIDMismatch, id, meta.Id) + } return &meta, nil } // saveMetadata saves instance metadata to disk func (m *manager) saveMetadata(meta *metadata) error { + return m.writeMetadata(meta, false) +} + +// saveMetadataDurably is saveMetadata for a write that a host crash must not +// undo once it has returned: it syncs the file and its directory. +func (m *manager) saveMetadataDurably(meta *metadata) error { + return m.writeMetadata(meta, true) +} + +func (m *manager) writeMetadata(meta *metadata, durable bool) error { if err := paths.ValidatePathComponent(meta.Id); err != nil { return err } unlockAliasReaders := hypervisor.LockSnapshotSourceAliasReaders() - defer unlockAliasReaders() + defer func() { unlockAliasReaders() }() metaPath := m.paths.InstanceMetadata(meta.Id) @@ -130,6 +148,27 @@ func (m *manager) saveMetadata(meta *metadata) error { tmp.Close() return fmt.Errorf("chmod temporary metadata: %w", err) } + var dir *os.File + if durable { + // The syncs run without the alias lock. A restore waiting to alias a + // source directory holds back every metadata read on the host, so it + // must not wait on a disk. An alias puts the directory back before it + // lets readers in again, so the file and directory opened here are + // still this instance's once the lock is taken again. + dir, err = os.Open(filepath.Dir(metaPath)) + if err != nil { + tmp.Close() + return fmt.Errorf("open instance directory: %w", err) + } + defer dir.Close() + unlockAliasReaders() + err = tmp.Sync() + unlockAliasReaders = hypervisor.LockSnapshotSourceAliasReaders() + if err != nil { + tmp.Close() + return fmt.Errorf("sync temporary metadata: %w", err) + } + } if err := tmp.Close(); err != nil { return fmt.Errorf("close temporary metadata: %w", err) } @@ -140,9 +179,31 @@ func (m *manager) saveMetadata(meta *metadata) error { m.syncAdmissionAllocation(meta) + if durable { + // The rename lasts only once the directory is synced too. + unlockAliasReaders() + unlockAliasReaders = func() {} + fsync := (*os.File).Sync + if m.syncDirFn != nil { + fsync = m.syncDirFn + } + if err := fsync(dir); err != nil { + return fmt.Errorf("sync instance directory: %w", err) + } + } + return nil } +func syncDir(path string) error { + dir, err := os.Open(path) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + // createOverlayDisk creates a sparse overlay disk for the instance func (m *manager) createOverlayDisk(id string, sizeBytes int64) error { overlayPath := m.paths.InstanceOverlay(id) diff --git a/lib/instances/types.go b/lib/instances/types.go index 50b563e76..cc2a708cb 100644 --- a/lib/instances/types.go +++ b/lib/instances/types.go @@ -100,6 +100,13 @@ type StoredMetadata struct { // IdentityRekeyPending marks a macOS clone whose SSH host keys still come from its // source. The next start rekeys them and clears the flag. IdentityRekeyPending bool `json:"identity_rekey_pending,omitempty"` + // ForkPending marks a fork that has not yet reached the state its caller + // asked for, and names the API process that is bringing it there. It is + // set when the fork's metadata is first saved and cleared when the fork + // request succeeds. A fork still marked once that process is gone was cut + // short by a crash or kill, so its caller never got an answer; the next + // start deletes it instead of leaving it behind holding its resources. + ForkPending *ForkOwner `json:"fork_pending,omitempty"` // Resources (matching Cloud Hypervisor terminology) Size int64 // Base memory in bytes diff --git a/lib/network/allocate.go b/lib/network/allocate.go index 27f333c2a..4b2082d00 100644 --- a/lib/network/allocate.go +++ b/lib/network/allocate.go @@ -376,13 +376,43 @@ func (m *manager) applyRateLimitAsync(ctx context.Context, req rateLimitRequest) // It deletes the TAP device using the deterministic name from the instance ID and // the persisted class ID if available. func (m *manager) ReleaseByInstanceID(ctx context.Context, instanceID string) error { + tap := GenerateTAPName(instanceID) + // TAP names use only the first eight ID characters. Don't guess which + // guest owns the link when cleaning up without an allocation. + guests, err := os.ReadDir(m.paths.GuestsDir()) + if err != nil && !os.IsNotExist(err) { + return err + } + for _, guest := range guests { + if guest.IsDir() && guest.Name() != instanceID && GenerateTAPName(guest.Name()) == tap { + return m.releaseAmbiguousTAP(instanceID, tap, guest.Name()) + } + } return m.ReleaseAllocation(ctx, &Allocation{ InstanceID: instanceID, - TAPDevice: GenerateTAPName(instanceID), + TAPDevice: tap, ClassID: m.loadClassID(instanceID), }) } +// A missing TAP is already released, even when two guest IDs share its name. +func (m *manager) releaseAmbiguousTAP(instanceID, tap, otherID string) error { + links, err := net.Interfaces() + if err != nil { + return err + } + for _, link := range links { + if link.Name == tap { + return fmt.Errorf("cannot release %s by ID: also matches guest %s", tap, otherID) + } + } + m.forgetPendingAllocation(instanceID) + m.tcMu.Lock() + defer m.tcMu.Unlock() + m.clearClassID(instanceID) + return nil +} + // ReleaseAllocation cleans up network allocation (shutdown/delete) // Takes the allocation directly since it should be retrieved before the VMM is killed. // If alloc is nil, this is a no-op (network not allocated or already released). @@ -399,14 +429,13 @@ func (m *manager) ReleaseAllocation(ctx context.Context, alloc *Allocation) erro } m.forgetPendingAllocation(alloc.InstanceID) - // 1. Delete TAP device (best effort), using the TAP's live tc filter for HTB cleanup. + // 1. Delete TAP device using the TAP's live tc filter for HTB cleanup. // Serialize with async tc setup so queued rate-limit work cannot race with // class removal and leave stale bridge state behind. if err := m.deleteTAPDeviceForInstanceSerialized(ctx, alloc.InstanceID, alloc.TAPDevice); err != nil { - log.WarnContext(ctx, "failed to delete TAP device", "tap", alloc.TAPDevice, "error", err) - } else { - m.recordTAPOperation(ctx, "delete") + return fmt.Errorf("release TAP %s: %w", alloc.TAPDevice, err) } + m.recordTAPOperation(ctx, "delete") log.InfoContext(ctx, "released network", "instance_id", alloc.InstanceID, diff --git a/lib/network/bridge_linux.go b/lib/network/bridge_linux.go index e19001164..b2b7f7c24 100644 --- a/lib/network/bridge_linux.go +++ b/lib/network/bridge_linux.go @@ -1127,8 +1127,11 @@ func deriveClassID(tapName string) string { func (m *manager) deleteTAPDevice(ctx context.Context, tapName string) error { link, err := netlink.LinkByName(tapName) if err != nil { - // TAP doesn't exist, nothing to do - return nil + var notFound netlink.LinkNotFoundError + if errors.As(err, ¬Found) { + return nil + } + return err } // Remove HTB class from bridge before deleting TAP diff --git a/lib/network/manager_test.go b/lib/network/manager_test.go index b9e0699cb..9199e19b6 100644 --- a/lib/network/manager_test.go +++ b/lib/network/manager_test.go @@ -143,6 +143,13 @@ func TestDefaultNetworkCacheReturnsCopy(t *testing.T) { assert.Equal(t, "hm0", m.cachedDefaultNetwork().Bridge) } +func TestReleaseByInstanceIDWithMissingSharedTAP(t *testing.T) { + p := paths.New(t.TempDir()) + require.NoError(t, os.MkdirAll(p.InstanceDir("abcdefgh-other"), 0755)) + m := &manager{paths: p} + require.NoError(t, m.ReleaseByInstanceID(t.Context(), "abcdefgh-fork")) +} + func TestGenerateTAPName(t *testing.T) { tests := []struct { name string diff --git a/lib/providers/providers.go b/lib/providers/providers.go index 342842e13..a3e42bab4 100644 --- a/lib/providers/providers.go +++ b/lib/providers/providers.go @@ -8,6 +8,7 @@ import ( "os" "strconv" "strings" + "sync" "time" "github.com/c2h5oh/datasize" @@ -58,17 +59,28 @@ func ProvideContext(log *slog.Logger) context.Context { return logger.AddToContext(context.Background(), log) } -// ProvideConfig provides the application configuration. -// Panics if configuration is invalid (prevents startup with bad config). -// Config path can be specified via CONFIG_PATH env var or defaults to platform-specific locations. -func ProvideConfig() *config.Config { - configPath := os.Getenv("CONFIG_PATH") - cfg, err := config.Load(configPath) +// ServerConfig loads the configuration once so dependency initialization uses +// the same data directory the API locked before startup. +func ServerConfig() (*config.Config, error) { + return loadServerConfig() +} + +var loadServerConfig = sync.OnceValues(func() (*config.Config, error) { + cfg, err := config.Load(os.Getenv("CONFIG_PATH")) if err != nil { - panic(fmt.Sprintf("failed to load configuration: %v", err)) + return nil, fmt.Errorf("load configuration: %w", err) } if err := cfg.Validate(); err != nil { - panic(fmt.Sprintf("invalid configuration: %v", err)) + return nil, fmt.Errorf("invalid configuration: %w", err) + } + return cfg, nil +}) + +// ProvideConfig supplies the validated configuration to the dependency graph. +func ProvideConfig() *config.Config { + cfg, err := ServerConfig() + if err != nil { + panic(err) } return cfg }