From cd6261210ad45589dd207aa2777808de40a61a39 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:21:33 +0000 Subject: [PATCH] Guard pending fork transitions and verify cleanup ownership --- lib/devices/manager.go | 20 ++++++++- lib/devices/manager_test.go | 32 ++++++++++---- lib/devices/vfio_linux.go | 2 +- lib/hypervisor/vz_shim_pids.go | 25 ++++++++--- lib/hypervisor/vz_shim_pids_darwin.go | 2 +- lib/hypervisor/vz_shim_pids_test.go | 9 ++-- lib/instances/fork.go | 16 +++++++ lib/instances/lifecycle_noop_test.go | 35 +++++++++++++++ lib/instances/macos.go | 3 +- lib/instances/macos_boot_admission_test.go | 18 ++++++++ lib/instances/macos_identity.go | 8 ++-- lib/instances/manager.go | 26 +++++------ lib/instances/process_identity.go | 9 ++-- lib/instances/process_identity_darwin_test.go | 43 +++++++++++++++++++ lib/instances/restart_policy.go | 16 +++---- lib/instances/restart_policy_test.go | 20 +++++++++ lib/instances/storage.go | 3 ++ 17 files changed, 233 insertions(+), 54 deletions(-) create mode 100644 lib/instances/process_identity_darwin_test.go diff --git a/lib/devices/manager.go b/lib/devices/manager.go index b12f93624..b05914346 100644 --- a/lib/devices/manager.go +++ b/lib/devices/manager.go @@ -359,7 +359,7 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error { } log := logger.FromContext(ctx) - if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil { + if err := m.unbindAndVerify(device.PCIAddress); err != nil { return err } @@ -414,6 +414,22 @@ 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 { @@ -427,7 +443,7 @@ func (m *manager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceI return nil } // A retry after the unbind but before the save sees ErrNotBound. - if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) { + if err := m.unbindAndVerify(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) { return err } device.AttachedTo = nil diff --git a/lib/devices/manager_test.go b/lib/devices/manager_test.go index 2d8c9fce3..fc1d3488d 100644 --- a/lib/devices/manager_test.go +++ b/lib/devices/manager_test.go @@ -185,28 +185,36 @@ func TestDeviceLookupAndDeleteRejectPathTraversal(t *testing.T) { type releaseTestBinder struct { *VFIOBinder - unbind func(string) error + unbind func(string) error + bound bool + inspectErr error } -func (b releaseTestBinder) UnbindFromVFIO(addr string) error { return b.unbind(addr) } +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 }{ - {"unbind", nil}, - {"already-unbound", ErrNotBound}, + {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) - busy := errors.New("device busy") - result := busy + result := tc.unbindErr var calls int - m.vfioBinder = releaseTestBinder{unbind: func(addr string) error { + 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) @@ -215,8 +223,14 @@ func TestReleaseInstanceDeviceKeepsOwnerUntilUnbound(t *testing.T) { return result }} - require.ErrorIs(t, m.ReleaseInstanceDevice(t.Context(), device.Id, owner), busy) - result = tc.retryResult + 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) diff --git a/lib/devices/vfio_linux.go b/lib/devices/vfio_linux.go index fd75219c1..b2e7ac838 100644 --- a/lib/devices/vfio_linux.go +++ b/lib/devices/vfio_linux.go @@ -129,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/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/fork.go b/lib/instances/fork.go index eb443aeff..4e42526da 100644 --- a/lib/instances/fork.go +++ b/lib/instances/fork.go @@ -641,6 +641,22 @@ func (m *manager) forkOwnerGone(owner ForkOwner) bool { 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 diff --git a/lib/instances/lifecycle_noop_test.go b/lib/instances/lifecycle_noop_test.go index 3ab5ac51e..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) @@ -415,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 0eaa13c99..22bde2224 100644 --- a/lib/instances/manager.go +++ b/lib/instances/manager.go @@ -618,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 { @@ -636,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) @@ -658,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 { @@ -717,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. @@ -734,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) 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/storage.go b/lib/instances/storage.go index 5dca83196..a1a05085c 100644 --- a/lib/instances/storage.go +++ b/lib/instances/storage.go @@ -100,6 +100,9 @@ func (m *manager) loadMetadataTimed(id string, timings *metadataScanTimings) (*m } 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