diff --git a/app.go b/app.go index 3637802..f105c61 100644 --- a/app.go +++ b/app.go @@ -178,6 +178,7 @@ func (a *App) pollVMs(ctx context.Context) { cachedHost := host.Inspect(initRoot) var lastSig string pinnedPIDs := make(map[int]bool) + exitWatched := make(map[int]bool) for { select { @@ -197,6 +198,7 @@ func (a *App) pollVMs(ctx context.Context) { if err != nil { continue } + watchExits(ctx, vms, exitWatched, a.wakePoll) type pinCandidate struct { name string pid int @@ -290,6 +292,39 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { return c.List(ctx) } +// qemuImage is the executable reims-ctl reports as a running VM's PID. +const qemuImage = "qemu-system-x86_64.exe" + +// watchExits waits on every running VM's QEMU process not yet watched and +// calls onExit the moment one exits, so a VM that stops by itself (macOS shut +// down, QEMU quit or crashed) shows as stopped at once instead of at the next +// steady poll. watched holds the PIDs being waited on; PIDs no longer running +// are dropped so a reused PID is watched again. +func watchExits(ctx context.Context, vms []reims.VMListItem, watched map[int]bool, onExit func()) { + running := make(map[int]bool, len(vms)) + for _, vm := range vms { + if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + continue + } + pid := *vm.PID + running[pid] = true + if watched[pid] { + continue + } + watched[pid] = true + go func() { + if err := host.WaitProcessExit(ctx, uint32(pid), qemuImage); err == nil { + onExit() + } + }() + } + for pid := range watched { + if !running[pid] { + delete(watched, pid) + } + } +} + // polledVMs returns the list pollVMs saw last if it is at most polledMaxAge // old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn // their own `reims-ctl list`. A stale or missing poll falls back to one. diff --git a/app_poll_test.go b/app_poll_test.go index f189dbe..a639e93 100644 --- a/app_poll_test.go +++ b/app_poll_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "runtime" "testing" "time" @@ -29,6 +30,40 @@ func TestPolledVMsReusesFreshPoll(t *testing.T) { } } +func TestWatchExitsTracksRunningPIDs(t *testing.T) { + gone := 999999 // no such process: WaitProcessExit reports it exited at once + stopped := reims.VMListItem{Name: "m1", State: "stopped"} + running := reims.VMListItem{Name: "m0", State: "running", PID: &gone} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + exits := make(chan struct{}, 4) + watched := map[int]bool{} + watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} }) + watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() { exits <- struct{}{} }) + if len(watched) != 1 || !watched[gone] { + t.Fatalf("watched = %v, want only %d", watched, gone) + } + if runtime.GOOS == "windows" { + select { + case <-exits: + case <-time.After(3 * time.Second): + t.Fatal("onExit not called for an exited process") + } + select { + case <-exits: + t.Fatal("a PID already watched must not get a second waiter") + case <-time.After(300 * time.Millisecond): + } + } + + running.State = "stopped" + watchExits(ctx, []reims.VMListItem{running, stopped}, watched, func() {}) + if len(watched) != 0 { + t.Fatalf("watched = %v, want empty once the VM stopped", watched) + } +} + func TestWakePollMarksStaleAndWakesOnce(t *testing.T) { a := &App{pollWake: make(chan struct{}, 1)} a.lastVMsAt = time.Now() diff --git a/internal/host/procwait_other.go b/internal/host/procwait_other.go new file mode 100644 index 0000000..e8a1b08 --- /dev/null +++ b/internal/host/procwait_other.go @@ -0,0 +1,16 @@ +//go:build !windows + +package host + +import ( + "context" + "errors" +) + +// ErrOtherProcess: the PID now names a process other than the one expected. +var ErrOtherProcess = errors.New("pid belongs to another process") + +// WaitProcessExit is not implemented off Windows; callers fall back to polling. +func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error { + return errors.ErrUnsupported +} diff --git a/internal/host/procwait_windows.go b/internal/host/procwait_windows.go new file mode 100644 index 0000000..626677e --- /dev/null +++ b/internal/host/procwait_windows.go @@ -0,0 +1,78 @@ +//go:build windows + +package host + +import ( + "context" + "errors" + "fmt" + "strings" + "syscall" + "unsafe" +) + +var ( + procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject") + procQueryFullProcessImageNameW = kernel32.NewProc("QueryFullProcessImageNameW") +) + +const ( + processSynchronize = 0x00100000 + errorInvalidParameter syscall.Errno = 87 // ERROR_INVALID_PARAMETER: no process with that PID + waitObject0 = 0x00000000 + waitTimeoutCode = 0x00000102 + // waitSliceMs is how long one wait blocks before checking ctx; the exit + // itself is reported the moment it happens. + waitSliceMs = 1000 +) + +// ErrOtherProcess: the PID now names a process other than the one expected. +var ErrOtherProcess = errors.New("pid belongs to another process") + +// WaitProcessExit blocks until process pid exits and returns nil, or returns +// ctx.Err() once ctx ends. A process already gone counts as exited. When +// imageSuffix is set the process's image path must end with it (case +// insensitive), else ErrOtherProcess: a guard against a reused PID. +func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error { + if pid == 0 { + return errors.New("no pid") + } + h, _, err := procOpenProcess.Call(uintptr(processSynchronize|processQueryLimitedInfo), 0, uintptr(pid)) + if h == 0 { + if errno, ok := err.(syscall.Errno); ok && errno == errorInvalidParameter { + return nil // no such process: it has exited + } + return fmt.Errorf("open process %d: %w", pid, err) + } + defer procCloseHandle.Call(h) + + // An exited process another handle keeps alive opens fine but has no + // image name to read: settle that first. + if r, _, _ := procWaitForSingleObject.Call(h, 0); r == waitObject0 { + return nil + } + if imageSuffix != "" { + var buf [syscall.MAX_PATH * 2]uint16 + size := uint32(len(buf)) + if r, _, err := procQueryFullProcessImageNameW.Call(h, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))); r == 0 { + return fmt.Errorf("image name of process %d: %w", pid, err) + } + if !strings.HasSuffix(strings.ToLower(syscall.UTF16ToString(buf[:size])), strings.ToLower(imageSuffix)) { + return ErrOtherProcess + } + } + + for { + r, _, err := procWaitForSingleObject.Call(h, waitSliceMs) + switch r { + case waitObject0: + return nil + case waitTimeoutCode: + if ctx.Err() != nil { + return ctx.Err() + } + default: + return fmt.Errorf("wait for process %d: %w", pid, err) + } + } +} diff --git a/internal/host/procwait_windows_test.go b/internal/host/procwait_windows_test.go new file mode 100644 index 0000000..5551f5f --- /dev/null +++ b/internal/host/procwait_windows_test.go @@ -0,0 +1,77 @@ +//go:build windows + +package host + +import ( + "context" + "errors" + "os/exec" + "testing" + "time" +) + +func startPing(t *testing.T, pings string) *exec.Cmd { + t.Helper() + cmd := exec.Command("ping", "-n", pings, "127.0.0.1") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) + return cmd +} + +func TestWaitProcessExitReturnsWhenTheProcessEnds(t *testing.T) { + cmd := startPing(t, "30") + pid := uint32(cmd.Process.Pid) + done := make(chan error, 1) + go func() { done <- WaitProcessExit(context.Background(), pid, "ping.exe") }() + + time.Sleep(300 * time.Millisecond) + killedAt := time.Now() + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Fatalf("WaitProcessExit = %v", err) + } + // The exit is signalled, not found by the next wait slice. + if d := time.Since(killedAt); d > 500*time.Millisecond { + t.Fatalf("noticed the exit after %v", d) + } + case <-time.After(5 * time.Second): + t.Fatal("WaitProcessExit did not return after the process was killed") + } +} + +func TestWaitProcessExitStopsWithContext(t *testing.T) { + cmd := startPing(t, "30") + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + err := WaitProcessExit(ctx, uint32(cmd.Process.Pid), "") + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v, want deadline exceeded", err) + } +} + +func TestWaitProcessExitChecksTheImage(t *testing.T) { + cmd := startPing(t, "30") + err := WaitProcessExit(context.Background(), uint32(cmd.Process.Pid), "qemu-system-x86_64.exe") + if !errors.Is(err, ErrOtherProcess) { + t.Fatalf("err = %v, want ErrOtherProcess", err) + } +} + +func TestWaitProcessExitOnAGoneProcess(t *testing.T) { + cmd := exec.Command("cmd", "/c", "exit") + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + // Its PID is free (or, rarely, reused by something that is not ping). + if err := WaitProcessExit(ctx, uint32(cmd.Process.Pid), "ping.exe"); err != nil && !errors.Is(err, ErrOtherProcess) { + t.Fatalf("err = %v", err) + } +}