fix(shell): notice a VM that stops by itself at once

When macOS shut down or QEMU quit on its own, reims-go had issued no
stop, so it only saw the VM stopped at its next steady poll, up to 5 s
later. Now pollVMs waits on each running QEMU process handle and wakes
the poll the moment the process exits; a PID is only waited on while it
names qemu-system-x86_64.exe, so a reused PID is not mistaken for the VM.

Measured with macos-tahoe and QMP quit: the window got the state change
51 ms after QEMU exited. Off Windows the steady poll remains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
千川白浪andClaude Opus 5.5 committed 2026-11-29 00:14:37 -07:00
1 parent 181ad64618
commit 12fa25d089
5 files changed
+241

No files matched your search

+35
View File
@@ -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.
+35
View File
@@ -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()
+16
View File
@@ -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
}
+78
View File
@@ -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)
}
}
}
+77
View File
@@ -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)
}
}