Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/devices/GPU.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,22 @@ 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.
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.

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.
Expand Down
27 changes: 13 additions & 14 deletions lib/hypervisor/qemu/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -296,23 +295,24 @@ 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 {
// 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()
releaseVMMState(proc.socketPath)
}
Expand Down Expand Up @@ -398,11 +398,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()
Expand Down
82 changes: 56 additions & 26 deletions lib/hypervisor/qemu/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -479,40 +480,69 @@ 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")

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')
require.NoError(t, err)
proc.termGrace = 50 * time.Millisecond
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)
}

proc.cleanup()
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")
}

assert.ErrorIs(t, syscall.Kill(proc.pid, 0), syscall.ESRCH, "SIGTERM-ignoring process must still be hard-killed")
require.NoFileExists(t, socketPath)
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)
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")
}
60 changes: 58 additions & 2 deletions lib/hypervisor/vfio.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,63 @@
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 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, 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 {
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 {
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 !canEscalate {
return false, context.DeadlineExceeded
}
return false, nil
}
if waitForExit(min(remaining, 200*time.Millisecond)) {
return true, nil
}
}
}
85 changes: 85 additions & 0 deletions lib/hypervisor/vfio_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
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
wantErr error
}{
{"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) {
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, 4*time.Second, func(d time.Duration) bool {
time.Sleep(d)
return false
})
require.ErrorIs(t, err, tc.wantErr)
require.False(t, exited)
require.Equal(t, tc.wantWait, time.Since(start))
})
})
}
}

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()
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))
})
}
5 changes: 4 additions & 1 deletion lib/instances/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
Expand Down
12 changes: 9 additions & 3 deletions lib/instances/fork.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down Expand Up @@ -566,7 +569,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
Expand Down
Loading
Loading