From 6f0bc7168f4dd26a8124b9b203ccec9c34cbfee4 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:25:10 +0000 Subject: [PATCH] Protect fork recovery from stale writers and inherited state --- DEVELOPMENT.md | 1 + cmd/api/data_dir_lock.go | 28 +++++ cmd/api/data_dir_lock_test.go | 41 +++++++ cmd/api/main.go | 19 +-- lib/devices/manager.go | 30 ++++- lib/devices/manager_test.go | 15 +++ lib/hypervisor/firecracker/process.go | 14 ++- lib/instances/delete.go | 11 +- lib/instances/fork_alias_recovery.go | 126 +++++++++++++++++++ lib/instances/fork_pending_test.go | 6 +- lib/instances/fork_recovery_guards_test.go | 134 +++++++++++++++++++++ lib/instances/lifecycle_noop_test.go | 8 +- lib/instances/snapshot.go | 54 ++++----- lib/instances/snapshot_alias_lock.go | 6 - lib/providers/providers.go | 24 ++-- 15 files changed, 442 insertions(+), 75 deletions(-) create mode 100644 cmd/api/data_dir_lock.go create mode 100644 cmd/api/data_dir_lock_test.go create mode 100644 lib/instances/fork_alias_recovery.go create mode 100644 lib/instances/fork_recovery_guards_test.go 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 92cfdd503..881fb7c10 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,17 @@ 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() + if err := instances.RecoverParkedForkSources(paths.New(cfg.DataDir)); err != nil { + return fmt.Errorf("recover parked fork sources: %w", err) } // Configure GPU profile cache TTL diff --git a/lib/devices/manager.go b/lib/devices/manager.go index 30763c04d..091701e4f 100644 --- a/lib/devices/manager.go +++ b/lib/devices/manager.go @@ -65,6 +65,9 @@ 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 + // ReconcileDevices cleans up stale device state on startup. // It detects devices with AttachedTo referencing non-existent instances // and clears the orphaned attachment state. @@ -322,8 +325,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,7 +342,11 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error { return ErrInUse } - // Unbind from VFIO + return m.unbindFromVFIOLocked(ctx, device) +} + +func (m *manager) unbindFromVFIOLocked(ctx context.Context, device *Device) error { + log := logger.FromContext(ctx) if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil { return err } @@ -397,6 +402,25 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error { return m.saveDevice(device) } +// 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 + } + device.AttachedTo = nil + if err := m.saveDevice(device); err != nil { + return err + } + return m.unbindFromVFIOLocked(ctx, 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) diff --git a/lib/devices/manager_test.go b/lib/devices/manager_test.go index 3c429f7e0..8ad0ac6d9 100644 --- a/lib/devices/manager_test.go +++ b/lib/devices/manager_test.go @@ -182,6 +182,21 @@ func TestDeviceLookupAndDeleteRejectPathTraversal(t *testing.T) { require.FileExists(t, marker) } +func TestReleaseInstanceDeviceClearsItsOwnAttachment(t *testing.T) { + p := paths.New(t.TempDir()) + m := NewManager(p).(*manager) + owner := "fork" + device := &Device{Id: "dev-1", PCIAddress: "test-device", AttachedTo: &owner} + require.NoError(t, os.MkdirAll(p.DeviceDir(device.Id), 0755)) + require.NoError(t, m.saveDevice(device)) + + // There is no hardware to unbind. Detachment must still persist. + require.Error(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner)) + got, err := m.loadDevice(device.Id) + require.NoError(t, err) + require.Nil(t, got.AttachedTo) +} + func TestSaveLoadDevice_MetadataRoundTrip(t *testing.T) { p := paths.New(t.TempDir()) mgr := &manager{ diff --git a/lib/hypervisor/firecracker/process.go b/lib/hypervisor/firecracker/process.go index 443a398b5..721deb0c4 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,7 +251,7 @@ 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) } diff --git a/lib/instances/delete.go b/lib/instances/delete.go index 37fd908ca..95d0fda6a 100644 --- a/lib/instances/delete.go +++ b/lib/instances/delete.go @@ -173,15 +173,8 @@ 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 { + log.WarnContext(ctx, "failed to release passthrough device", "instance_id", id, "device", deviceID, "error", err) } } } diff --git a/lib/instances/fork_alias_recovery.go b/lib/instances/fork_alias_recovery.go new file mode 100644 index 000000000..fc29f30e6 --- /dev/null +++ b/lib/instances/fork_alias_recovery.go @@ -0,0 +1,126 @@ +package instances + +import ( + "encoding/json" + "fmt" + "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. Call under the data directory lock, before even +// listing instances: a lookup by source ID would otherwise read the fork. +func RecoverParkedForkSources(p *paths.Paths) error { + entries, err := os.ReadDir(p.GuestsDir()) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + backups := make(map[string]string) + 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 { + return fmt.Errorf("invalid source ID in backup %q", entry.Name()) + } + if other, ok := backups[id]; ok { + return fmt.Errorf("ambiguous backups for %q: %q and %q", id, other, entry.Name()) + } + backups[id] = entry.Name() + } + for id, backup := range backups { + if err := restoreParkedForkSource(p, id, backup); err != nil { + return fmt.Errorf("restore %s from %s: %w", id, backup, err) + } + } + if len(backups) > 0 { + return syncDir(p.GuestsDir()) + } + return nil +} + +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); 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: + return err // Never replace an ordinary source directory. + } + return os.Rename(p.InstanceDir(backup), source) +} + +func verifyForkAlias(p *paths.Paths, source, link string) 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 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_test.go b/lib/instances/fork_pending_test.go index 729d06ab4..72015e3a3 100644 --- a/lib/instances/fork_pending_test.go +++ b/lib/instances/fork_pending_test.go @@ -290,16 +290,12 @@ type detachGateDeviceManager struct { release chan struct{} } -func (m detachGateDeviceManager) MarkDetached(ctx context.Context, deviceID string) error { +func (m detachGateDeviceManager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error { m.arrived <- deviceID <-m.release return nil } -func (m detachGateDeviceManager) UnbindFromVFIO(ctx context.Context, id string) error { - 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) { diff --git a/lib/instances/fork_recovery_guards_test.go b/lib/instances/fork_recovery_guards_test.go new file mode 100644 index 000000000..3c10d57e4 --- /dev/null +++ b/lib/instances/fork_recovery_guards_test.go @@ -0,0 +1,134 @@ +package instances + +import ( + "encoding/json" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/kernel/hypeman/lib/devices" + "github.com/kernel/hypeman/lib/hypervisor" + "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)) + source := owner + data, err := json.Marshal(devices.Device{Id: dev, AttachedTo: &source, 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)) + + 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 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", "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 == "two-backups" { + require.NoError(t, os.Mkdir(sourceDir+".fork-bak.124", 0755)) + } + err = RecoverParkedForkSources(m.paths) + if layout != "link" && layout != "source-absent" { + require.Error(t, err) + require.DirExists(t, backup) + require.DirExists(t, forkDir) + if layout == "existing-directory" { + 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) + }) + } +} diff --git a/lib/instances/lifecycle_noop_test.go b/lib/instances/lifecycle_noop_test.go index 4926894cf..3ab5ac51e 100644 --- a/lib/instances/lifecycle_noop_test.go +++ b/lib/instances/lifecycle_noop_test.go @@ -356,11 +356,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 +367,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) diff --git a/lib/instances/snapshot.go b/lib/instances/snapshot.go index 49d695ca5..a9b2f7a6d 100644 --- a/lib/instances/snapshot.go +++ b/lib/instances/snapshot.go @@ -289,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 } @@ -581,45 +584,42 @@ func (m *manager) forkSnapshot(ctx context.Context, snapshotID string, req ForkS 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) } return fmt.Errorf("copy guest directory into snapshot: %w", err) } - return clearCopiedForkPending(filepath.Join(snapshotGuestDir, filepath.Base(m.paths.InstanceMetadata(sourceInstanceID)))) + return nil } -// clearCopiedForkPending removes the fork-pending mark from the copy of an -// instance's metadata that its snapshot payload holds. A restore puts that -// file back as the instance's own until it saves the restored metadata; cut -// short there, a mark in it would have the next start delete the instance. -func clearCopiedForkPending(metaPath string) error { - data, err := os.ReadFile(metaPath) +func copySnapshotMetadata(src, dst string) error { + data, err := os.ReadFile(src) if err != nil { - if os.IsNotExist(err) { - return nil - } - return fmt.Errorf("read snapshot payload metadata: %w", err) - } - var meta metadata - if err := json.Unmarshal(data, &meta); err != nil { - return fmt.Errorf("unmarshal snapshot payload metadata: %w", err) - } - if meta.ForkPending == nil { - return nil + return err } - meta.ForkPending = nil - data, err = json.MarshalIndent(&meta, "", " ") - if err != nil { - return fmt.Errorf("marshal snapshot payload metadata: %w", err) + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err } - if err := os.WriteFile(metaPath, data, 0644); err != nil { - return fmt.Errorf("write snapshot payload metadata: %w", err) + if _, marked := fields["fork_pending"]; marked { + delete(fields, "fork_pending") + data, err = json.MarshalIndent(fields, "", " ") + if err != nil { + return err + } } - return nil + return os.WriteFile(dst, data, 0644) } func (m *manager) replaceInstanceWithSnapshotPayload(snapshotID, instanceID string) error { diff --git a/lib/instances/snapshot_alias_lock.go b/lib/instances/snapshot_alias_lock.go index d994bf331..412921b01 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( diff --git a/lib/providers/providers.go b/lib/providers/providers.go index 342842e13..7f5de14d4 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,24 @@ 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. +var ServerConfig = 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 }