From d4fb892ce45c35e8e80cc5a5c698e36b00078988 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:07:48 +0000 Subject: [PATCH 1/5] Give VFIO guests time to exit when many are terminated together A VMM with VFIO devices releases them on its way out, and the host driver is slower at that when many guests go down at once. The grace after SIGTERM was fixed, so deleting 16 or more vGPU guests together hard-killed them mid-release and then failed most of the deletes about a second before the VMMs were gone, leaving the instances for a retry. The grace now grows by one second for every other VFIO teardown in flight, up to a minute. A guest terminated alone waits as before. --- lib/instances/manager.go | 3 + lib/instances/process_identity.go | 39 ++++++++++- lib/instances/process_identity_linux_test.go | 74 ++++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) diff --git a/lib/instances/manager.go b/lib/instances/manager.go index ed85f22f4..a99e14305 100644 --- a/lib/instances/manager.go +++ b/lib/instances/manager.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "sync" + "sync/atomic" "time" "github.com/kernel/hypeman/lib/devices" @@ -228,6 +229,8 @@ type manager struct { vgpuReconcileInterval time.Duration vfioTermGrace time.Duration + // vfioTeardowns counts the VMMs with VFIO devices being terminated now. + vfioTeardowns atomic.Int32 // Hypervisor support vmStarters map[hypervisor.Type]hypervisor.VMStarter diff --git a/lib/instances/process_identity.go b/lib/instances/process_identity.go index 57aac3af7..08ac860bb 100644 --- a/lib/instances/process_identity.go +++ b/lib/instances/process_identity.go @@ -27,6 +27,21 @@ const linuxBootIDPath = "/proc/sys/kernel/random/boot_id" // does not unstick it, so the wait is short to keep stop and delete fast. const hypervisorSIGKILLWaitTimeout = 2 * time.Second +const ( + // vfioTeardownQueueAllowance is the extra time a VMM with VFIO devices + // gets to exit on SIGTERM for every other such VMM being terminated at + // the same time. The device is released on the VMM's way out, and the + // host driver is slower at that when many go at once: vGPU guests exited + // about a second after SIGTERM when up to 8 were terminated together, but + // took up to 10 s when 16 or 26 were. That outlasted the fixed grace, so + // they were hard-killed mid-release and their deletes failed about a + // second before the VMMs were gone. + vfioTeardownQueueAllowance = time.Second + // vfioTeardownMaxAllowance caps the allowance for a queue of any length. + vfioTeardownMaxAllowance = time.Minute + vfioTeardownPollInterval = 200 * time.Millisecond +) + func (m *manager) vfioTerminationGrace() time.Duration { if m.vfioTermGrace > 0 { return m.vfioTermGrace @@ -37,7 +52,9 @@ func (m *manager) vfioTerminationGrace() time.Duration { // SIGKILL during guest driver init can wedge a VF until the parent GPU is reset. func (m *manager) terminateThenKill(ctx context.Context, inst *Instance, pid int) error { if hasVFIODevices(&inst.StoredMetadata) { - if syscall.Kill(pid, syscall.SIGTERM) == nil && WaitForProcessExit(pid, m.vfioTerminationGrace()) { + m.vfioTeardowns.Add(1) + defer m.vfioTeardowns.Add(-1) + if syscall.Kill(pid, syscall.SIGTERM) == nil && m.waitForVFIOTeardown(pid, m.vfioTerminationGrace()) { return nil } logger.FromContext(ctx).WarnContext(ctx, "hypervisor with VFIO devices did not exit on SIGTERM; hard-killing, device may wedge if the guest driver was initializing", @@ -46,6 +63,26 @@ func (m *manager) terminateThenKill(ctx context.Context, inst *Instance, pid int return killProcessAndWait(pid) } +// waitForVFIOTeardown waits for pid to exit for base plus the queue allowance. +// The allowance follows the largest number of VFIO teardowns seen in flight +// during the wait: a VMM that started exiting alone is still slowed down by +// the ones that join it. +func (m *manager) waitForVFIOTeardown(pid int, base time.Duration) bool { + start := time.Now() + peak := int32(1) + for { + peak = max(peak, m.vfioTeardowns.Load()) + allowance := min(time.Duration(peak-1)*vfioTeardownQueueAllowance, vfioTeardownMaxAllowance) + remaining := base + allowance - time.Since(start) + if remaining <= 0 { + return false + } + if WaitForProcessExit(pid, min(remaining, vfioTeardownPollInterval)) { + return true + } + } +} + // killProcessAndWait SIGKILLs pid and waits for it to exit. A process that // survives the first wait gets its process group killed too (the hypervisor // may have spawned children in its own group) and a short grace period. An diff --git a/lib/instances/process_identity_linux_test.go b/lib/instances/process_identity_linux_test.go index 0bf65d7af..8ce958ff1 100644 --- a/lib/instances/process_identity_linux_test.go +++ b/lib/instances/process_identity_linux_test.go @@ -721,6 +721,80 @@ func TestKillHypervisorEscalatesToSIGKILLWhenSIGTERMIgnored(t *testing.T) { assert.ErrorIs(t, syscall.Kill(pid, 0), syscall.ESRCH, "SIGTERM-ignoring hypervisor must still be hard-killed") } +// A VMM with VFIO devices exits only after the host driver has released its +// device, and the driver is slower at that when many guests go down together. +// The wait has to grow with their number, or a mass delete hard-kills and +// then gives up on VMMs that were about to exit. +func TestKillHypervisorWaitsLongerWhileOtherVFIOTeardownsAreInFlight(t *testing.T) { + for _, tc := range []struct { + name string + othersInQueue int32 + exitsCleanly bool + }{ + {name: "alone", othersInQueue: 0, exitsCleanly: false}, + {name: "behind two others", othersInQueue: 2, exitsCleanly: true}, + } { + t.Run(tc.name, func(t *testing.T) { + markerPath := filepath.Join(t.TempDir(), "released") + // Stands in for a VMM whose device release takes 0.6 s after SIGTERM. + pid, identity := startTrapProcess(t, "sleep 0.6; touch "+markerPath+"; exit 0") + + m := &manager{vfioTermGrace: 100 * time.Millisecond} + m.vfioTeardowns.Store(tc.othersInQueue) + require.NoError(t, m.killHypervisor(context.Background(), &Instance{ + State: StateRunning, + StoredMetadata: StoredMetadata{ + Id: "kill-test", + GPUProfile: "NVIDIA L40S-1Q", + GPUFramework: devices.VGPUFrameworkVendorVFIO, + GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", + HypervisorProcessIdentity: identity, + SocketPath: filepath.Join(t.TempDir(), "missing.sock"), + }, + })) + + assert.ErrorIs(t, syscall.Kill(pid, 0), syscall.ESRCH) + assert.Equal(t, tc.othersInQueue, m.vfioTeardowns.Load(), "the teardown must leave the queue when it returns") + if tc.exitsCleanly { + assert.FileExists(t, markerPath, "a queued VMM must be allowed to finish releasing its device") + } else { + assert.NoFileExists(t, markerPath, "without a queue the short grace still applies") + } + }) + } +} + +// The queue is made of the teardowns themselves: one that is in flight has to +// count for the next one that starts. +func TestKillHypervisorCountsVFIOTeardownsInFlight(t *testing.T) { + m := &manager{vfioTermGrace: 250 * time.Millisecond} + kill := func(identity HypervisorProcessIdentity) error { + return m.killHypervisor(context.Background(), &Instance{ + State: StateRunning, + StoredMetadata: StoredMetadata{ + Id: "kill-test", + GPUProfile: "NVIDIA L40S-1Q", + GPUFramework: devices.VGPUFrameworkVendorVFIO, + GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", + HypervisorProcessIdentity: identity, + SocketPath: filepath.Join(t.TempDir(), "missing.sock"), + }, + }) + } + markerPath := filepath.Join(t.TempDir(), "released") + _, first := startTrapProcess(t, "sleep 0.6; exit 0") + _, second := startTrapProcess(t, "sleep 0.6; touch "+markerPath+"; exit 0") + + firstDone := make(chan error, 1) + go func() { firstDone <- kill(first) }() + require.Eventually(t, func() bool { return m.vfioTeardowns.Load() == 1 }, 5*time.Second, time.Millisecond) + + require.NoError(t, kill(second)) + assert.FileExists(t, markerPath, "a teardown in flight must lengthen the wait of one that starts meanwhile") + require.NoError(t, <-firstDone) + assert.Zero(t, m.vfioTeardowns.Load()) +} + func TestKillHypervisorHardKillsNonVGPUHypervisor(t *testing.T) { markerPath := filepath.Join(t.TempDir(), "terminated") pid, identity := startTrapProcess(t, "touch "+markerPath+"; exit 0") From 202e651c368d6ae7e7ec01087ebfc206eb7a863d Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:41:23 +0000 Subject: [PATCH 2/5] Fit VFIO teardown grace to caller deadlines and include QEMU rollback --- lib/hypervisor/qemu/process.go | 30 ++--- lib/hypervisor/qemu/process_test.go | 72 +++++++---- lib/hypervisor/vfio.go | 53 ++++++++- lib/hypervisor/vfio_test.go | 65 ++++++++++ lib/instances/manager.go | 3 - lib/instances/process_identity.go | 53 +++------ lib/instances/process_identity_linux_test.go | 118 ++++++++++--------- 7 files changed, 253 insertions(+), 141 deletions(-) create mode 100644 lib/hypervisor/vfio_test.go diff --git a/lib/hypervisor/qemu/process.go b/lib/hypervisor/qemu/process.go index b6da760cc..38f980ea7 100644 --- a/lib/hypervisor/qemu/process.go +++ b/lib/hypervisor/qemu/process.go @@ -229,7 +229,6 @@ func buildQMPArgs(socketPath string) []string { type startedProcess struct { pid int socketPath string - termGrace time.Duration waitDone chan error waitConsumed bool waitErr error @@ -296,23 +295,27 @@ func (p *startedProcess) waitFor(d time.Duration) bool { func (p *startedProcess) cleanup() { if _, exited := p.checkExited(); !exited { - terminated := false - if p.termGrace > 0 { - if syscall.Kill(p.pid, syscall.SIGTERM) == nil { - terminated = p.waitFor(p.termGrace) - } - } - if !terminated { - _ = syscall.Kill(p.pid, syscall.SIGKILL) - _ = p.wait() - } + _ = syscall.Kill(p.pid, syscall.SIGKILL) + _ = p.wait() } _ = os.Remove(p.socketPath) } // cleanupFailedStart kills a QEMU process whose start failed. The failure can // come after the QMP client is pooled, so the client is dropped with it. -func cleanupFailedStart(proc *startedProcess) { +func cleanupFailedStart(ctx context.Context, proc *startedProcess, termGrace time.Duration) { + if _, exited := proc.checkExited(); !exited && termGrace > 0 { + teardown := hypervisor.BeginVFIOTeardown() + defer teardown.Done() + if syscall.Kill(proc.pid, syscall.SIGTERM) == nil { + start := time.Now() + if _, err := teardown.Wait(ctx, termGrace, time.Second, proc.waitFor); err != nil { + // Rollback must reap the child even after cancellation, but + // don't cut its base grace short to do so. + proc.waitFor(termGrace - time.Since(start)) + } + } + } proc.cleanup() releaseVMMState(proc.socketPath) } @@ -398,11 +401,10 @@ func (s *Starter) startQEMUProcess(ctx context.Context, p *paths.Paths, version } pid := proc.pid - proc.termGrace = termGrace log.DebugContext(processCtx, "QEMU process started", "pid", pid, "duration_ms", time.Since(processStartTime).Milliseconds()) // Setup cleanup to kill, reap, and remove the socket if subsequent steps fail. - cu := cleanup.Make(func() { cleanupFailedStart(proc) }) + cu := cleanup.Make(func() { cleanupFailedStart(ctx, proc, termGrace) }) // Wait for socket to be ready socketWaitStart := time.Now() diff --git a/lib/hypervisor/qemu/process_test.go b/lib/hypervisor/qemu/process_test.go index 4411f3d9c..ec42f9553 100644 --- a/lib/hypervisor/qemu/process_test.go +++ b/lib/hypervisor/qemu/process_test.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "errors" + "fmt" "os" "os/exec" "path/filepath" @@ -408,7 +409,7 @@ func TestCleanupFailedStartDropsPooledClient(t *testing.T) { proc, err := startManagedProcess(exec.Command("sleep", "30"), socketPath) require.NoError(t, err) - cleanupFailedStart(proc) + cleanupFailedStart(t.Context(), proc, 0) clientPool.RLock() _, pooled := clientPool.clients[socketPath] @@ -479,40 +480,59 @@ func TestVFIOTermGraceFor(t *testing.T) { } } -func TestCleanupSIGTERMsProcessWithTermGrace(t *testing.T) { - socketPath := filepath.Join(t.TempDir(), "qemu.sock") - markerPath := filepath.Join(t.TempDir(), "terminated") - - cmd := exec.Command("sh", "-c", "trap 'touch "+markerPath+"; exit 0' TERM; echo ready; sleep 30 & wait") +func startCleanupProcess(t *testing.T, onTerm string) (*startedProcess, *exec.Cmd) { + t.Helper() + cmd := exec.Command("sh", "-c", "trap '"+onTerm+"' TERM; echo ready; read -r line") + stdin, err := cmd.StdinPipe() + require.NoError(t, err) stdout, err := cmd.StdoutPipe() require.NoError(t, err) - proc, err := startManagedProcess(cmd, socketPath) + proc, err := startManagedProcess(cmd, filepath.Join(t.TempDir(), "qemu.sock")) require.NoError(t, err) + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = stdin.Close() }) _, err = bufio.NewReader(stdout).ReadString('\n') require.NoError(t, err) - proc.termGrace = 5 * time.Second - - proc.cleanup() + return proc, cmd +} - assert.FileExists(t, markerPath, "process must get SIGTERM, not SIGKILL, when termGrace is set") - require.NoFileExists(t, socketPath) - require.NotNil(t, cmd.ProcessState) +func TestCleanupSIGTERMsProcessWithTermGrace(t *testing.T) { + // Even rollback of a canceled startup owes the child the base SIGTERM grace. + ctx, cancel := context.WithCancel(t.Context()) + cancel() + proc, cmd := startCleanupProcess(t, "sleep 0.1; exit 0") + cleanupFailedStart(ctx, proc, time.Second) + require.True(t, cmd.ProcessState.Success()) + require.NoFileExists(t, proc.socketPath) } func TestCleanupEscalatesToSIGKILLAfterTermGrace(t *testing.T) { - socketPath := filepath.Join(t.TempDir(), "qemu.sock") + proc, _ := startCleanupProcess(t, "") + cleanupFailedStart(t.Context(), proc, 50*time.Millisecond) + assert.ErrorIs(t, syscall.Kill(proc.pid, 0), syscall.ESRCH) + require.NoFileExists(t, proc.socketPath) +} - cmd := exec.Command("sh", "-c", "trap '' TERM; echo ready; sleep 30 & wait") - stdout, err := cmd.StdoutPipe() - require.NoError(t, err) - proc, err := startManagedProcess(cmd, socketPath) - require.NoError(t, err) - _, err = bufio.NewReader(stdout).ReadString('\n') +func TestCleanupSharesVFIOGraceWithLifecycleTeardown(t *testing.T) { + started := filepath.Join(t.TempDir(), "terminating") + proc, cmd := startCleanupProcess(t, fmt.Sprintf("touch %q; sleep 0.8; exit 0", started)) + done := make(chan struct{}) + go func() { cleanupFailedStart(t.Context(), proc, 400*time.Millisecond); close(done) }() + defer func() { <-done }() + require.Eventually(t, func() bool { _, err := os.Stat(started); return err == nil }, 5*time.Second, time.Millisecond) + + peer := hypervisor.BeginVFIOTeardown() + defer peer.Done() + release := time.After(600 * time.Millisecond) + exited, err := peer.Wait(t.Context(), 300*time.Millisecond, 0, func(d time.Duration) bool { + select { + case <-release: + return true + case <-time.After(d): + return false + } + }) require.NoError(t, err) - proc.termGrace = 50 * time.Millisecond - - proc.cleanup() - - assert.ErrorIs(t, syscall.Kill(proc.pid, 0), syscall.ESRCH, "SIGTERM-ignoring process must still be hard-killed") - require.NoFileExists(t, socketPath) + assert.True(t, exited, "the lifecycle teardown must count the rollback") + <-done + assert.True(t, cmd.ProcessState.Success(), "rollback must gain grace when a lifecycle teardown joins") } diff --git a/lib/hypervisor/vfio.go b/lib/hypervisor/vfio.go index 1744cfc84..09771ba1f 100644 --- a/lib/hypervisor/vfio.go +++ b/lib/hypervisor/vfio.go @@ -1,7 +1,56 @@ package hypervisor -import "time" +import ( + "context" + "sync/atomic" + "time" +) // VFIOTermGrace allows VFIO teardown to finish after SIGTERM before SIGKILL; -// SIGKILL during initialization can wedge the VF, while teardown takes 1-2s. +// SIGKILL during initialization can wedge the VF. const VFIOTermGrace = 5 * time.Second + +var activeVFIOTeardowns atomic.Int32 + +// VFIOTeardown counts a VMM against the host driver until it exits or its +// caller gives up, including time spent waiting after SIGKILL. +type VFIOTeardown struct { + atStart int32 +} + +func BeginVFIOTeardown() VFIOTeardown { + return VFIOTeardown{atStart: activeVFIOTeardowns.Add(1)} +} + +func (VFIOTeardown) Done() { activeVFIOTeardowns.Add(-1) } + +// Wait allows one extra second per overlapping teardown, up to a minute: +// 16 simultaneous vGPU deletes can take 10s in the driver after SIGTERM. +// It leaves reserve before the caller's deadline for escalation and cleanup. +// False with no error means the caller may escalate; cancellation or a budget +// too short for the base grace is not a reason to hard-kill. +func (t VFIOTeardown) Wait(ctx context.Context, base, reserve time.Duration, waitForExit func(time.Duration) bool) (bool, error) { + start := time.Now() + limit := base + time.Minute + if deadline, ok := ctx.Deadline(); ok { + limit = min(limit, deadline.Sub(start)-reserve) + } + peak := t.atStart + for { + if err := ctx.Err(); err != nil { + return false, err + } + peak = max(peak, activeVFIOTeardowns.Load()) + grace := min(base+time.Duration(peak-1)*time.Second, limit) + remaining := grace - time.Since(start) + if remaining <= 0 { + if limit < base { + return false, context.DeadlineExceeded + } + return false, nil + } + if waitForExit(min(remaining, 200*time.Millisecond)) { + return true, nil + } + } +} diff --git a/lib/hypervisor/vfio_test.go b/lib/hypervisor/vfio_test.go new file mode 100644 index 000000000..33c923c53 --- /dev/null +++ b/lib/hypervisor/vfio_test.go @@ -0,0 +1,65 @@ +package hypervisor + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/require" +) + +func TestVFIOTeardownWaitBudget(t *testing.T) { + for _, tc := range []struct { + name string + others int + budget, wantWait time.Duration + }{ + {"alone", 0, 30 * time.Second, 5 * time.Second}, + {"26 teardowns, TTL reaper", 25, 30 * time.Second, 20 * time.Second}, + {"61 teardowns, API", 60, time.Minute, 50 * time.Second}, + {"queue allowance cap", 80, 2 * time.Minute, 65 * time.Second}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), tc.budget) + defer cancel() + time.Sleep(5 * time.Second) // guest shutdown before SIGTERM + for range tc.others { + defer BeginVFIOTeardown().Done() + } + teardown := BeginVFIOTeardown() + defer teardown.Done() + start := time.Now() + exited, err := teardown.Wait(ctx, VFIOTermGrace, 5*time.Second, func(d time.Duration) bool { + time.Sleep(d) + return false + }) + require.NoError(t, err) + require.False(t, exited) + require.Equal(t, tc.wantWait, time.Since(start)) + }) + }) + } +} + +func TestVFIOTeardownKeepsLatePeak(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + first := BeginVFIOTeardown() + defer first.Done() + go func() { + time.Sleep(time.Second) + peer := BeginVFIOTeardown() + defer peer.Done() + time.Sleep(time.Second) + }() + start := time.Now() + exited, err := first.Wait(t.Context(), VFIOTermGrace, 0, func(d time.Duration) bool { + time.Sleep(d) + return false + }) + require.NoError(t, err) + require.False(t, exited) + require.Equal(t, VFIOTermGrace+time.Second, time.Since(start)) + }) +} diff --git a/lib/instances/manager.go b/lib/instances/manager.go index 4384cb322..a4c6fb357 100644 --- a/lib/instances/manager.go +++ b/lib/instances/manager.go @@ -8,7 +8,6 @@ import ( "os" "path/filepath" "sync" - "sync/atomic" "time" "github.com/kernel/hypeman/lib/devices" @@ -229,8 +228,6 @@ type manager struct { vgpuReconcileInterval time.Duration vfioTermGrace time.Duration - // vfioTeardowns counts the VMMs with VFIO devices being terminated now. - vfioTeardowns atomic.Int32 // Hypervisor support vmStarters map[hypervisor.Type]hypervisor.VMStarter diff --git a/lib/instances/process_identity.go b/lib/instances/process_identity.go index 08ac860bb..210e7b36e 100644 --- a/lib/instances/process_identity.go +++ b/lib/instances/process_identity.go @@ -27,20 +27,8 @@ const linuxBootIDPath = "/proc/sys/kernel/random/boot_id" // does not unstick it, so the wait is short to keep stop and delete fast. const hypervisorSIGKILLWaitTimeout = 2 * time.Second -const ( - // vfioTeardownQueueAllowance is the extra time a VMM with VFIO devices - // gets to exit on SIGTERM for every other such VMM being terminated at - // the same time. The device is released on the VMM's way out, and the - // host driver is slower at that when many go at once: vGPU guests exited - // about a second after SIGTERM when up to 8 were terminated together, but - // took up to 10 s when 16 or 26 were. That outlasted the fixed grace, so - // they were hard-killed mid-release and their deletes failed about a - // second before the VMMs were gone. - vfioTeardownQueueAllowance = time.Second - // vfioTeardownMaxAllowance caps the allowance for a queue of any length. - vfioTeardownMaxAllowance = time.Minute - vfioTeardownPollInterval = 200 * time.Millisecond -) +// Leave both SIGKILL waits and time for resource cleanup inside the caller's deadline. +const vfioEscalationReserve = 2*hypervisorSIGKILLWaitTimeout + time.Second func (m *manager) vfioTerminationGrace() time.Duration { if m.vfioTermGrace > 0 { @@ -52,10 +40,19 @@ func (m *manager) vfioTerminationGrace() time.Duration { // SIGKILL during guest driver init can wedge a VF until the parent GPU is reset. func (m *manager) terminateThenKill(ctx context.Context, inst *Instance, pid int) error { if hasVFIODevices(&inst.StoredMetadata) { - m.vfioTeardowns.Add(1) - defer m.vfioTeardowns.Add(-1) - if syscall.Kill(pid, syscall.SIGTERM) == nil && m.waitForVFIOTeardown(pid, m.vfioTerminationGrace()) { - return nil + grace := m.vfioTerminationGrace() + if err := ctx.Err(); err != nil { + return err + } + teardown := hypervisor.BeginVFIOTeardown() + defer teardown.Done() + if syscall.Kill(pid, syscall.SIGTERM) == nil { + exited, err := teardown.Wait(ctx, grace, vfioEscalationReserve, func(d time.Duration) bool { + return WaitForProcessExit(pid, d) + }) + if exited || err != nil { + return err + } } logger.FromContext(ctx).WarnContext(ctx, "hypervisor with VFIO devices did not exit on SIGTERM; hard-killing, device may wedge if the guest driver was initializing", "instance_id", inst.Id, "device_path", inst.GPUDevicePath) @@ -63,26 +60,6 @@ func (m *manager) terminateThenKill(ctx context.Context, inst *Instance, pid int return killProcessAndWait(pid) } -// waitForVFIOTeardown waits for pid to exit for base plus the queue allowance. -// The allowance follows the largest number of VFIO teardowns seen in flight -// during the wait: a VMM that started exiting alone is still slowed down by -// the ones that join it. -func (m *manager) waitForVFIOTeardown(pid int, base time.Duration) bool { - start := time.Now() - peak := int32(1) - for { - peak = max(peak, m.vfioTeardowns.Load()) - allowance := min(time.Duration(peak-1)*vfioTeardownQueueAllowance, vfioTeardownMaxAllowance) - remaining := base + allowance - time.Since(start) - if remaining <= 0 { - return false - } - if WaitForProcessExit(pid, min(remaining, vfioTeardownPollInterval)) { - return true - } - } -} - // killProcessAndWait SIGKILLs pid and waits for it to exit. A process that // survives the first wait gets its process group killed too (the hypervisor // may have spawned children in its own group) and a short grace period. An diff --git a/lib/instances/process_identity_linux_test.go b/lib/instances/process_identity_linux_test.go index 8ce958ff1..370018e0c 100644 --- a/lib/instances/process_identity_linux_test.go +++ b/lib/instances/process_identity_linux_test.go @@ -721,78 +721,80 @@ func TestKillHypervisorEscalatesToSIGKILLWhenSIGTERMIgnored(t *testing.T) { assert.ErrorIs(t, syscall.Kill(pid, 0), syscall.ESRCH, "SIGTERM-ignoring hypervisor must still be hard-killed") } -// A VMM with VFIO devices exits only after the host driver has released its -// device, and the driver is slower at that when many guests go down together. -// The wait has to grow with their number, or a mass delete hard-kills and -// then gives up on VMMs that were about to exit. +func vfioTestInstance(t *testing.T, identity HypervisorProcessIdentity) *Instance { + t.Helper() + return &Instance{State: StateRunning, StoredMetadata: StoredMetadata{ + GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", + HypervisorProcessIdentity: identity, + SocketPath: filepath.Join(t.TempDir(), "vmm.sock"), + }} +} + func TestKillHypervisorWaitsLongerWhileOtherVFIOTeardownsAreInFlight(t *testing.T) { for _, tc := range []struct { - name string - othersInQueue int32 - exitsCleanly bool + name string + others int + budget time.Duration + released bool }{ - {name: "alone", othersInQueue: 0, exitsCleanly: false}, - {name: "behind two others", othersInQueue: 2, exitsCleanly: true}, + {name: "behind two others", others: 2, released: true}, + {name: "queued but deadline limits grace", others: 2, budget: vfioEscalationReserve + 300*time.Millisecond}, + {name: "alone"}, } { t.Run(tc.name, func(t *testing.T) { - markerPath := filepath.Join(t.TempDir(), "released") - // Stands in for a VMM whose device release takes 0.6 s after SIGTERM. - pid, identity := startTrapProcess(t, "sleep 0.6; touch "+markerPath+"; exit 0") - + for range tc.others { + t.Cleanup(hypervisor.BeginVFIOTeardown().Done) + } + released := filepath.Join(t.TempDir(), "released") + pid, id := startTrapProcess(t, fmt.Sprintf("sleep 0.6; touch %q; exit 0", released)) m := &manager{vfioTermGrace: 100 * time.Millisecond} - m.vfioTeardowns.Store(tc.othersInQueue) - require.NoError(t, m.killHypervisor(context.Background(), &Instance{ - State: StateRunning, - StoredMetadata: StoredMetadata{ - Id: "kill-test", - GPUProfile: "NVIDIA L40S-1Q", - GPUFramework: devices.VGPUFrameworkVendorVFIO, - GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", - HypervisorProcessIdentity: identity, - SocketPath: filepath.Join(t.TempDir(), "missing.sock"), - }, - })) - + ctx := t.Context() + if tc.budget > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, tc.budget) + defer cancel() + } + require.NoError(t, m.killHypervisor(ctx, vfioTestInstance(t, id))) + assert.NoError(t, ctx.Err()) assert.ErrorIs(t, syscall.Kill(pid, 0), syscall.ESRCH) - assert.Equal(t, tc.othersInQueue, m.vfioTeardowns.Load(), "the teardown must leave the queue when it returns") - if tc.exitsCleanly { - assert.FileExists(t, markerPath, "a queued VMM must be allowed to finish releasing its device") + if tc.released { + assert.FileExists(t, released) } else { - assert.NoFileExists(t, markerPath, "without a queue the short grace still applies") + assert.NoFileExists(t, released) } }) } } -// The queue is made of the teardowns themselves: one that is in flight has to -// count for the next one that starts. func TestKillHypervisorCountsVFIOTeardownsInFlight(t *testing.T) { - m := &manager{vfioTermGrace: 250 * time.Millisecond} - kill := func(identity HypervisorProcessIdentity) error { - return m.killHypervisor(context.Background(), &Instance{ - State: StateRunning, - StoredMetadata: StoredMetadata{ - Id: "kill-test", - GPUProfile: "NVIDIA L40S-1Q", - GPUFramework: devices.VGPUFrameworkVendorVFIO, - GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", - HypervisorProcessIdentity: identity, - SocketPath: filepath.Join(t.TempDir(), "missing.sock"), - }, - }) - } - markerPath := filepath.Join(t.TempDir(), "released") - _, first := startTrapProcess(t, "sleep 0.6; exit 0") - _, second := startTrapProcess(t, "sleep 0.6; touch "+markerPath+"; exit 0") - - firstDone := make(chan error, 1) - go func() { firstDone <- kill(first) }() - require.Eventually(t, func() bool { return m.vfioTeardowns.Load() == 1 }, 5*time.Second, time.Millisecond) - - require.NoError(t, kill(second)) - assert.FileExists(t, markerPath, "a teardown in flight must lengthen the wait of one that starts meanwhile") - require.NoError(t, <-firstDone) - assert.Zero(t, m.vfioTeardowns.Load()) + dir := t.TempDir() + started := filepath.Join(dir, "started") + firstExit, secondExit := filepath.Join(dir, "first"), filepath.Join(dir, "second") + _, first := startTrapProcess(t, fmt.Sprintf("touch %q; sleep 0.9; touch %q; exit 0", started, firstExit)) + _, second := startTrapProcess(t, fmt.Sprintf("sleep 0.7; touch %q; exit 0", secondExit)) + firstInst := vfioTestInstance(t, first) + m := &manager{vfioTermGrace: 400 * time.Millisecond} + + done := make(chan error, 1) + go func() { done <- m.killHypervisor(t.Context(), firstInst) }() + require.Eventually(t, func() bool { _, err := os.Stat(started); return err == nil }, 5*time.Second, time.Millisecond) + require.NoError(t, m.killHypervisor(t.Context(), vfioTestInstance(t, second))) + require.NoError(t, <-done) + assert.FileExists(t, firstExit, "the first VMM must gain grace when the second joins") + assert.FileExists(t, secondExit, "the second VMM must count the first") +} + +func TestKillHypervisorRetainsVFIOProcessWhenDeadlineCannotFitBaseGrace(t *testing.T) { + pid, id := startTrapProcess(t, "") + inst := vfioTestInstance(t, id) + require.NoError(t, os.WriteFile(inst.SocketPath, nil, 0600)) + ctx, cancel := context.WithTimeout(t.Context(), vfioEscalationReserve+100*time.Millisecond) + defer cancel() + + m := &manager{} + require.ErrorIs(t, m.killHypervisor(ctx, inst), context.DeadlineExceeded) + assert.NoError(t, syscall.Kill(pid, 0), "a short caller deadline must not force an early SIGKILL") + assert.FileExists(t, inst.SocketPath) } func TestKillHypervisorHardKillsNonVGPUHypervisor(t *testing.T) { From 24289f1167bd5da1d32341d505d2dfbace7308d8 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:04:39 +0000 Subject: [PATCH 3/5] Finish interrupted VFIO cleanup without cutting short a clean exit --- lib/hypervisor/qemu/process.go | 2 +- lib/hypervisor/vfio.go | 15 ++- lib/hypervisor/vfio_test.go | 32 ++++- lib/instances/fork.go | 5 +- lib/instances/process_identity.go | 5 +- lib/instances/process_identity_linux_test.go | 4 +- lib/instances/query.go | 4 + lib/instances/stop.go | 29 ++++- lib/instances/storage.go | 3 + lib/instances/vfio_lifecycle_linux_test.go | 119 +++++++++++++++++++ 10 files changed, 198 insertions(+), 20 deletions(-) create mode 100644 lib/instances/vfio_lifecycle_linux_test.go diff --git a/lib/hypervisor/qemu/process.go b/lib/hypervisor/qemu/process.go index 38f980ea7..4202036cf 100644 --- a/lib/hypervisor/qemu/process.go +++ b/lib/hypervisor/qemu/process.go @@ -309,7 +309,7 @@ func cleanupFailedStart(ctx context.Context, proc *startedProcess, termGrace tim defer teardown.Done() if syscall.Kill(proc.pid, syscall.SIGTERM) == nil { start := time.Now() - if _, err := teardown.Wait(ctx, termGrace, time.Second, proc.waitFor); err != nil { + if _, err := teardown.Wait(ctx, termGrace, 0, proc.waitFor); err != nil { // Rollback must reap the child even after cancellation, but // don't cut its base grace short to do so. proc.waitFor(termGrace - time.Since(start)) diff --git a/lib/hypervisor/vfio.go b/lib/hypervisor/vfio.go index 09771ba1f..a8ab8a38a 100644 --- a/lib/hypervisor/vfio.go +++ b/lib/hypervisor/vfio.go @@ -26,14 +26,21 @@ func (VFIOTeardown) Done() { activeVFIOTeardowns.Add(-1) } // Wait allows one extra second per overlapping teardown, up to a minute: // 16 simultaneous vGPU deletes can take 10s in the driver after SIGTERM. -// It leaves reserve before the caller's deadline for escalation and cleanup. +// It leaves one second for cleanup, and reserves killWait for escalation only +// when the base grace and both reserves fit before the caller's deadline. // False with no error means the caller may escalate; cancellation or a budget // too short for the base grace is not a reason to hard-kill. -func (t VFIOTeardown) Wait(ctx context.Context, base, reserve time.Duration, waitForExit func(time.Duration) bool) (bool, error) { +func (t VFIOTeardown) Wait(ctx context.Context, base, killWait time.Duration, waitForExit func(time.Duration) bool) (bool, error) { start := time.Now() limit := base + time.Minute + canEscalate := true if deadline, ok := ctx.Deadline(); ok { - limit = min(limit, deadline.Sub(start)-reserve) + budget := deadline.Sub(start) - time.Second // cleanup after exit + canEscalate = budget >= base+killWait + if canEscalate { + budget -= killWait + } + limit = min(limit, budget) } peak := t.atStart for { @@ -44,7 +51,7 @@ func (t VFIOTeardown) Wait(ctx context.Context, base, reserve time.Duration, wai grace := min(base+time.Duration(peak-1)*time.Second, limit) remaining := grace - time.Since(start) if remaining <= 0 { - if limit < base { + if !canEscalate { return false, context.DeadlineExceeded } return false, nil diff --git a/lib/hypervisor/vfio_test.go b/lib/hypervisor/vfio_test.go index 33c923c53..c202e1d3d 100644 --- a/lib/hypervisor/vfio_test.go +++ b/lib/hypervisor/vfio_test.go @@ -14,11 +14,14 @@ func TestVFIOTeardownWaitBudget(t *testing.T) { name string others int budget, wantWait time.Duration + wantErr error }{ - {"alone", 0, 30 * time.Second, 5 * time.Second}, - {"26 teardowns, TTL reaper", 25, 30 * time.Second, 20 * time.Second}, - {"61 teardowns, API", 60, time.Minute, 50 * time.Second}, - {"queue allowance cap", 80, 2 * time.Minute, 65 * time.Second}, + {"alone", 0, 30 * time.Second, 5 * time.Second, nil}, + {"just enough for escalation", 0, 15 * time.Second, 5 * time.Second, nil}, + {"base fits but escalation does not", 0, 13 * time.Second, 5 * time.Second, context.DeadlineExceeded}, + {"26 teardowns, TTL reaper", 25, 30 * time.Second, 20 * time.Second, nil}, + {"61 teardowns, API", 60, time.Minute, 50 * time.Second, nil}, + {"queue allowance cap", 80, 2 * time.Minute, 65 * time.Second, nil}, } { t.Run(tc.name, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { @@ -31,11 +34,11 @@ func TestVFIOTeardownWaitBudget(t *testing.T) { teardown := BeginVFIOTeardown() defer teardown.Done() start := time.Now() - exited, err := teardown.Wait(ctx, VFIOTermGrace, 5*time.Second, func(d time.Duration) bool { + exited, err := teardown.Wait(ctx, VFIOTermGrace, 4*time.Second, func(d time.Duration) bool { time.Sleep(d) return false }) - require.NoError(t, err) + require.ErrorIs(t, err, tc.wantErr) require.False(t, exited) require.Equal(t, tc.wantWait, time.Since(start)) }) @@ -43,6 +46,23 @@ func TestVFIOTeardownWaitBudget(t *testing.T) { } } +func TestVFIOTeardownShortBudgetAllowsCleanExit(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + teardown := BeginVFIOTeardown() + defer teardown.Done() + start := time.Now() + exited, err := teardown.Wait(ctx, VFIOTermGrace, 4*time.Second, func(d time.Duration) bool { + time.Sleep(d) + return time.Since(start) >= 4*time.Second + }) + require.NoError(t, err, "waited %s for an exit at 4s", time.Since(start)) + require.True(t, exited) + require.Equal(t, 4*time.Second, time.Since(start)) + }) +} + func TestVFIOTeardownKeepsLatePeak(t *testing.T) { synctest.Test(t, func(t *testing.T) { first := BeginVFIOTeardown() diff --git a/lib/instances/fork.go b/lib/instances/fork.go index 2b2231156..1fb79a1f8 100644 --- a/lib/instances/fork.go +++ b/lib/instances/fork.go @@ -566,7 +566,10 @@ func (m *manager) cleanupForkInstanceOnError(ctx context.Context, forkID string) lock.Lock() defer lock.Unlock() - err := m.deleteInstance(ctx, forkID) + // A readiness timeout can leave a running fork that was never returned to the caller. + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute) + defer cancel() + err := m.deleteInstance(cleanupCtx, forkID) if err == nil || errors.Is(err, ErrNotFound) { m.instanceLocks.Delete(forkID) return nil diff --git a/lib/instances/process_identity.go b/lib/instances/process_identity.go index 210e7b36e..3226cb5f9 100644 --- a/lib/instances/process_identity.go +++ b/lib/instances/process_identity.go @@ -27,8 +27,7 @@ const linuxBootIDPath = "/proc/sys/kernel/random/boot_id" // does not unstick it, so the wait is short to keep stop and delete fast. const hypervisorSIGKILLWaitTimeout = 2 * time.Second -// Leave both SIGKILL waits and time for resource cleanup inside the caller's deadline. -const vfioEscalationReserve = 2*hypervisorSIGKILLWaitTimeout + time.Second +const vfioKillWait = 2 * hypervisorSIGKILLWaitTimeout func (m *manager) vfioTerminationGrace() time.Duration { if m.vfioTermGrace > 0 { @@ -47,7 +46,7 @@ func (m *manager) terminateThenKill(ctx context.Context, inst *Instance, pid int teardown := hypervisor.BeginVFIOTeardown() defer teardown.Done() if syscall.Kill(pid, syscall.SIGTERM) == nil { - exited, err := teardown.Wait(ctx, grace, vfioEscalationReserve, func(d time.Duration) bool { + exited, err := teardown.Wait(ctx, grace, vfioKillWait, func(d time.Duration) bool { return WaitForProcessExit(pid, d) }) if exited || err != nil { diff --git a/lib/instances/process_identity_linux_test.go b/lib/instances/process_identity_linux_test.go index 370018e0c..f8714bd21 100644 --- a/lib/instances/process_identity_linux_test.go +++ b/lib/instances/process_identity_linux_test.go @@ -738,7 +738,7 @@ func TestKillHypervisorWaitsLongerWhileOtherVFIOTeardownsAreInFlight(t *testing. released bool }{ {name: "behind two others", others: 2, released: true}, - {name: "queued but deadline limits grace", others: 2, budget: vfioEscalationReserve + 300*time.Millisecond}, + {name: "queued but deadline limits grace", others: 2, budget: vfioKillWait + time.Second + 300*time.Millisecond}, {name: "alone"}, } { t.Run(tc.name, func(t *testing.T) { @@ -788,7 +788,7 @@ func TestKillHypervisorRetainsVFIOProcessWhenDeadlineCannotFitBaseGrace(t *testi pid, id := startTrapProcess(t, "") inst := vfioTestInstance(t, id) require.NoError(t, os.WriteFile(inst.SocketPath, nil, 0600)) - ctx, cancel := context.WithTimeout(t.Context(), vfioEscalationReserve+100*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), time.Second+100*time.Millisecond) defer cancel() m := &manager{} diff --git a/lib/instances/query.go b/lib/instances/query.go index f1b177c9b..822e9cc68 100644 --- a/lib/instances/query.go +++ b/lib/instances/query.go @@ -554,6 +554,10 @@ func (m *manager) toInstanceWithStateDerivation(ctx context.Context, meta *metad } else { result = m.deriveStateWithoutHydration(ctx, &meta.StoredMetadata) } + // Losing the control socket during stop does not mean the VMM or its resources are gone. + if meta.StopCleanupPending && (result.State == StateStopped || result.State == StateStandby) { + result.State = StateShutdown + } inst := Instance{ StoredMetadata: meta.StoredMetadata, diff --git a/lib/instances/stop.go b/lib/instances/stop.go index 986b0a201..1772d4467 100644 --- a/lib/instances/stop.go +++ b/lib/instances/stop.go @@ -120,6 +120,21 @@ func (m *manager) tryGracefulGuestShutdown(ctx context.Context, inst *Instance, return false } +// beginVFIOStop saves the confirmed owner while its socket is still available. +// A retry cannot recover a legacy PID from a listener already closed by SIGTERM. +func (m *manager) beginVFIOStop(meta *metadata, inst *Instance) error { + pid, err := resolveLiveHypervisorPID(meta.HypervisorProcessIdentity, meta.SocketPath) + if err != nil { + return err + } + if pid > 0 { + inst.HypervisorProcessIdentity.Set(pid) + meta.HypervisorProcessIdentity = inst.HypervisorProcessIdentity + } + meta.StopCleanupPending = true + return m.saveMetadata(meta) +} + // stopInstance stops an active instance. // Flow: send Shutdown RPC -> wait for VM to power off -> // fall back to hypervisor shutdown -> final SIGKILL if still alive. @@ -153,12 +168,20 @@ func (m *manager) stopInstance( ctx = enrichInstancesTrace(ctx, attribute.String("hypervisor", string(stored.HypervisorType))) log.DebugContext(ctx, "loaded instance", "instance_id", id, "state", inst.State) - // 2. Validate state transition (must be active to stop) - if inst.State != StateRunning && inst.State != StateInitializing { + // A pending stop still has to confirm VMM exit and finish cleanup even + // when the missing control socket already makes the guest look stopped. + active := inst.State == StateRunning || inst.State == StateInitializing + if !active && !meta.StopCleanupPending { log.ErrorContext(ctx, "invalid state for stop", "instance_id", id, "state", inst.State) return nil, fmt.Errorf("%w: cannot stop from state %s, must be Running or Initializing", ErrInvalidState, inst.State) } + if hasVFIODevices(stored) && !meta.StopCleanupPending { + if err := m.beginVFIOStop(meta, &inst); err != nil { + return nil, fmt.Errorf("record pending VFIO stop: %w", err) + } + } + // 3. Get network allocation BEFORE killing VMM (while we can still query it) var networkAlloc *network.Allocation var networkAllocErr error @@ -173,7 +196,7 @@ func (m *manager) stopInstance( // 4. Graceful shutdown: send signal to guest init via Shutdown RPC, // then wait for VM to power off cleanly. Fall back to hypervisor shutdown on timeout. gracefulShutdown := false - if !req.Force { + if active && !req.Force { stopTimeout := resolveStopTimeout(stored) if inst.MacOS != nil { // macOS power-off can outlast the ordinary short stop default. diff --git a/lib/instances/storage.go b/lib/instances/storage.go index 2e7440e3a..01baa2c56 100644 --- a/lib/instances/storage.go +++ b/lib/instances/storage.go @@ -42,6 +42,9 @@ const ( // metadata wraps StoredMetadata for JSON serialization type metadata struct { StoredMetadata + // A VFIO stop may outlive its caller. Keep it distinct from an ordinary + // stopped instance until the stop has released resources and saved StoppedAt. + StopCleanupPending bool `json:"stop_cleanup_pending,omitempty"` AutoStandbyRuntime *autostandby.Runtime `json:"auto_standby_runtime,omitempty"` HealthCheckRuntime *healthcheck.Runtime `json:"health_check_runtime,omitempty"` } diff --git a/lib/instances/vfio_lifecycle_linux_test.go b/lib/instances/vfio_lifecycle_linux_test.go new file mode 100644 index 000000000..92d7aeaef --- /dev/null +++ b/lib/instances/vfio_lifecycle_linux_test.go @@ -0,0 +1,119 @@ +package instances + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/kernel/hypeman/lib/devices" + "github.com/kernel/hypeman/lib/network" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCanceledForkRollbackRemovesRunningVFIOGuest(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + pid, identity := startTrapProcess(t, "exit 0") + meta.HypervisorProcessIdentity = identity + meta.GPUDevicePath = "/sys/bus/pci/devices/0000:82:00.4" + meta.SkipGuestAgent = true + require.NoError(t, m.saveMetadata(meta)) + + released := false + m.destroyVGPU = func(ctx context.Context, _ devices.VGPUAssignment) error { + assert.NoError(t, ctx.Err()) + _, bounded := ctx.Deadline() + assert.True(t, bounded, "rollback must have its own deadline") + assert.False(t, ProcessExists(pid), "release only after the VMM exits") + released = true + return nil + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err = m.cleanupForkInstanceOnError(ctx, id) + assert.NoError(t, err) + assert.False(t, ProcessExists(pid)) + assert.True(t, released) + assert.NoDirExists(t, meta.DataDir) +} + +type stopRetryNetwork struct { + network.Manager + released []string +} + +func (n *stopRetryNetwork) GetAllocation(_ context.Context, id string) (*network.Allocation, error) { + return &network.Allocation{InstanceID: id}, nil +} + +func (n *stopRetryNetwork) ReleaseAllocation(_ context.Context, a *network.Allocation) error { + n.released = append(n.released, a.InstanceID) + return nil +} + +func TestStopRetryFinishesAfterVFIOGuestExits(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + dir := t.TempDir() + terminating, release := filepath.Join(dir, "terminating"), filepath.Join(dir, "release") + pid, identity := startTrapProcess(t, fmt.Sprintf("rm %q; touch %q; while [ ! -f %q ]; do sleep 0.01; done; exit 0", + meta.SocketPath, terminating, release)) + meta.HypervisorProcessIdentity = identity + meta.NetworkEnabled = true + meta.GPUDevicePath = "/sys/bus/pci/devices/0000:82:00.4" + require.NoError(t, m.saveMetadata(meta)) + + net := &stopRetryNetwork{} + m.networkManager = net + var resets []string + m.destroyVGPU = func(_ context.Context, a devices.VGPUAssignment) error { + assert.False(t, ProcessExists(pid)) + resets = append(resets, a.DevicePath) + return nil + } + + ctx, cancel := context.WithCancel(t.Context()) + var stopErr error + done := make(chan struct{}) + go func() { + defer close(done) + _, stopErr = m.StopInstance(ctx, id, StopInstanceRequest{Force: true}) + }() + defer func() { cancel(); <-done }() + require.Eventually(t, func() bool { _, err := os.Stat(terminating); return err == nil }, 5*time.Second, time.Millisecond) + cancel() + <-done + require.ErrorIs(t, stopErr, context.Canceled) + + // A fresh manager sees the unfinished stop even after the socket has gone. + restarted := &manager{paths: m.paths, networkManager: net, destroyVGPU: m.destroyVGPU, lifecycleEvents: newLifecycleSubscribers()} + pending, err := restarted.currentInstanceWithoutHydration(t.Context(), id) + require.NoError(t, err) + require.Equal(t, StateShutdown, pending.State) + require.ErrorIs(t, restarted.DeleteInstance(ctx, id), context.Canceled) + require.True(t, ProcessExists(pid)) + require.Empty(t, net.released) + require.Empty(t, resets) + + require.NoError(t, os.WriteFile(release, nil, 0600)) + require.Eventually(t, func() bool { return !ProcessExists(pid) }, 5*time.Second, time.Millisecond) + inst, err := restarted.StopInstance(t.Context(), id, StopInstanceRequest{}) + require.NoError(t, err) + assert.Equal(t, StateStopped, inst.State) + stored, err := m.loadMetadata(id) + require.NoError(t, err) + assert.NotNil(t, stored.StoppedAt) + assert.Nil(t, stored.HypervisorPID) + assert.Empty(t, stored.GPUDevicePath) + + _, err = restarted.StopInstance(t.Context(), id, StopInstanceRequest{}) + require.NoError(t, err) + assert.Equal(t, []string{id}, net.released) + assert.Equal(t, []string{meta.GPUDevicePath}, resets) +} From 700c9b0a62db815c373cd35a88dfcb8968be6709 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:04:43 +0000 Subject: [PATCH 4/5] Preserve unfinished VFIO teardown across lifecycle retries Confirm the VMM owner before direct deletes as well as stops. Keep cleanup pending if vGPU release fails or metadata is updated, and reject start and in-place restore until the stop is complete. Resume interrupted health-check restarts without charging the same attempt twice. --- lib/devices/GPU.md | 5 + lib/instances/delete.go | 5 +- lib/instances/lifecycle_noop_test.go | 24 +++++ lib/instances/metadata_clone.go | 10 +- lib/instances/process_identity_linux_test.go | 18 ++-- lib/instances/restart_policy.go | 106 +++++++++++++------ lib/instances/restart_policy_test.go | 54 ++++++++++ lib/instances/snapshot.go | 3 + lib/instances/snapshot_test.go | 18 ++++ lib/instances/stop.go | 30 +++--- lib/instances/storage.go | 4 +- lib/instances/vfio_lifecycle_linux_test.go | 43 ++++++++ lib/restart-policy/README.md | 2 +- 13 files changed, 261 insertions(+), 61 deletions(-) diff --git a/lib/devices/GPU.md b/lib/devices/GPU.md index 33e54354b..1bc34d2db 100644 --- a/lib/devices/GPU.md +++ b/lib/devices/GPU.md @@ -106,6 +106,11 @@ itself down and wait for it. Delete normally caps that wait at 2s, but guests with a vGPU or passthrough device get 5s so the guest can unload its GPU driver before the hypervisor is signalled. +If a stop or delete is interrupted, retry the same operation. The control socket +can disappear before the VMM releases its devices. Hypeman keeps the process +identity and confirms exit on retry; it rejects starts and snapshot restores +while cleanup is pending. A failed vGPU reset also leaves the stop pending. + Hypeman reconciles metadata claims once at startup and every minute afterward, skipping hosts without GPUs. A claim whose VMM is confirmed dead is reset before the claim is removed. An ambiguous hypervisor ownership check preserves the claim, logs a warning, and increments `hypeman_instances_vgpu_liveness_uncertain_total`; the create and start cleanup paths preserve and count the same way. mdev hosts also sweep orphaned device-level assignments. Vendor VFIO hosts reset unclaimed dirty VFs on every reconcile pass, which covers a restart between a claim writing the type and saving the claim, or a failed claim whose reset also failed, but also clears a type written to `current_vgpu_type` by hand unless the VF has an open VFIO handle. A reset that is refused is retried on the next pass and increments `hypeman_instances_vgpu_reconcile_failures_total{stage="reset_unclaimed_vfs"}`. The allocator also repairs an unclaimed dirty VF when it next selects it; repair checks for open VFIO handles before resetting `current_vgpu_type`. The allocator prefers VFs that are already clean, and a dirty VF that refuses its reset is skipped in favor of another candidate. Vendor VFIO placement and `/resources` both read the driver's creatable placements through NVML (`nvmlDeviceGetVgpuTypeCreatablePlacements`, the query behind `nvidia-smi vgpu -c -v`), which list the free placement IDs of every profile each GPU can still create. Hypeman loads `libnvidia-ml.so.1` at runtime on first use and keeps it initialized, which holds the GPU device nodes open (stop hypeman before the SR-IOV cycle below); a query for every profile on two L40S GPUs takes about 20 ms. A free VF can take any profile its GPU lists there, and a claim only writes a type the driver has just reported a free placement for; if that configure still fails, the VF is reset and the claim fails without trying another GPU. The per-VF `creatable_vgpu_types` lists are not used for this because in mixed-size (heterogeneous) mode they under-report: the driver drops a profile from them once its GPU holds as many vGPUs as that profile's equal-size instance limit (12 for L40S-4Q), even while a placement for it remains. If NVML cannot be loaded or initialized or takes longer than 5 s, placement and `/resources` fall back to those lists for every GPU; if it fails for one GPU, or reports a GPU not in mixed-size mode, only that GPU falls back. Profiles the lists hide are refused on a GPU that has fallen back until NVML recovers. Queries run one at a time and wait for each other within the same 5 s, so callers queued behind a hung query never enter the driver. A query that times out is abandoned rather than waited for, since a call stuck in the driver cannot be interrupted; until it returns, queries skip NVML and use the lists directly, so a hung driver costs one timeout rather than one per claim. Each fallback increments `hypeman_resources_gpu_nvml_fallbacks_total` with `reason` `error`, `equal_size` (every GPU NVML failed for is in equal-size mode, as after a driver reload or GPU reset), `timeout` or `stuck`. A warning is logged when a fallback starts or its error changes, and an info line once NVML answers for every GPU again, rather than on every query. Admission only checks free VFs, so it does not query NVML. `/resources` does not query it either: it counts profiles from cached placements, loaded at startup, refreshed in the background after every vendor VFIO configure or reset, and refreshed again on every reconcile pass. Free and quarantined VFs are read fresh on every request, so a claim or release changes the counts at once; the placements it frees or takes on a mixed-size GPU show once the background refresh lands, about 20 ms later. diff --git a/lib/instances/delete.go b/lib/instances/delete.go index 46b7baaba..e3630f5bf 100644 --- a/lib/instances/delete.go +++ b/lib/instances/delete.go @@ -103,6 +103,9 @@ func (m *manager) deleteInstanceWithOptions( return fmt.Errorf("reload metadata after blocking restart policy: %w", err) } stored = &meta.StoredMetadata + if err := m.beginVFIOStop(meta, &inst); err != nil { + return fmt.Errorf("record pending VFIO stop: %w", err) + } // 4. If active, try graceful guest shutdown before force kill. gracefulShutdown := false @@ -125,7 +128,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 && (meta.StopCleanupPending || inst.State.RequiresVMM() || inst.State == StateUnknown) { log.DebugContext(ctx, "stopping hypervisor", "instance_id", id, "state", inst.State) killCtx, killSpanEnd := m.startLifecycleStep(ctx, "force_kill_hypervisor", attribute.String("instance_id", id), diff --git a/lib/instances/lifecycle_noop_test.go b/lib/instances/lifecycle_noop_test.go index b374cedbb..8224e17c4 100644 --- a/lib/instances/lifecycle_noop_test.go +++ b/lib/instances/lifecycle_noop_test.go @@ -331,6 +331,30 @@ func TestStopInstanceRetiresPooledGuestConnection(t *testing.T) { }, time.Second, time.Millisecond, "stop must close the retired connection") } +func TestStopRetriesFailedVGPURelease(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.GPUDevicePath = "/sys/bus/pci/devices/0000:82:00.4" + require.NoError(t, m.saveMetadata(meta)) + releaseErr := errors.New("reset failed") + m.destroyVGPU = func(context.Context, devices.VGPUAssignment) error { return releaseErr } + _, err = m.StopInstance(t.Context(), id, StopInstanceRequest{Force: true}) + require.ErrorIs(t, err, releaseErr) + retained, err := m.loadMetadata(id) + require.NoError(t, err) + require.True(t, retained.StopCleanupPending) + require.Nil(t, retained.StoppedAt) + require.Equal(t, meta.GPUDevicePath, retained.GPUDevicePath) + + m.destroyVGPU = func(context.Context, devices.VGPUAssignment) error { return nil } + inst, err := m.StopInstance(t.Context(), id, StopInstanceRequest{}) + require.NoError(t, err) + require.Equal(t, StateStopped, inst.State) + require.Empty(t, inst.GPUDevicePath) + require.NotNil(t, inst.StoppedAt) +} + func TestStopStoppedInstanceLeavesVGPUForReconcile(t *testing.T) { m, id := newLifecycleNoopManagerWithInstance(t, StateStopped, time.Now().UTC()) meta, err := m.loadMetadata(id) diff --git a/lib/instances/metadata_clone.go b/lib/instances/metadata_clone.go index 70742edc4..a7552dc32 100644 --- a/lib/instances/metadata_clone.go +++ b/lib/instances/metadata_clone.go @@ -9,9 +9,9 @@ func deepCopyMetadata(src *metadata) *metadata { return nil } - return &metadata{ - StoredMetadata: cloneStoredMetadata(src.StoredMetadata), - AutoStandbyRuntime: cloneAutoStandbyRuntime(src.AutoStandbyRuntime), - HealthCheckRuntime: healthcheck.CloneRuntime(src.HealthCheckRuntime), - } + dst := *src + dst.StoredMetadata = cloneStoredMetadata(src.StoredMetadata) + dst.AutoStandbyRuntime = cloneAutoStandbyRuntime(src.AutoStandbyRuntime) + dst.HealthCheckRuntime = healthcheck.CloneRuntime(src.HealthCheckRuntime) + return &dst } diff --git a/lib/instances/process_identity_linux_test.go b/lib/instances/process_identity_linux_test.go index f8714bd21..1ba2c6169 100644 --- a/lib/instances/process_identity_linux_test.go +++ b/lib/instances/process_identity_linux_test.go @@ -260,8 +260,8 @@ func TestGracefulShutdownWaitsForSocketOwnerInsteadOfExitedStoredPID(t *testing. assert.True(t, ProcessExists(owner.Process.Pid)) } -func TestGracefulShutdownFallbackKillsCapturedPIDAfterListenerCloses(t *testing.T) { - socketPath := filepath.Join(t.TempDir(), "test.sock") +func startClosingSocketOwner(t *testing.T, socketPath string) (int, func() error) { + t.Helper() owner := exec.Command(os.Args[0], "-test.run=^TestSocketListenerHelper$") owner.Env = append(os.Environ(), "HYPERVISOR_SOCKET_HELPER=1", @@ -282,24 +282,30 @@ func TestGracefulShutdownFallbackKillsCapturedPIDAfterListenerCloses(t *testing. _, err = output.ReadString('\n') require.NoError(t, err) - m := &manager{shutdownGuestFn: func(context.Context, hypervisor.VsockDialer, int32) error { + return owner.Process.Pid, func() error { if _, err := stdin.Write([]byte{1}); err != nil { return err } _, err := output.ReadString('\n') return err - }} + } +} + +func TestGracefulShutdownFallbackKillsCapturedPIDAfterListenerCloses(t *testing.T) { + socketPath := filepath.Join(t.TempDir(), "test.sock") + pid, closeListener := startClosingSocketOwner(t, socketPath) + m := &manager{shutdownGuestFn: func(context.Context, hypervisor.VsockDialer, int32) error { return closeListener() }} inst := &Instance{StoredMetadata: StoredMetadata{ Id: "graceful-listener-close", HypervisorType: hypervisor.TypeCloudHypervisor, - HypervisorProcessIdentity: HypervisorProcessIdentity{HypervisorPID: &owner.Process.Pid}, + HypervisorProcessIdentity: HypervisorProcessIdentity{HypervisorPID: &pid}, SocketPath: socketPath, VsockSocket: filepath.Join(t.TempDir(), "missing-vsock.sock"), }} assert.False(t, m.tryGracefulGuestShutdown(context.Background(), inst, 0)) require.NoError(t, m.killHypervisor(context.Background(), inst)) - assert.False(t, ProcessExists(owner.Process.Pid)) + assert.False(t, ProcessExists(pid)) } func TestShutdownHypervisorSparesReusedPIDWhenNoProcessOwnsSocket(t *testing.T) { diff --git a/lib/instances/restart_policy.go b/lib/instances/restart_policy.go index c65496e1f..6509921bf 100644 --- a/lib/instances/restart_policy.go +++ b/lib/instances/restart_policy.go @@ -69,6 +69,9 @@ func (m *manager) clearRestartStatusLocked(ctx context.Context, id string) error logger.FromContext(ctx).WarnContext(ctx, "failed to clear restart policy status", "instance_id", id, "error", err) return err } + if meta.StopCleanupPending { + return fmt.Errorf("%w: cannot start while stop cleanup is pending", ErrInvalidState) + } if meta.RestartStatus.IsZero() { return nil } @@ -89,10 +92,6 @@ func (m *manager) updateRestartStatusLocked(id string, status restartpolicy.Stat return m.saveMetadata(meta) } -func (m *manager) setRestartStatus(ctx context.Context, id string, status restartpolicy.Status) (bool, error) { - return m.setRestartStatusIf(ctx, id, status, nil) -} - func (m *manager) setRestartStatusIfStopped(ctx context.Context, id string, status restartpolicy.Status) (bool, error) { return m.setRestartStatusIf(ctx, id, status, func(meta *metadata) bool { return m.toInstanceWithoutHydration(ctx, meta).State == StateStopped @@ -139,31 +138,31 @@ func (m *manager) HandleHealthCheckUnhealthy(ctx context.Context, id string) err lock.Lock() defer lock.Unlock() - current, err := m.currentInstanceWithoutHydration(ctx, id) + meta, err := m.loadMetadata(id) if err != nil { return err } - if current.State != StateRunning { + if meta.StopCleanupPending || m.toInstanceWithoutHydration(ctx, meta).State != StateRunning { return nil } - policy, err := restartpolicy.NormalizePolicy(current.RestartPolicy) + policy, err := restartpolicy.NormalizePolicy(meta.RestartPolicy) if err != nil { return err } if !restartpolicy.ShouldRestart(policy, nil) { return nil } - if current.RestartStatus.BlockedReason != "" { + if meta.RestartStatus.BlockedReason != "" { return nil } now := time.Now().UTC() - status := current.RestartStatus + status := meta.RestartStatus status.LastReason = restartpolicy.RestartReasonHealthCheckFailed - nextStatus, reason, shouldAttempt := prepareRestartAttempt(policy, status, now) + nextStatus, shouldAttempt := restartpolicy.PrepareAttempt(policy, status, now) if !shouldAttempt { - if !restartpolicy.EqualStatus(current.RestartStatus, nextStatus) { + if !restartpolicy.EqualStatus(meta.RestartStatus, nextStatus) { return m.updateRestartStatusLocked(id, nextStatus) } return nil @@ -173,20 +172,30 @@ func (m *manager) HandleHealthCheckUnhealthy(ctx context.Context, id string) err return err } + return m.finishHealthCheckRestartLocked(ctx, id, policy, nextStatus) +} + +func (m *manager) finishHealthCheckRestartLocked(ctx context.Context, id string, policy *restartpolicy.Policy, status restartpolicy.Status) error { + now := time.Now().UTC() stopped, err := m.stopInstance(ctx, id, StopInstanceRequest{}) - if err != nil { - _ = m.updateRestartStatusLocked(id, restartStatusAfterFailedAttempt(policy, nextStatus, reason, now)) - return err + if err == nil { + m.notifyLifecycleEvent(ctx, LifecycleEventStop, stopped) } - m.notifyLifecycleEvent(ctx, LifecycleEventStop, stopped) - - started, err := m.startInstance(ctx, id, StartInstanceRequest{}) - if err != nil { - _ = m.updateRestartStatusLocked(id, restartStatusAfterFailedAttempt(policy, nextStatus, reason, now)) + // An attempt already recorded as failed only owes cleanup. Once stopped, + // normal policy reconciliation respects its backoff or attempt limit. + if status.NextAttemptAt != nil || status.BlockedReason != "" { return err } - m.notifyLifecycleEvent(ctx, LifecycleEventStart, started) - return nil + if err == nil { + var started *Instance + started, err = m.startInstance(ctx, id, StartInstanceRequest{}) + if err == nil { + m.notifyLifecycleEvent(ctx, LifecycleEventStart, started) + return nil + } + } + _ = m.updateRestartStatusLocked(id, restartpolicy.AfterFailedAttempt(policy, status, now)) + return err } func (m *manager) StartRestartPolicyController(ctx context.Context) error { @@ -243,32 +252,61 @@ func (m *manager) reconcileRestartPolicies(ctx context.Context, log *slog.Logger log.WarnContext(ctx, "skipping restart policy reconcile for invalid instance metadata", "instance_id", id, "error", err) continue } - if meta.RestartPolicy == nil { - continue - } - inst := m.toInstanceWithoutHydration(ctx, meta) - if err := m.reconcileRestartPolicyInstance(ctx, &inst, log); err != nil { - log.WarnContext(ctx, "restart policy reconcile failed for instance", "instance_id", inst.Id, "error", err) + if err := m.reconcileRestartPolicyInstance(ctx, meta, log); err != nil { + log.WarnContext(ctx, "restart policy reconcile failed for instance", "instance_id", id, "error", err) } } return nil } func (m *manager) reconcileRestartPolicyInstanceID(ctx context.Context, id string, log *slog.Logger) error { - inst, err := m.currentInstanceWithoutHydration(ctx, id) + meta, err := m.loadMetadata(id) if errors.Is(err, ErrNotFound) { return nil } if err != nil { return err } - return m.reconcileRestartPolicyInstance(ctx, inst, log) + return m.reconcileRestartPolicyInstance(ctx, meta, log) +} + +func pendingHealthCheckRestart(meta *metadata) bool { + return meta.StopCleanupPending && meta.RestartPolicy != nil && + meta.RestartStatus.LastReason == restartpolicy.RestartReasonHealthCheckFailed && + meta.RestartStatus.BlockedReason != restartpolicy.BlockedReasonManualStop +} + +func (m *manager) resumeHealthCheckRestart(ctx context.Context, id string) error { + lock := m.getInstanceLock(id) + if !lock.TryLock() { + return nil // an active lifecycle operation takes precedence + } + defer lock.Unlock() + meta, err := m.loadMetadata(id) + if errors.Is(err, ErrNotFound) { + return nil + } + if err != nil || !pendingHealthCheckRestart(meta) { + return err + } + policy, err := restartpolicy.NormalizePolicy(meta.RestartPolicy) + if err != nil || policy == nil { + return err + } + return m.finishHealthCheckRestartLocked(ctx, id, policy, meta.RestartStatus) } -func (m *manager) reconcileRestartPolicyInstance(ctx context.Context, inst *Instance, log *slog.Logger) error { - if inst == nil { +func (m *manager) reconcileRestartPolicyInstance(ctx context.Context, meta *metadata, log *slog.Logger) error { + if meta.RestartPolicy == nil { + return nil + } + if meta.StopCleanupPending { + if pendingHealthCheckRestart(meta) { + return m.resumeHealthCheckRestart(ctx, meta.Id) + } return nil } + inst := m.toInstanceWithoutHydration(ctx, meta) policy, err := restartpolicy.NormalizePolicy(inst.RestartPolicy) if err != nil { return err @@ -279,9 +317,11 @@ func (m *manager) reconcileRestartPolicyInstance(ctx context.Context, inst *Inst status := inst.RestartStatus now := time.Now().UTC() - if shouldResetRestartAttempts(policy, status, inst, now) { + if shouldResetRestartAttempts(policy, status, &inst, now) { log.InfoContext(ctx, "restart policy stable window reached", "instance_id", inst.Id, "attempts", status.Attempts) - _, err := m.setRestartStatus(ctx, inst.Id, restartpolicy.Status{}) + _, err := m.setRestartStatusIf(ctx, inst.Id, restartpolicy.Status{}, func(current *metadata) bool { + return !current.StopCleanupPending && restartpolicy.EqualStatus(current.RestartStatus, status) + }) return err } if inst.State != StateStopped || status.BlockedReason != "" { diff --git a/lib/instances/restart_policy_test.go b/lib/instances/restart_policy_test.go index 9d90247f4..7fba79e39 100644 --- a/lib/instances/restart_policy_test.go +++ b/lib/instances/restart_policy_test.go @@ -8,7 +8,9 @@ import ( "testing" "time" + "github.com/kernel/hypeman/lib/devices" "github.com/kernel/hypeman/lib/hypervisor" + "github.com/kernel/hypeman/lib/images" restartpolicy "github.com/kernel/hypeman/lib/restart-policy" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -269,6 +271,58 @@ func TestStartInstanceForRestartPolicySkipsConcurrentStart(t *testing.T) { assert.True(t, loaded.RestartStatus.IsZero()) } +func TestReconcileInterruptedHealthCheckStop(t *testing.T) { + now := time.Now().UTC() + for _, tc := range []struct { + name string + block restartpolicy.BlockedReason + next *time.Time + wantCleanup, wantStart bool + }{ + {name: "resume reserved attempt", wantCleanup: true, wantStart: true}, + {name: "manual stop", block: restartpolicy.BlockedReasonManualStop}, + {name: "exhausted attempts", block: restartpolicy.BlockedReasonMaxAttemptsExceeded, wantCleanup: true}, + {name: "retry scheduled", next: new(now.Add(time.Hour)), wantCleanup: true}, + } { + t.Run(tc.name, func(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateStopped, now) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.StopCleanupPending = true + meta.GPUDevicePath = "/sys/bus/pci/devices/0000:82:00.4" + meta.RestartPolicy = &restartpolicy.Policy{Policy: restartpolicy.PolicyAlways, MaxAttempts: 1} + meta.RestartStatus = restartpolicy.Status{ + Attempts: 1, LastAttemptAt: &now, LastReason: restartpolicy.RestartReasonHealthCheckFailed, + BlockedReason: tc.block, NextAttemptAt: tc.next, + } + require.NoError(t, m.saveMetadata(meta)) + + // A rejected manual start must not erase the controller's pending attempt or manual-stop block. + _, err = m.StartInstance(t.Context(), id, StartInstanceRequest{}) + require.ErrorIs(t, err, ErrInvalidState) + m.destroyVGPU = func(context.Context, devices.VGPUAssignment) error { return nil } + m.imageManager = readyFixtureImageManager{} // a cold start reaches image lookup and fails + err = m.reconcileRestartPolicyInstanceID(t.Context(), id, slog.Default()) + if tc.wantStart { + require.ErrorIs(t, err, images.ErrNotFound) + } else { + require.NoError(t, err) + } + stored, err := m.loadMetadata(id) + require.NoError(t, err) + require.Equal(t, tc.wantCleanup, stored.StoppedAt != nil) + require.Equal(t, !tc.wantCleanup, stored.StopCleanupPending) + require.Equal(t, tc.wantCleanup, stored.GPUDevicePath == "") + require.Equal(t, 1, stored.RestartStatus.Attempts) + if tc.wantStart { + require.Equal(t, restartpolicy.BlockedReasonMaxAttemptsExceeded, stored.RestartStatus.BlockedReason) + } else { + require.True(t, restartpolicy.EqualStatus(meta.RestartStatus, stored.RestartStatus)) + } + }) + } +} + func TestReconcileRestartPolicyInstanceIDUsesCurrentState(t *testing.T) { manager, _ := setupTestManager(t) id := "restart-current-state" diff --git a/lib/instances/snapshot.go b/lib/instances/snapshot.go index dd6f6aead..e99ce01d6 100644 --- a/lib/instances/snapshot.go +++ b/lib/instances/snapshot.go @@ -287,6 +287,9 @@ func (m *manager) restoreSnapshot(ctx context.Context, id string, snapshotID str if err != nil { return nil, err } + if sourceMeta.StopCleanupPending { + return nil, fmt.Errorf("%w: cannot restore snapshot while stop cleanup is pending", ErrInvalidState) + } if err := validateMacOSSnapshotRestore(sourceMeta, rec); err != nil { return nil, err } diff --git a/lib/instances/snapshot_test.go b/lib/instances/snapshot_test.go index b23e364ee..57e8eb62e 100644 --- a/lib/instances/snapshot_test.go +++ b/lib/instances/snapshot_test.go @@ -93,6 +93,24 @@ func TestRestoreSnapshotDoesNotResurrectStaleVGPUAssignment(t *testing.T) { assert.Empty(t, restored.GPUMdevUUID) } +func TestRestoreSnapshotRejectsPendingStop(t *testing.T) { + m, _ := setupTestManager(t) + const id = "restore-while-stopping" + createStoppedSnapshotSourceFixture(t, m, id, id, m.defaultHypervisor) + snap, err := m.CreateSnapshot(t.Context(), id, CreateSnapshotRequest{Kind: SnapshotKindStopped, Name: "before-stop"}) + require.NoError(t, err) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.StopCleanupPending = true + require.NoError(t, m.saveMetadata(meta)) + afterSnapshot := filepath.Join(meta.DataDir, "after-snapshot") + require.NoError(t, os.WriteFile(afterSnapshot, nil, 0600)) + + _, err = m.RestoreSnapshot(t.Context(), id, snap.Id, RestoreSnapshotRequest{TargetState: StateStopped}) + require.ErrorIs(t, err, ErrInvalidState) + require.FileExists(t, afterSnapshot) +} + func TestRestoreSnapshotKeepsCurrentVGPUAssignment(t *testing.T) { mgr, _ := setupTestManager(t) ctx := context.Background() diff --git a/lib/instances/stop.go b/lib/instances/stop.go index 1772d4467..7358f5772 100644 --- a/lib/instances/stop.go +++ b/lib/instances/stop.go @@ -123,6 +123,9 @@ func (m *manager) tryGracefulGuestShutdown(ctx context.Context, inst *Instance, // beginVFIOStop saves the confirmed owner while its socket is still available. // A retry cannot recover a legacy PID from a listener already closed by SIGTERM. func (m *manager) beginVFIOStop(meta *metadata, inst *Instance) error { + if meta.StopCleanupPending || !hasVFIODevices(&meta.StoredMetadata) { + return nil + } pid, err := resolveLiveHypervisorPID(meta.HypervisorProcessIdentity, meta.SocketPath) if err != nil { return err @@ -130,6 +133,8 @@ func (m *manager) beginVFIOStop(meta *metadata, inst *Instance) error { if pid > 0 { inst.HypervisorProcessIdentity.Set(pid) meta.HypervisorProcessIdentity = inst.HypervisorProcessIdentity + } else if inst.State == StateStopped || inst.State == StateStandby { + return nil // deleting an already inactive guest needs no pending stop } meta.StopCleanupPending = true return m.saveMetadata(meta) @@ -176,10 +181,8 @@ func (m *manager) stopInstance( return nil, fmt.Errorf("%w: cannot stop from state %s, must be Running or Initializing", ErrInvalidState, inst.State) } - if hasVFIODevices(stored) && !meta.StopCleanupPending { - if err := m.beginVFIOStop(meta, &inst); err != nil { - return nil, fmt.Errorf("record pending VFIO stop: %w", err) - } + if err := m.beginVFIOStop(meta, &inst); err != nil { + return nil, fmt.Errorf("record pending VFIO stop: %w", err) } // 3. Get network allocation BEFORE killing VMM (while we can still query it) @@ -247,7 +250,16 @@ func (m *manager) stopInstance( } } - // 6. Release network allocation (delete TAP device) + // 6. Release the vGPU first so a failed reset can be retried without + // repeating the network teardown. The on-disk stop is still pending. + if path := storedVGPUDevicePath(stored); path != "" { + log.InfoContext(ctx, "destroying vGPU on stop", "instance_id", id, "device_path", path) + if err := m.releaseStoredVGPU(ctx, stored); err != nil { + return nil, fmt.Errorf("release vGPU: %w", err) + } + } + + // 7. Release network allocation (delete TAP device) if inst.NetworkEnabled { m.unregisterEgressProxyInstance(ctx, id) } @@ -282,14 +294,6 @@ func (m *manager) stopInstance( } } - // 7. Release the vGPU assignment if present (frees the vGPU slot for other VMs). - if path := storedVGPUDevicePath(stored); path != "" { - log.InfoContext(ctx, "destroying vGPU on stop", "instance_id", id, "device_path", path) - if err := m.releaseStoredVGPU(ctx, stored); err != nil { - log.WarnContext(ctx, "failed to destroy vGPU on stop; retaining assignment metadata", "instance_id", id, "device_path", path, "error", err) - } - } - // 8. Drop the guest-agent and hypervisor connections for this VM incarnation // and remove stale runtime sockets after process exit. The hypervisor // shutdown closes the live peer, but the keyed gRPC ClientConn must not diff --git a/lib/instances/storage.go b/lib/instances/storage.go index 01baa2c56..e3bc0b8fe 100644 --- a/lib/instances/storage.go +++ b/lib/instances/storage.go @@ -42,8 +42,8 @@ const ( // metadata wraps StoredMetadata for JSON serialization type metadata struct { StoredMetadata - // A VFIO stop may outlive its caller. Keep it distinct from an ordinary - // stopped instance until the stop has released resources and saved StoppedAt. + // Stop and delete set this before signaling a VFIO guest. A missing + // socket does not mean it is safe to reuse the instance or its devices. StopCleanupPending bool `json:"stop_cleanup_pending,omitempty"` AutoStandbyRuntime *autostandby.Runtime `json:"auto_standby_runtime,omitempty"` HealthCheckRuntime *healthcheck.Runtime `json:"health_check_runtime,omitempty"` diff --git a/lib/instances/vfio_lifecycle_linux_test.go b/lib/instances/vfio_lifecycle_linux_test.go index 92d7aeaef..e21747b72 100644 --- a/lib/instances/vfio_lifecycle_linux_test.go +++ b/lib/instances/vfio_lifecycle_linux_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/kernel/hypeman/lib/devices" + "github.com/kernel/hypeman/lib/hypervisor" "github.com/kernel/hypeman/lib/network" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -42,6 +43,44 @@ func TestCanceledForkRollbackRemovesRunningVFIOGuest(t *testing.T) { assert.NoDirExists(t, meta.DataDir) } +func TestInterruptedVFIODeleteKeepsLegacySocketOwner(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.SocketPath = filepath.Join(t.TempDir(), "vmm.sock") + pid, closeListener := startClosingSocketOwner(t, meta.SocketPath) + meta.HypervisorPID = &pid // legacy metadata without a boot-scoped identity + meta.Devices = []string{"dev-1"} + meta.StopTimeout = 1 + require.NoError(t, m.saveMetadata(meta)) + m.storeCachedHypervisorState(id, hypervisor.StateRunning) + dev := &recordingDeviceManager{} + m.deviceManager = dev + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + m.shutdownGuestFn = func(context.Context, hypervisor.VsockDialer, int32) error { + require.NoError(t, closeListener()) + cancel() + return nil + } + require.ErrorIs(t, m.DeleteInstance(ctx, id), context.Canceled) + + restarted := &manager{paths: m.paths, deviceManager: dev, lifecycleEvents: newLifecycleSubscribers()} + require.ErrorIs(t, restarted.DeleteInstance(ctx, id), context.Canceled) + require.Empty(t, dev.detached) + require.DirExists(t, meta.DataDir) + stored, err := restarted.loadMetadata(id) + require.NoError(t, err) + require.Equal(t, processStartTime(pid), stored.HypervisorStartTime) + require.NotZero(t, stored.HypervisorStartTime) + require.Equal(t, hostBootID(), stored.HypervisorBootID) + + dev.onMarkDetached = func() { assert.False(t, ProcessExists(pid), "device detached before its owner exited") } + require.NoError(t, restarted.DeleteInstance(t.Context(), id)) + require.Equal(t, []string{"dev-1"}, dev.detached) + require.NoDirExists(t, meta.DataDir) +} + type stopRetryNetwork struct { network.Manager released []string @@ -96,6 +135,10 @@ func TestStopRetryFinishesAfterVFIOGuestExits(t *testing.T) { pending, err := restarted.currentInstanceWithoutHydration(t.Context(), id) require.NoError(t, err) require.Equal(t, StateShutdown, pending.State) + ttl := time.Hour + updated, err := restarted.UpdateInstance(t.Context(), id, UpdateInstanceRequest{TTL: &ttl}) + require.NoError(t, err) + require.Equal(t, StateShutdown, updated.State, "a TTL update must preserve the pending stop") require.ErrorIs(t, restarted.DeleteInstance(ctx, id), context.Canceled) require.True(t, ProcessExists(pid)) require.Empty(t, net.released) diff --git a/lib/restart-policy/README.md b/lib/restart-policy/README.md index f8dd76bb9..10356600d 100644 --- a/lib/restart-policy/README.md +++ b/lib/restart-policy/README.md @@ -53,7 +53,7 @@ Health checks are a separate feature. They report workload health without changi When health status reaches `unhealthy`, restart policy treats that as a failure signal for `on_failure` and `always`. `never` still reports health without restarting. -Health-triggered restart uses the same attempt counter, backoff, max-attempt limit, manual-stop suppression, and stable-window reset as exit-triggered restart. +Health-triggered restart uses the same attempt counter, backoff, max-attempt limit, manual-stop suppression, and stable-window reset as exit-triggered restart. If Hypeman restarts during a VFIO stop for a health check, the controller finishes cleanup and resumes the same attempt. An attempt already recorded as failed still observes its backoff or limit. ## Lifecycle Behavior From ee5e16b47a8e0258471485ddeaa19033504b2d85 Mon Sep 17 00:00:00 2001 From: yummybomb <19238148+yummybomb@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:37:42 +0000 Subject: [PATCH 5/5] Recover VFIO stops and reserved restarts across cancellation --- lib/devices/GPU.md | 11 ++++ lib/hypervisor/qemu/process.go | 9 +-- lib/hypervisor/qemu/process_test.go | 10 +++ lib/instances/fork.go | 7 ++- lib/instances/fork_test.go | 61 ++++++++++++++++++ lib/instances/liveness.go | 9 +-- lib/instances/query.go | 1 + lib/instances/restart_policy.go | 73 +++++++++++++++------- lib/instances/restart_policy_test.go | 66 +++++++++++++++++++ lib/instances/stop.go | 6 +- lib/instances/storage.go | 4 +- lib/instances/tap_gc.go | 8 +-- lib/instances/types.go | 1 + lib/instances/update.go | 3 + lib/instances/vfio_lifecycle_linux_test.go | 6 ++ lib/restart-policy/README.md | 2 +- 16 files changed, 233 insertions(+), 44 deletions(-) diff --git a/lib/devices/GPU.md b/lib/devices/GPU.md index 1bc34d2db..339a1ea87 100644 --- a/lib/devices/GPU.md +++ b/lib/devices/GPU.md @@ -110,6 +110,17 @@ If a stop or delete is interrupted, retry the same operation. The control socket can disappear before the VMM releases its devices. Hypeman keeps the process identity and confirms exit on retry; it rejects starts and snapshot restores while cleanup is pending. A failed vGPU reset also leaves the stop pending. +Startup PCI reconciliation and TAP garbage collection leave these resources +to the pending stop or delete. + +Before downgrading to a build without this recovery logic, drain the host of +new lifecycle requests and let in-flight operations finish. Check the guest +`metadata.json` files for `stop_cleanup_pending: true` or +`health_start_pending: true`. Retry the original manual stop/delete +or let the restart controller finish its reserved attempt on the current build. +Stop the server and check once more before starting the older build; a +controller may have begun another stop during the drain. If a marker remains, +restart the current build to finish recovery rather than clearing it by hand. Hypeman reconciles metadata claims once at startup and every minute afterward, skipping hosts without GPUs. A claim whose VMM is confirmed dead is reset before the claim is removed. An ambiguous hypervisor ownership check preserves the claim, logs a warning, and increments `hypeman_instances_vgpu_liveness_uncertain_total`; the create and start cleanup paths preserve and count the same way. mdev hosts also sweep orphaned device-level assignments. Vendor VFIO hosts reset unclaimed dirty VFs on every reconcile pass, which covers a restart between a claim writing the type and saving the claim, or a failed claim whose reset also failed, but also clears a type written to `current_vgpu_type` by hand unless the VF has an open VFIO handle. A reset that is refused is retried on the next pass and increments `hypeman_instances_vgpu_reconcile_failures_total{stage="reset_unclaimed_vfs"}`. The allocator also repairs an unclaimed dirty VF when it next selects it; repair checks for open VFIO handles before resetting `current_vgpu_type`. The allocator prefers VFs that are already clean, and a dirty VF that refuses its reset is skipped in favor of another candidate. diff --git a/lib/hypervisor/qemu/process.go b/lib/hypervisor/qemu/process.go index 4202036cf..1e89ae4e2 100644 --- a/lib/hypervisor/qemu/process.go +++ b/lib/hypervisor/qemu/process.go @@ -308,12 +308,9 @@ func cleanupFailedStart(ctx context.Context, proc *startedProcess, termGrace tim teardown := hypervisor.BeginVFIOTeardown() defer teardown.Done() if syscall.Kill(proc.pid, syscall.SIGTERM) == nil { - start := time.Now() - if _, err := teardown.Wait(ctx, termGrace, 0, proc.waitFor); err != nil { - // Rollback must reap the child even after cancellation, but - // don't cut its base grace short to do so. - proc.waitFor(termGrace - time.Since(start)) - } + // Rollback owns this child. Wait enforces its own bounded grace + // even when the failed startup's deadline has already expired. + _, _ = teardown.Wait(context.WithoutCancel(ctx), termGrace, 0, proc.waitFor) } } proc.cleanup() diff --git a/lib/hypervisor/qemu/process_test.go b/lib/hypervisor/qemu/process_test.go index ec42f9553..8bb6d0c00 100644 --- a/lib/hypervisor/qemu/process_test.go +++ b/lib/hypervisor/qemu/process_test.go @@ -512,6 +512,16 @@ func TestCleanupEscalatesToSIGKILLAfterTermGrace(t *testing.T) { require.NoFileExists(t, proc.socketPath) } +func TestCanceledCleanupSharesVFIOGrace(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + peer := hypervisor.BeginVFIOTeardown() + defer peer.Done() + proc, cmd := startCleanupProcess(t, "sleep 0.5; exit 0") + cleanupFailedStart(ctx, proc, 100*time.Millisecond) + require.True(t, cmd.ProcessState.Success(), "cancellation must not cut rollback back to the base grace") +} + func TestCleanupSharesVFIOGraceWithLifecycleTeardown(t *testing.T) { started := filepath.Join(t.TempDir(), "terminating") proc, cmd := startCleanupProcess(t, fmt.Sprintf("touch %q; sleep 0.8; exit 0", started)) diff --git a/lib/instances/fork.go b/lib/instances/fork.go index 1fb79a1f8..a51fd0a6f 100644 --- a/lib/instances/fork.go +++ b/lib/instances/fork.go @@ -101,7 +101,10 @@ 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) + // Putting the source back is required even if the fork request timed out. + restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute) + defer cancel() + restoredSource, restoreErr := m.restoreInstance(restoreCtx, id) if restoreErr != nil { if forkErr != nil { @@ -110,7 +113,7 @@ func (m *manager) forkInstance(ctx context.Context, id string, req ForkInstanceR 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 err := ensureGuestAgentReadyForForkPhase(restoreCtx, &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) } diff --git a/lib/instances/fork_test.go b/lib/instances/fork_test.go index 2ce61f3ad..c9c3dd9c2 100644 --- a/lib/instances/fork_test.go +++ b/lib/instances/fork_test.go @@ -322,6 +322,67 @@ func (concurrentForkPrepareTestStarter) PrepareFork(context.Context, hypervisor. return hypervisor.ForkPrepareResult{}, nil } +type cancelForkRestoreStarter struct { + concurrentForkPrepareTestStarter + cancel context.CancelFunc + source string +} + +func (s cancelForkRestoreStarter) RestoreVM(ctx context.Context, p *paths.Paths, version, socket, snapshot string) (int, hypervisor.Hypervisor, error) { + if socket != s.source { + s.cancel() + return 0, nil, ctx.Err() + } + if err := ctx.Err(); err != nil { + return 0, nil, err + } + if _, ok := ctx.Deadline(); !ok { + return 0, nil, errors.New("source recovery has no deadline") + } + _, hv, err := s.concurrentForkPrepareTestStarter.RestoreVM(ctx, p, version, socket, snapshot) + return 0, hv, err +} + +type forkSnapshotTestHypervisor struct{ lifecycleNoopHypervisor } + +func (forkSnapshotTestHypervisor) Capabilities() hypervisor.Capabilities { + return hypervisor.Capabilities{SupportsSnapshot: true} +} + +func (forkSnapshotTestHypervisor) Snapshot(_ context.Context, dir string) error { + return os.WriteFile(filepath.Join(dir, "state"), []byte("snapshot"), 0600) +} + +func TestCanceledRunningForkRestoresSource(t *testing.T) { + m := &manager{paths: paths.New(t.TempDir()), vmStarters: make(map[hypervisor.Type]hypervisor.VMStarter), lifecycleEvents: newLifecycleSubscribers()} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + const hvType = hypervisor.Type("cancel-running-fork") + hypervisor.RegisterClientFactory(hvType, func(string) (hypervisor.Hypervisor, error) { + return forkSnapshotTestHypervisor{lifecycleNoopHypervisor{state: hypervisor.StateRunning}}, nil + }) + const id = "fork-source" + socket := m.paths.InstanceSocket(id, concurrentForkPrepareTestStarter{}.SocketName()) + m.vmStarters[hvType] = cancelForkRestoreStarter{cancel: cancel, source: socket} + createStoppedSnapshotSourceFixture(t, m, id, id, hvType) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.SkipGuestAgent = true + meta.StartedAt = new(time.Now().UTC()) + meta.ProgramStartedAt = meta.StartedAt + meta.StoppedAt = nil + require.NoError(t, m.saveMetadata(meta)) + require.NoError(t, os.WriteFile(socket, nil, 0600)) + + _, err = m.ForkInstance(ctx, id, ForkInstanceRequest{Name: "canceled-fork", FromRunning: true, TargetState: StateRunning}) + require.ErrorIs(t, err, context.Canceled) + insts, err := m.ListInstances(t.Context(), nil) + require.NoError(t, err) + require.Len(t, insts, 1, "the failed child must be removed") + require.Equal(t, id, insts[0].Id) + require.Equal(t, StateRunning, insts[0].State) +} + func TestForkInstanceStandbyRunningTargetSkipsSourceWriteLockWithoutAlias(t *testing.T) { manager, _ := setupTestManager(t) ctx := context.Background() diff --git a/lib/instances/liveness.go b/lib/instances/liveness.go index 92f27dc53..0bbb1ede3 100644 --- a/lib/instances/liveness.go +++ b/lib/instances/liveness.go @@ -28,9 +28,8 @@ func NewLivenessChecker(m Manager) devices.InstanceLivenessChecker { return &instanceLivenessAdapter{manager: mgr} } -// IsInstanceRunning returns true if the instance exists and is in a running state -// (i.e., has an active VMM process). Returns false if the instance doesn't exist -// or is stopped/standby/unknown. +// IsInstanceRunning protects device attachments for active VMMs and for +// pending stops whose VMM may have already closed its control socket. func (a *instanceLivenessAdapter) IsInstanceRunning(ctx context.Context, instanceID string) bool { if a.manager == nil { return false @@ -40,13 +39,11 @@ func (a *instanceLivenessAdapter) IsInstanceRunning(ctx context.Context, instanc return false } - // Consider instance "running" if the VMM is active (any of these states means VM is using the device) switch inst.State { case StateRunning, StateInitializing, StatePaused, StateCreated: return true default: - // StateStopped, StateStandby, StateShutdown, StateUnknown - return false + return inst.stopCleanupPending } } diff --git a/lib/instances/query.go b/lib/instances/query.go index 822e9cc68..b5da270e5 100644 --- a/lib/instances/query.go +++ b/lib/instances/query.go @@ -565,6 +565,7 @@ func (m *manager) toInstanceWithStateDerivation(ctx context.Context, meta *metad StateError: result.Error, HasSnapshot: m.hasSnapshot(meta.StoredMetadata.DataDir), BootMarkersHydrated: result.BootMarkersHydrated, + stopCleanupPending: meta.StopCleanupPending, HealthCheckRuntime: healthcheck.CloneRuntime(meta.HealthCheckRuntime), } refreshHypervisorPID(&inst.StoredMetadata, result.State) diff --git a/lib/instances/restart_policy.go b/lib/instances/restart_policy.go index 6509921bf..bb208950a 100644 --- a/lib/instances/restart_policy.go +++ b/lib/instances/restart_policy.go @@ -56,6 +56,7 @@ func (m *manager) markRestartManualStopLocked(ctx context.Context, id string) er return nil } meta.RestartStatus = status + meta.HealthStartPending = false if err := m.saveMetadata(meta); err != nil { logger.FromContext(ctx).WarnContext(ctx, "failed to mark restart policy manual stop", "instance_id", id, "error", err) return err @@ -76,6 +77,7 @@ func (m *manager) clearRestartStatusLocked(ctx context.Context, id string) error return nil } meta.RestartStatus = restartpolicy.Status{} + meta.HealthStartPending = false if err := m.saveMetadata(meta); err != nil { logger.FromContext(ctx).WarnContext(ctx, "failed to clear restart policy status", "instance_id", id, "error", err) return err @@ -89,6 +91,7 @@ func (m *manager) updateRestartStatusLocked(id string, status restartpolicy.Stat return err } meta.RestartStatus = status + meta.HealthStartPending = false return m.saveMetadata(meta) } @@ -107,6 +110,9 @@ func (m *manager) setRestartStatusIf(ctx context.Context, id string, status rest if err != nil { return false, err } + if pendingHealthCheckRestart(meta) { + return false, nil + } if meta.RestartStatus.BlockedReason == restartpolicy.BlockedReasonManualStop && status.BlockedReason != restartpolicy.BlockedReasonManualStop { return false, nil @@ -142,7 +148,11 @@ func (m *manager) HandleHealthCheckUnhealthy(ctx context.Context, id string) err if err != nil { return err } - if meta.StopCleanupPending || m.toInstanceWithoutHydration(ctx, meta).State != StateRunning { + if meta.StopCleanupPending || meta.HealthStartPending { + return nil + } + current := m.toInstanceWithoutHydration(ctx, meta) + if current.State != StateRunning { return nil } @@ -168,23 +178,33 @@ func (m *manager) HandleHealthCheckUnhealthy(ctx context.Context, id string) err return nil } - if err := m.updateRestartStatusLocked(id, nextStatus); err != nil { + // Reserve the attempt and record the VFIO stop in one metadata write. + meta.RestartStatus = nextStatus + if hasVFIODevices(&meta.StoredMetadata) { + err = m.beginVFIOStop(meta, ¤t) + } else { + err = m.saveMetadata(meta) + } + if err != nil { return err } - - return m.finishHealthCheckRestartLocked(ctx, id, policy, nextStatus) + return m.finishHealthCheckRestartLocked(ctx, meta, policy) } -func (m *manager) finishHealthCheckRestartLocked(ctx context.Context, id string, policy *restartpolicy.Policy, status restartpolicy.Status) error { +func (m *manager) finishHealthCheckRestartLocked(ctx context.Context, meta *metadata, policy *restartpolicy.Policy) error { now := time.Now().UTC() - stopped, err := m.stopInstance(ctx, id, StopInstanceRequest{}) - if err == nil { - m.notifyLifecycleEvent(ctx, LifecycleEventStop, stopped) - } - // An attempt already recorded as failed only owes cleanup. Once stopped, - // normal policy reconciliation respects its backoff or attempt limit. - if status.NextAttemptAt != nil || status.BlockedReason != "" { - return err + id, status := meta.Id, meta.RestartStatus + var err error + if !meta.HealthStartPending { + var stopped *Instance + stopped, err = m.stopInstance(ctx, id, StopInstanceRequest{}) + if err == nil { + m.notifyLifecycleEvent(ctx, LifecycleEventStop, stopped) + } + // A failed attempt still owes cleanup, not another start. + if status.NextAttemptAt != nil || status.BlockedReason != "" { + return err + } } if err == nil { var started *Instance @@ -194,8 +214,7 @@ func (m *manager) finishHealthCheckRestartLocked(ctx context.Context, id string, return nil } } - _ = m.updateRestartStatusLocked(id, restartpolicy.AfterFailedAttempt(policy, status, now)) - return err + return errors.Join(err, m.updateRestartStatusLocked(id, restartpolicy.AfterFailedAttempt(policy, status, now))) } func (m *manager) StartRestartPolicyController(ctx context.Context) error { @@ -271,7 +290,7 @@ func (m *manager) reconcileRestartPolicyInstanceID(ctx context.Context, id strin } func pendingHealthCheckRestart(meta *metadata) bool { - return meta.StopCleanupPending && meta.RestartPolicy != nil && + return (meta.StopCleanupPending || meta.HealthStartPending) && meta.RestartPolicy != nil && meta.RestartStatus.LastReason == restartpolicy.RestartReasonHealthCheckFailed && meta.RestartStatus.BlockedReason != restartpolicy.BlockedReasonManualStop } @@ -293,17 +312,25 @@ func (m *manager) resumeHealthCheckRestart(ctx context.Context, id string) error if err != nil || policy == nil { return err } - return m.finishHealthCheckRestartLocked(ctx, id, policy, meta.RestartStatus) + if meta.HealthStartPending { + state := m.toInstanceWithoutHydration(ctx, meta).State + if state == StateRunning || state == StateInitializing { + // The VMM started before the server committed its metadata. + meta.HealthStartPending = false + return m.saveMetadata(meta) + } + if state != StateStopped { + return nil // wait for a definitive state before starting + } + } + return m.finishHealthCheckRestartLocked(ctx, meta, policy) } func (m *manager) reconcileRestartPolicyInstance(ctx context.Context, meta *metadata, log *slog.Logger) error { - if meta.RestartPolicy == nil { - return nil + if pendingHealthCheckRestart(meta) { + return m.resumeHealthCheckRestart(ctx, meta.Id) } - if meta.StopCleanupPending { - if pendingHealthCheckRestart(meta) { - return m.resumeHealthCheckRestart(ctx, meta.Id) - } + if meta.RestartPolicy == nil || meta.StopCleanupPending { return nil } inst := m.toInstanceWithoutHydration(ctx, meta) diff --git a/lib/instances/restart_policy_test.go b/lib/instances/restart_policy_test.go index 7fba79e39..12f05560d 100644 --- a/lib/instances/restart_policy_test.go +++ b/lib/instances/restart_policy_test.go @@ -323,6 +323,72 @@ func TestReconcileInterruptedHealthCheckStop(t *testing.T) { } } +func TestHealthRestartSurvivesCrashAfterStop(t *testing.T) { + for _, tc := range []struct { + name string + wantErr error + wantAttempts int + wantBlock restartpolicy.BlockedReason + }{ + {"before start", images.ErrNotFound, 1, restartpolicy.BlockedReasonMaxAttemptsExceeded}, + {"after boot", nil, 1, ""}, + {"manual stop", nil, 0, restartpolicy.BlockedReasonManualStop}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Now().UTC() + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, now) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.Devices = []string{"pci-device"} + meta.RestartPolicy = &restartpolicy.Policy{Policy: restartpolicy.PolicyAlways, MaxAttempts: 1} + meta.RestartStatus = restartpolicy.Status{Attempts: 1, LastAttemptAt: &now, LastReason: restartpolicy.RestartReasonHealthCheckFailed} + require.NoError(t, m.saveMetadata(meta)) + + // Only the stop made it to disk. The next server owns recovery. + _, err = m.stopInstance(t.Context(), id, StopInstanceRequest{}) + require.NoError(t, err) + restarted := &manager{paths: m.paths, lifecycleEvents: newLifecycleSubscribers(), imageManager: readyFixtureImageManager{}} + switch tc.name { + case "after boot": + writeLifecycleNoopSocket(t, meta.SocketPath, hypervisor.StateRunning) + case "manual stop": + _, err = restarted.StopInstance(t.Context(), id, StopInstanceRequest{}) + require.NoError(t, err) + } + err = restarted.reconcileRestartPolicyInstanceID(t.Context(), id, slog.Default()) + require.ErrorIs(t, err, tc.wantErr) + require.NoError(t, restarted.reconcileRestartPolicyInstanceID(t.Context(), id, slog.Default())) + meta, err = restarted.loadMetadata(id) + require.NoError(t, err) + require.False(t, meta.HealthStartPending) + require.Equal(t, tc.wantAttempts, meta.RestartStatus.Attempts) + require.Equal(t, tc.wantBlock, meta.RestartStatus.BlockedReason) + }) + } +} + +func TestRestartPolicyUpdateDuringFailedHealthStop(t *testing.T) { + m, id := newLifecycleNoopManagerWithInstance(t, StateRunning, time.Now().UTC()) + meta, err := m.loadMetadata(id) + require.NoError(t, err) + meta.GPUDevicePath = "/sys/bus/pci/devices/0000:82:00.4" + meta.RestartPolicy = &restartpolicy.Policy{Policy: restartpolicy.PolicyAlways, MaxAttempts: 1} + require.NoError(t, m.saveMetadata(meta)) + resetErr := errors.New("reset failed") + m.destroyVGPU = func(context.Context, devices.VGPUAssignment) error { return resetErr } + require.ErrorIs(t, m.HandleHealthCheckUnhealthy(t.Context(), id), resetErr) + + _, err = m.UpdateInstance(t.Context(), id, UpdateInstanceRequest{RestartPolicySet: true, RestartPolicy: meta.RestartPolicy}) + assert.ErrorIs(t, err, ErrInvalidState) + m.destroyVGPU = func(context.Context, devices.VGPUAssignment) error { return nil } + require.NoError(t, m.reconcileRestartPolicyInstanceID(t.Context(), id, slog.Default())) + meta, err = m.loadMetadata(id) + require.NoError(t, err) + assert.False(t, meta.StopCleanupPending) + assert.Empty(t, meta.GPUDevicePath) + assert.Equal(t, restartpolicy.BlockedReasonMaxAttemptsExceeded, meta.RestartStatus.BlockedReason) +} + func TestReconcileRestartPolicyInstanceIDUsesCurrentState(t *testing.T) { manager, _ := setupTestManager(t) id := "restart-current-state" diff --git a/lib/instances/stop.go b/lib/instances/stop.go index 7358f5772..ad05075c9 100644 --- a/lib/instances/stop.go +++ b/lib/instances/stop.go @@ -339,7 +339,11 @@ func (m *manager) stopInstance( stored.GuestAgent = nil stored.Phases.Record(phasetracking.PhaseStopped, now) - meta = &metadata{StoredMetadata: *stored} + meta = &metadata{ + StoredMetadata: *stored, + HealthStartPending: pendingHealthCheckRestart(meta) && + meta.RestartStatus.NextAttemptAt == nil && meta.RestartStatus.BlockedReason == "", + } if err := m.saveMetadata(meta); err != nil { log.ErrorContext(ctx, "failed to save metadata", "instance_id", id, "error", err) return nil, fmt.Errorf("save metadata: %w", err) diff --git a/lib/instances/storage.go b/lib/instances/storage.go index e3bc0b8fe..d7c8fa7ee 100644 --- a/lib/instances/storage.go +++ b/lib/instances/storage.go @@ -44,7 +44,9 @@ type metadata struct { StoredMetadata // Stop and delete set this before signaling a VFIO guest. A missing // socket does not mean it is safe to reuse the instance or its devices. - StopCleanupPending bool `json:"stop_cleanup_pending,omitempty"` + StopCleanupPending bool `json:"stop_cleanup_pending,omitempty"` + // Committed with StoppedAt when the reserved health-check attempt still owes a start. + HealthStartPending bool `json:"health_start_pending,omitempty"` AutoStandbyRuntime *autostandby.Runtime `json:"auto_standby_runtime,omitempty"` HealthCheckRuntime *healthcheck.Runtime `json:"health_check_runtime,omitempty"` } diff --git a/lib/instances/tap_gc.go b/lib/instances/tap_gc.go index 32a51c43f..e2b604df1 100644 --- a/lib/instances/tap_gc.go +++ b/lib/instances/tap_gc.go @@ -2,6 +2,7 @@ package instances import ( "context" + "slices" "time" "github.com/kernel/hypeman/lib/logger" @@ -17,12 +18,11 @@ const ( ) // TAPPreserveIDs returns the instances whose TAPs must survive orphan cleanup. -// Paused guests still own their TAPs; Unknown guests may still have a live VMM. +// Paused, unknown and pending-stop guests may still own their TAPs. func TAPPreserveIDs(instances []Instance) []string { ids := make([]string, 0, len(instances)) for _, inst := range instances { - switch inst.State { - case StateRunning, StateInitializing, StatePaused, StateUnknown: + if inst.stopCleanupPending || slices.Contains([]State{StateRunning, StateInitializing, StatePaused, StateUnknown}, inst.State) { ids = append(ids, inst.Id) } } @@ -31,7 +31,7 @@ func TAPPreserveIDs(instances []Instance) []string { // StartTAPGCReconciler starts a background goroutine that periodically deletes // orphaned TAP devices on the host. Orphaned means: a hype-prefixed netdev whose -// instance ID does not correspond to any Running/Initializing/Paused/Unknown instance. +// instance ID is not in TAPPreserveIDs. // To avoid racing against in-flight CreateAllocation calls whose metadata hasn't // been persisted yet, only TAPs older than tapGCMinAge are considered. // The goroutine stops when ctx is cancelled. diff --git a/lib/instances/types.go b/lib/instances/types.go index db171e488..898d0a875 100644 --- a/lib/instances/types.go +++ b/lib/instances/types.go @@ -220,6 +220,7 @@ type Instance struct { HasSnapshot bool // Derived from filesystem check BootMarkersHydrated bool // True when missing boot markers were hydrated from logs in this read HealthCheckRuntime *healthcheck.Runtime + stopCleanupPending bool // stop/delete still owns the instance's host resources } // GetHypervisorType returns the hypervisor type as a string. diff --git a/lib/instances/update.go b/lib/instances/update.go index ca15bfd00..4e7435b37 100644 --- a/lib/instances/update.go +++ b/lib/instances/update.go @@ -49,6 +49,9 @@ func (m *manager) updateInstance(ctx context.Context, id string, req UpdateInsta } req.HealthCheck = normalizedHealthCheck if req.RestartPolicySet { + if pendingHealthCheckRestart(meta) { + return nil, fmt.Errorf("%w: cannot update restart policy during health-check restart recovery", ErrInvalidState) + } normalizedRestartPolicy, err := normalizeRestartPolicy(req.RestartPolicy) if err != nil { return nil, err diff --git a/lib/instances/vfio_lifecycle_linux_test.go b/lib/instances/vfio_lifecycle_linux_test.go index e21747b72..754fb25ac 100644 --- a/lib/instances/vfio_lifecycle_linux_test.go +++ b/lib/instances/vfio_lifecycle_linux_test.go @@ -66,6 +66,10 @@ func TestInterruptedVFIODeleteKeepsLegacySocketOwner(t *testing.T) { require.ErrorIs(t, m.DeleteInstance(ctx, id), context.Canceled) restarted := &manager{paths: m.paths, deviceManager: dev, lifecycleEvents: newLifecycleSubscribers()} + all, err := restarted.ListInstances(t.Context(), nil) + require.NoError(t, err) + assert.Contains(t, TAPPreserveIDs(all), id, "startup TAP cleanup must preserve the live owner's TAP") + assert.True(t, NewLivenessChecker(restarted).IsInstanceRunning(t.Context(), id), "startup PCI cleanup must preserve its attachment") require.ErrorIs(t, restarted.DeleteInstance(ctx, id), context.Canceled) require.Empty(t, dev.detached) require.DirExists(t, meta.DataDir) @@ -149,6 +153,8 @@ func TestStopRetryFinishesAfterVFIOGuestExits(t *testing.T) { inst, err := restarted.StopInstance(t.Context(), id, StopInstanceRequest{}) require.NoError(t, err) assert.Equal(t, StateStopped, inst.State) + assert.Empty(t, TAPPreserveIDs([]Instance{*inst})) + assert.False(t, NewLivenessChecker(restarted).IsInstanceRunning(t.Context(), id)) stored, err := m.loadMetadata(id) require.NoError(t, err) assert.NotNil(t, stored.StoppedAt) diff --git a/lib/restart-policy/README.md b/lib/restart-policy/README.md index 10356600d..4ecd55831 100644 --- a/lib/restart-policy/README.md +++ b/lib/restart-policy/README.md @@ -53,7 +53,7 @@ Health checks are a separate feature. They report workload health without changi When health status reaches `unhealthy`, restart policy treats that as a failure signal for `on_failure` and `always`. `never` still reports health without restarting. -Health-triggered restart uses the same attempt counter, backoff, max-attempt limit, manual-stop suppression, and stable-window reset as exit-triggered restart. If Hypeman restarts during a VFIO stop for a health check, the controller finishes cleanup and resumes the same attempt. An attempt already recorded as failed still observes its backoff or limit. +Health-triggered restart uses the same attempt counter, backoff, max-attempt limit, manual-stop suppression, and stable-window reset as exit-triggered restart. If Hypeman restarts during a VFIO stop for a health check, the controller finishes cleanup and uses the already-counted start, even if the stop was committed before the interruption. An attempt already recorded as failed still observes its backoff or limit. Updating the restart policy during this recovery returns `409 invalid_state`; retry after recovery or issue a manual stop to suppress the restart. ## Lifecycle Behavior