diff --git a/internal/app/affinity_flow.go b/internal/app/affinity_flow.go index 730de8c..3bdbab7 100644 --- a/internal/app/affinity_flow.go +++ b/internal/app/affinity_flow.go @@ -38,22 +38,10 @@ type VMAffinityStatus struct { func (a *App) findRunningVMPID(ctx context.Context, name string) int { if c, err := a.client(); err == nil { if vms, lerr := c.List(ctx); lerr == nil { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return runningPIDByName(vms, name) } } - a.mu.Lock() - defer a.mu.Unlock() - for _, vm := range a.lastVMs { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return a.cachedVMPID(name) } func buildVMAffinityStatus(detail driver.VMInfo, rep host.Report, globalAutoPin bool, pid int) VMAffinityStatus { @@ -133,7 +121,7 @@ func (a *App) SetVMAffinity(driverID, name string, req VMAffinityUpdate) (VMAffi if err != nil { return VMAffinityStatus{}, err } - if driver.IsHosted(vm.Capabilities) || (len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapAffinity)) { + if driver.IsHosted(vm.Capabilities) || !driver.SupportsCapability(vm.Capabilities, driver.CapAffinity) { return VMAffinityStatus{}, fmt.Errorf("CPU affinity is not available for %s", name) } if detail.Directory == "" { diff --git a/internal/app/app.go b/internal/app/app.go index 4bc5373..4a44fcd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "maps" "os" "path/filepath" "strings" @@ -333,446 +332,6 @@ func (a *App) shutdown(ctx context.Context) { releaseVMTyping("") } -// pollVMs refreshes the VM list every pollBusy while a VM is starting or -// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. -// Start, stop and delete call wakePoll so their result shows up at once. -const ( - pollBusy = 2 * time.Second - // Exits are caught at once by watchExits and GUI actions call wakePoll, so - // the steady tick only has to notice VMs started or removed elsewhere (CLI). - pollSteady = 10 * time.Second - // polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits - // above pollSteady so a poll that runs a little late still counts. - polledMaxAge = pollSteady + 3*time.Second -) - -func (a *App) pollVMs(ctx context.Context) { - timer := time.NewTimer(pollBusy) - defer timer.Stop() - // Cache static hybrid P-core mask once instead of querying host every tick. - a.mu.Lock() - initRoot := a.cfg.DataRoot - a.mu.Unlock() - cachedHost := host.Inspect(initRoot) - var lastSig string - pinnedPIDs := make(map[int]bool) - guideCheckedPIDs := make(map[int]bool) - lastGuideMgr := a.getInstallGuideManager() - exitWatched := make(map[int]bool) - - for { - select { - case <-ctx.Done(): - return - case <-timer.C: - case <-a.pollWake: - } - a.mu.Lock() - next := pollSteady - if len(a.transitions) > 0 { - next = pollBusy - } - a.mu.Unlock() - timer.Reset(next) - // reims-ctl keeps its state in the data folder; leave it alone until - // setup has chosen one, and while it is open read-only. - if !a.dataRootUsable() { - continue - } - vms, err := a.listVMsInternal(ctx) - if err != nil { - a.mu.Lock() - changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error() - a.lastVMListErr = err - if a.lastVMsAt.IsZero() && a.lastVMs == nil { - a.lastVMs = vms - } - a.lastVMsAt = time.Now() - a.mu.Unlock() - if changed { - a.emitStateChanged() - } - continue - } - a.syncComputerUseOwnership(vms) - // Only VMs whose process the host neither spawned (the broker watches - // those through their job) nor leaves to the driver (hosted) need a - // per-PID exit watcher. - procVMs := make([]driver.VMListItem, 0, len(vms)) - for _, vm := range vms { - if !driver.IsHosted(vm.Capabilities) && !a.brokerRunsVM(vm.DriverID, vm.Name) { - procVMs = append(procVMs, vm) - } - } - watchExits(ctx, procVMs, exitWatched, a.wakePoll) - type pinCandidate struct { - driverID string - name string - dir string - pid int - } - var toPin []pinCandidate - a.mu.Lock() - loc := a.cfg.Locale - autoPin := a.cfg.AutoPinPCores - tm := a.trayMgr - runningCount := 0 - var b strings.Builder - var imeTargets []host.IMETarget - for _, vm := range vms { - key := vmKeyForDriver(vm.DriverID, vm.Name) - if vm.State == "running" { - runningCount++ - // The remote IME bridge types through the macOS guest's tools. - if vm.PID != nil && *vm.PID > 0 && (driver.HasCapability(vm.Capabilities, driver.CapGuestTools) || len(vm.Capabilities) == 0) { - imeTargets = append(imeTargets, host.IMETarget{ - VMName: vm.Name, - VMDir: vm.Dir, - PID: uint32(*vm.PID), - }) - } - } - if tr, ok := a.transitions[key]; ok { - if (tr == "starting" && vm.State == "running") || - (tr == "stopping" && vm.State == "stopped") || - (tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) || - (tr == "resuming" && vm.State == "running") { - delete(a.transitions, key) - if vm.State == "stopped" { - delete(a.pendingChanges, key) - } - } - } - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] && - !driver.IsHosted(vm.Capabilities) && (driver.HasCapability(vm.Capabilities, driver.CapAffinity) || len(vm.Capabilities) == 0) { - pinnedPIDs[*vm.PID] = true - toPin = append(toPin, pinCandidate{driverID: vm.DriverID, name: vm.Name, dir: vm.Dir, pid: *vm.PID}) - } - fmt.Fprintf(&b, "%s:%s:%s:%s:%s:%s;", key, vm.State, a.transitions[key], vm.Phase, readyToken(vm.Ready), endpointSignature(vm.Endpoints)) - } - sig := b.String() - ib := a.imeBridge - liveVMs := make(map[string]struct{}, len(vms)) - for _, vm := range vms { - liveVMs[vmKeyForDriver(vm.DriverID, vm.Name)] = struct{}{} - } - removedVMs := make(map[string]struct{}) - for _, vm := range a.lastVMs { - key := vmKeyForDriver(vm.DriverID, vm.Name) - if _, ok := liveVMs[key]; !ok { - removedVMs[key] = struct{}{} - } - } - for name := range a.rebootWatchers { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - for name := range a.diskPaths { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - for name := range a.procSamples { - if _, ok := liveVMs[name]; !ok { - removedVMs[name] = struct{}{} - } - } - maps.DeleteFunc(a.diskPaths, func(name string, _ cachedDiskPath) bool { - _, ok := liveVMs[name] - return !ok - }) - maps.DeleteFunc(a.procSamples, func(name string, _ host.ProcessSample) bool { - _, ok := liveVMs[name] - return !ok - }) - var stoppedBridges []string - for _, prev := range a.lastVMs { - if prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID { - continue - } - key := vmKeyForDriver(prev.DriverID, prev.Name) - tr := a.transitions[key] - if tr == "starting" || tr == "resuming" { - continue - } - for _, cur := range vms { - if cur.DriverID == prev.DriverID && cur.Name == prev.Name && cur.State != "running" { - stoppedBridges = append(stoppedBridges, cur.Name) - break - } - } - } - gt := a.guestTools - a.lastVMs = append([]driver.VMListItem(nil), vms...) - a.lastVMsAt = time.Now() - listRecovered := a.lastVMListErr != nil - a.lastVMListErr = nil - a.mu.Unlock() - for _, vmName := range stoppedBridges { - a.stopPacketBridge(vmName) - if gt != nil { - gt.StopManagementNetwork(vmName) - } - } - prunePinnedPIDs(pinnedPIDs, vms) - prunePinnedPIDs(guideCheckedPIDs, vms) - guideMgr := a.getInstallGuideManager() - if guideMgr != lastGuideMgr { - clear(guideCheckedPIDs) - lastGuideMgr = guideMgr - } - runningPIDs := make(map[int]bool, len(vms)) - for _, vm := range vms { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - runningPIDs[*vm.PID] = true - } - } - guidesChanged := false - if guideMgr != nil { - guidesChanged = guideMgr.CancelStopped(runningPIDs) - } - for key := range removedVMs { - name := vmNameFromKey(key) - if ref, ok := driver.ParseVMRef(key); ok && ref.DriverID == driver.BuiltinReimsMacOSDriverID { - a.stopPacketBridge(name) - } - a.forgetComputerUseOwnedVM(key) - ref, parsed := driver.ParseVMRef(key) - // A disabled driver's VMs may leave the list without being deleted. - if parsed && a.driverFor(driver.VMInfo{DriverID: ref.DriverID}) != nil { - a.discardMaterializedSecretsForVM(key) - } - a.mu.Lock() - delete(a.transitions, key) - delete(a.pendingChanges, key) - a.mu.Unlock() - if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID { - // These helpers are keyed by bare name and belong to macOS VMs only. - stopVMMonitor(name) - releaseVMTyping(name) - releaseVMThumbnail(name) - } else { - releaseVMTypingForDriver(ref.DriverID, ref.Name) - releaseVMThumbnailForDriver(ref.DriverID, ref.Name) - } - if parsed { - a.stateTable().Delete(ref) - } - a.cancelRebootWatcherKey(key) - if gt != nil { - gt.UnregisterVM(key) - } - } - if ib != nil { - ib.SetTargets(imeTargets) - } - a.syncKeymapRules() - a.syncFullscreenHotkeyTargets() - if tm != nil { - effLoc := i18n.EffectiveLocale(loc) - if runningCount >= 1 { - tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount})) - } else { - tm.UpdateTooltip("Reims-Go") - } - } - shownDetails := make(map[string]driver.VMInfo, len(toPin)) - for _, cand := range toPin { - det, err := a.resolveVMInfo(cand.driverID, cand.name) - if err != nil { - // Retry boot discovery if the runtime was still starting. - delete(pinnedPIDs, cand.pid) - continue - } - vmDir := cand.dir - if vmDir == "" { - vmDir = det.Directory - } - if det.Directory == "" { - det.Directory = vmDir - } - shownDetails[vmKeyForDriver(cand.driverID, cand.name)] = det - if line, _ := a.applyVMAffinity(loc, cachedHost, driver.NewVMRef(cand.driverID, cand.name), vmDir, autoPin, cand.pid, det.CPUs, false); line != "" { - if driver.NewVMRef(cand.driverID, cand.name).DriverID == driver.BuiltinReimsMacOSDriverID { - a.emitLog(cand.name, line) - } else { - a.emitVMLogForDriver(cand.driverID, cand.name, line) - } - } - } - if guideMgr != nil { - for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { - continue - } - // The install guide belongs to the macOS installer flow. - if len(vm.Capabilities) > 0 && !driver.HasCapability(vm.Capabilities, driver.CapOpenCore) { - continue - } - pid := *vm.PID - if guideCheckedPIDs[pid] { - continue - } - det, ok := shownDetails[vmKeyForDriver(vm.DriverID, vm.Name)] - if !ok { - d, err := a.resolveVMInfo(vm.DriverID, vm.Name) - if err != nil { - continue - } - if d.Directory == "" { - d.Directory = vm.Dir - } - det = d - } - guideCheckedPIDs[pid] = true - if a.maybeStartInstallGuide(ctx, guideMgr, vm.Name, pid, det, loc) { - guidesChanged = true - } - } - } - if sig != lastSig || guidesChanged || listRecovered { - lastSig = sig - a.emitStateChanged() - } - } -} - -func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) { - a.mu.Lock() - svc := a.lifecycleSvc - a.mu.Unlock() - if svc != nil { - vms, err := svc.List(ctx) - out := make([]driver.VMListItem, 0, len(vms)) - for _, vm := range vms { - out = append(out, driver.VMListItem{ - Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State, - Capabilities: vm.Capabilities, GuestOS: vm.GuestOS, Phase: vm.Phase, Ready: vm.Ready, Endpoints: vm.Endpoints, - }) - } - return out, err - } - c, err := a.client() - if err != nil { - return nil, err - } - vms, err := c.List(ctx) - if err != nil { - return nil, err - } - for i := range vms { - vms[i].DriverID = driver.BuiltinReimsMacOSDriverID - } - enrichMacOSVMListStates(vms) - return vms, nil -} - -// 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 []driver.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) - } - } -} - -func prunePinnedPIDs(pinned map[int]bool, vms []driver.VMListItem) { - running := make(map[int]struct{}, len(vms)) - for _, vm := range vms { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - running[*vm.PID] = struct{}{} - } - } - for pid := range pinned { - if _, ok := running[pid]; !ok { - delete(pinned, 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. -func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) { - a.mu.Lock() - if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge { - vms := append([]driver.VMListItem(nil), a.lastVMs...) - err := a.lastVMListErr - a.mu.Unlock() - return vms, err - } - a.mu.Unlock() - return a.listVMsInternal(ctx) -} - -// polledVM looks name up in polledVMs. -func (a *App) polledVM(name string) (driver.VMListItem, bool) { - vms, err := a.polledVMs(context.Background()) - if err != nil { - return driver.VMListItem{}, false - } - for _, vm := range vms { - if vm.Name == name { - return vm, true - } - } - return driver.VMListItem{}, false -} - -func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { - vms, err := a.polledVMs(context.Background()) - if err != nil { - return driver.VMListItem{}, false - } - driverID = driver.CanonicalDriverID(driverID) - if driverID == "" { - driverID = driver.BuiltinReimsMacOSDriverID - } - for _, vm := range vms { - if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID { - return vm, true - } - } - return driver.VMListItem{}, false -} - -// wakePoll marks the polled list stale and runs pollVMs now. Call it after -// anything that changes which VMs exist or run. -func (a *App) wakePoll() { - a.mu.Lock() - a.lastVMsAt = time.Time{} - a.mu.Unlock() - select { - case a.pollWake <- struct{}{}: - default: - } -} - // cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for // diskPathTTL so GetVMStats doesn't run `show` every few seconds. type cachedDiskPath struct { diff --git a/internal/app/app_poll_test.go b/internal/app/app_poll_test.go index a1b80fd..32574e5 100644 --- a/internal/app/app_poll_test.go +++ b/internal/app/app_poll_test.go @@ -2,10 +2,13 @@ package app import ( "context" + "errors" "runtime" + "slices" "testing" "time" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/macos/reims" ) @@ -140,3 +143,39 @@ func TestCachedVMPID(t *testing.T) { t.Fatalf("cachedVMPID(missing-vm) = %d, want 0", got) } } + +func TestRecordVMListReportsWhatChanged(t *testing.T) { + mac := driver.BuiltinReimsMacOSDriverID + item := func(name, state string) driver.VMListItem { + return driver.VMListItem{DriverID: mac, Name: name, State: state} + } + key := func(name string) string { return vmKeyForDriver(mac, name) } + a := &App{ + lastVMs: []driver.VMListItem{item("gone", "running"), item("crashed", "running"), item("rebooting", "running"), item("kept", "running")}, + lastVMListErr: errors.New("reims-ctl failed"), + transitions: map[string]string{key("rebooting"): "starting", key("new"): "starting"}, + pendingChanges: map[string][]PendingChange{}, + diskPaths: map[string]cachedDiskPath{key("old-disk"): {}, key("kept"): {}}, + } + change := a.recordVMList([]driver.VMListItem{item("crashed", "stopped"), item("rebooting", "stopped"), item("kept", "running"), item("new", "running")}) + + if !change.recovered || a.lastVMListErr != nil { + t.Error("a good listing after a failed one must count as recovered") + } + if len(change.removed) != 2 { + t.Errorf("removed = %v, want gone and old-disk", change.removed) + } + if _, ok := a.diskPaths[key("old-disk")]; ok || len(a.diskPaths) != 1 { + t.Errorf("diskPaths = %v, want only kept", a.diskPaths) + } + // "rebooting" is down only because it is being started again. + if !slices.Equal(change.stoppedBridges, []string{"crashed"}) { + t.Errorf("stoppedBridges = %v, want crashed", change.stoppedBridges) + } + if _, ok := a.transitions[key("new")]; ok { + t.Error("a running VM must not stay in the starting transition") + } + if a.transitions[key("rebooting")] != "starting" { + t.Error("an unfinished transition must be kept") + } +} diff --git a/internal/app/console_router.go b/internal/app/console_router.go index 3d3f13e..cf3d4f3 100644 --- a/internal/app/console_router.go +++ b/internal/app/console_router.go @@ -49,7 +49,7 @@ func (a *App) resolveConsoleRoute(vm driver.VMInfo) (consoleRoute, error) { if cd, ok := driver.DriverServesConsole(a.driverFor(vm)); ok && driver.HasCapability(vm.Capabilities, driver.CapConsole) { return consoleRoute{kind: consoleRouteDriver, vm: vm, console: cd}, nil } - if !driver.IsHosted(vm.Capabilities) && (len(vm.Capabilities) == 0 || driver.HasCapability(vm.Capabilities, driver.CapQMP)) { + if !driver.IsHosted(vm.Capabilities) && driver.SupportsCapability(vm.Capabilities, driver.CapQMP) { return consoleRoute{kind: consoleRouteQMP, vm: vm}, nil } return consoleRoute{}, fmt.Errorf("computer_use_unavailable: driver %q has no console the host can reach", vm.DriverID) diff --git a/internal/app/fullscreen_hotkey_flow.go b/internal/app/fullscreen_hotkey_flow.go index ca59368..db07531 100644 --- a/internal/app/fullscreen_hotkey_flow.go +++ b/internal/app/fullscreen_hotkey_flow.go @@ -109,10 +109,11 @@ func (a *App) fullscreenHotkeyTargets(vms []driver.VMListItem, legacy bool, cach var targets []host.IMETarget support := make(map[fullscreenHotkeyVM]bool, len(cached)) for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + pid := vm.RunningPID() + if pid == 0 { continue } - target := host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(*vm.PID)} + target := host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)} key := fullscreenHotkeyVM{driverID: vm.DriverID, target: target} supported, known := cached[key] if !known { @@ -146,7 +147,7 @@ func (a *App) onFullscreenHotkey(target host.IMETarget, hwnd uintptr) { return } for _, vm := range a.lastVMs { - if vm.State != "running" || vm.Name != target.VMName || vm.Dir != target.VMDir || vm.PID == nil || *vm.PID != int(target.PID) { + if vm.Name != target.VMName || vm.Dir != target.VMDir || vm.RunningPID() == 0 || vm.RunningPID() != int(target.PID) { continue } a.mu.Unlock() diff --git a/internal/app/install_guide.go b/internal/app/install_guide.go index aff10fe..cf4db49 100644 --- a/internal/app/install_guide.go +++ b/internal/app/install_guide.go @@ -75,6 +75,59 @@ func installGuideKind(d reims.VMDetail) (installguide.Kind, bool) { return installguide.BuiltIn, startprep.ReadRecoveryMarker(d.Directory) == "on" } +// guideTracker follows the install guides of running VMs for the poll loop. +type guideTracker struct { + a *App + mgr *installguide.Manager // nil while the guide service is disabled + checked map[int]bool // PIDs already offered a guide by mgr +} + +func (a *App) newGuideTracker() *guideTracker { + return &guideTracker{a: a, mgr: a.getInstallGuideManager(), checked: make(map[int]bool)} +} + +// cancelStopped closes the guides of VMs that stopped and reports whether any +// did. A restarted guide service checks every running VM again. +func (t *guideTracker) cancelStopped(vms []driver.VMListItem) bool { + prunePinnedPIDs(t.checked, vms) + if mgr := t.a.getInstallGuideManager(); mgr != t.mgr { + clear(t.checked) + t.mgr = mgr + } + return t.mgr != nil && t.mgr.CancelStopped(runningPIDs(vms)) +} + +// startMissing opens the guide of running VMs that need one and reports +// whether any opened. details holds VM details already looked up, by VM key. +func (t *guideTracker) startMissing(ctx context.Context, vms []driver.VMListItem, details map[string]driver.VMInfo, loc i18n.Locale) bool { + if t.mgr == nil { + return false + } + started := false + for _, vm := range vms { + pid := vm.RunningPID() + // The install guide belongs to the macOS installer flow. + if pid == 0 || t.checked[pid] || !driver.SupportsCapability(vm.Capabilities, driver.CapOpenCore) { + continue + } + det, ok := details[vmKeyForDriver(vm.DriverID, vm.Name)] + if !ok { + var err error + if det, err = t.a.resolveVMInfo(vm.DriverID, vm.Name); err != nil { + continue + } + if det.Directory == "" { + det.Directory = vm.Dir + } + } + t.checked[pid] = true + if t.a.maybeStartInstallGuide(ctx, t.mgr, vm.Name, pid, det, loc) { + started = true + } + } + return started +} + func (a *App) maybeStartInstallGuide(ctx context.Context, gm *installguide.Manager, name string, pid int, vm driver.VMInfo, loc i18n.Locale) bool { if gm == nil || pid <= 0 || gm.HasActive(name, pid) { return false @@ -114,7 +167,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei return err } for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID == pid { + if vm.Name == name && vm.RunningPID() == pid { return ctx.Err() } } diff --git a/internal/app/keymap_flow.go b/internal/app/keymap_flow.go index 104083f..f15769d 100644 --- a/internal/app/keymap_flow.go +++ b/internal/app/keymap_flow.go @@ -118,7 +118,7 @@ func (a *App) syncKeymapRulesLocked() { var targets []host.IMETarget pids := make(map[string]int) for _, vm := range vms { - if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + if vm.RunningPID() == 0 { if srv != nil { srv.SetKeymapCarrier(vm.Name, false) } diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index bf63ee4..451d7ff 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -29,12 +29,7 @@ const ( func (a *App) cachedVMPID(name string) int { a.mu.Lock() defer a.mu.Unlock() - for _, vm := range a.lastVMs { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID - } - } - return 0 + return runningPIDByName(a.lastVMs, name) } func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) { diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go index 28c2708..5f184f5 100644 --- a/internal/app/vm_close_windows.go +++ b/internal/app/vm_close_windows.go @@ -12,16 +12,6 @@ import ( "github.com/Nwflower/reims-go/internal/tray" ) -// runningVMPID returns the process ID of the named VM when it is running. -func runningVMPID(vms []driver.VMListItem, name string) (uint32, bool) { - for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return uint32(*vm.PID), true - } - } - return 0, false -} - func (a *App) confirmVMWindowClose(name string) { if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { return @@ -66,7 +56,7 @@ func (a *App) confirmVMWindowClose(name string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error()) return } - if current, running := runningVMPID(vms, ref.Name); !running || current != uint32(pid) { + if current := runningPIDByName(vms, ref.Name); current == 0 || current != pid { return } if choice == host.VMCloseSuspend { diff --git a/internal/app/vm_monitor.go b/internal/app/vm_monitor.go index 94a4a82..91e8e84 100644 --- a/internal/app/vm_monitor.go +++ b/internal/app/vm_monitor.go @@ -197,10 +197,8 @@ func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) { } for _, vm := range vms { if vm.Name == name { - if vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - return *vm.PID, true - } - return 0, false + pid := vm.RunningPID() + return pid, pid > 0 } } return 0, false diff --git a/internal/app/vm_poll.go b/internal/app/vm_poll.go new file mode 100644 index 0000000..fc5667c --- /dev/null +++ b/internal/app/vm_poll.go @@ -0,0 +1,458 @@ +package app + +import ( + "context" + "fmt" + "maps" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" +) + +// pollVMs refreshes the VM list every pollBusy while a VM is starting or +// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. +// Start, stop and delete call wakePoll so their result shows up at once. +const ( + pollBusy = 2 * time.Second + // Exits are caught at once by watchExits and GUI actions call wakePoll, so + // the steady tick only has to notice VMs started or removed elsewhere (CLI). + pollSteady = 10 * time.Second + // polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits + // above pollSteady so a poll that runs a little late still counts. + polledMaxAge = pollSteady + 3*time.Second +) + +// vmPoller holds what the poll loop remembers between ticks. Only the loop +// touches it, so it needs no lock. +type vmPoller struct { + a *App + // host is inspected once: pinning only needs the static P-core mask. + host host.Report + lastSig string + pinned map[int]bool + exitWatched map[int]bool + guides *guideTracker +} + +func (a *App) pollVMs(ctx context.Context) { + timer := time.NewTimer(pollBusy) + defer timer.Stop() + a.mu.Lock() + root := a.cfg.DataRoot + a.mu.Unlock() + p := &vmPoller{ + a: a, + host: host.Inspect(root), + pinned: make(map[int]bool), + exitWatched: make(map[int]bool), + guides: a.newGuideTracker(), + } + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + case <-a.pollWake: + } + a.mu.Lock() + next := pollSteady + if len(a.transitions) > 0 { + next = pollBusy + } + a.mu.Unlock() + timer.Reset(next) + // reims-ctl keeps its state in the data folder; leave it alone until + // setup has chosen one, and while it is open read-only. + if a.dataRootUsable() { + p.tick(ctx) + } + } +} + +// tick lists the VMs once and brings everything that follows them up to date. +func (p *vmPoller) tick(ctx context.Context) { + a := p.a + vms, err := a.listVMsInternal(ctx) + if err != nil { + if a.recordVMListError(vms, err) { + a.emitStateChanged() + } + return + } + a.syncComputerUseOwnership(vms) + // Only VMs whose process the host neither spawned (the broker watches + // those through their job) nor leaves to the driver (hosted) need a + // per-PID exit watcher. + procVMs := make([]driver.VMListItem, 0, len(vms)) + for _, vm := range vms { + if !driver.IsHosted(vm.Capabilities) && !a.brokerRunsVM(vm.DriverID, vm.Name) { + procVMs = append(procVMs, vm) + } + } + watchExits(ctx, procVMs, p.exitWatched, a.wakePoll) + + change := a.recordVMList(vms) + a.mu.Lock() + loc := a.cfg.Locale + autoPin := a.cfg.AutoPinPCores + tm := a.trayMgr + ib := a.imeBridge + gt := a.guestTools + a.mu.Unlock() + + for _, name := range change.stoppedBridges { + a.stopPacketBridge(name) + if gt != nil { + gt.StopManagementNetwork(name) + } + } + prunePinnedPIDs(p.pinned, vms) + guidesChanged := p.guides.cancelStopped(vms) + for key := range change.removed { + a.forgetVM(key) + } + if ib != nil { + ib.SetTargets(imeTargets(vms)) + } + a.syncKeymapRules() + a.syncFullscreenHotkeyTargets() + if tm != nil { + tm.UpdateTooltip(trayTooltip(loc, vms)) + } + details := p.pinStarted(vms, loc, autoPin) + if p.guides.startMissing(ctx, vms, details, loc) { + guidesChanged = true + } + if change.signature != p.lastSig || guidesChanged || change.recovered { + p.lastSig = change.signature + a.emitStateChanged() + } +} + +// recordVMListError remembers a failed listing and reports whether the error +// is new. +func (a *App) recordVMListError(vms []driver.VMListItem, err error) bool { + a.mu.Lock() + defer a.mu.Unlock() + changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error() + a.lastVMListErr = err + if a.lastVMsAt.IsZero() && a.lastVMs == nil { + a.lastVMs = vms + } + a.lastVMsAt = time.Now() + return changed +} + +// vmListChange is how a listing differs from the one before it. +type vmListChange struct { + signature string // everything the UI shows about the VMs + removed map[string]struct{} // keys of VMs no longer listed + stoppedBridges []string // macOS VMs that stopped by themselves + recovered bool // the previous listing failed +} + +// recordVMList makes vms the current list and settles finished transitions. +func (a *App) recordVMList(vms []driver.VMListItem) vmListChange { + a.mu.Lock() + defer a.mu.Unlock() + change := vmListChange{removed: make(map[string]struct{}), recovered: a.lastVMListErr != nil} + live := make(map[string]driver.VMListItem, len(vms)) + var sig strings.Builder + for _, vm := range vms { + key := vmKeyForDriver(vm.DriverID, vm.Name) + live[key] = vm + if transitionDone(a.transitions[key], vm.State) { + delete(a.transitions, key) + if vm.State == "stopped" { + delete(a.pendingChanges, key) + } + } + fmt.Fprintf(&sig, "%s:%s:%s:%s:%s:%s;", key, vm.State, a.transitions[key], vm.Phase, readyToken(vm.Ready), endpointSignature(vm.Endpoints)) + } + change.signature = sig.String() + + // gone reports whether key is no longer listed, and notes it as removed. + gone := func(key string) bool { + if _, ok := live[key]; ok { + return false + } + change.removed[key] = struct{}{} + return true + } + for key := range a.rebootWatchers { + gone(key) + } + maps.DeleteFunc(a.diskPaths, func(key string, _ cachedDiskPath) bool { return gone(key) }) + maps.DeleteFunc(a.procSamples, func(key string, _ host.ProcessSample) bool { return gone(key) }) + for _, prev := range a.lastVMs { + key := vmKeyForDriver(prev.DriverID, prev.Name) + if gone(key) || prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID { + continue + } + if tr := a.transitions[key]; tr != "starting" && tr != "resuming" && live[key].State != "running" { + change.stoppedBridges = append(change.stoppedBridges, prev.Name) + } + } + a.lastVMs = append([]driver.VMListItem(nil), vms...) + a.lastVMsAt = time.Now() + a.lastVMListErr = nil + return change +} + +// transitionDone reports whether a VM now in state has finished transition. +func transitionDone(transition, state string) bool { + switch transition { + case "starting", "resuming": + return state == "running" + case "stopping": + return state == "stopped" + case "suspending": + return state == "suspended" || state == "stopped" + } + return false +} + +// forgetVM releases everything held for a VM that is no longer listed. +func (a *App) forgetVM(key string) { + name := vmNameFromKey(key) + ref, parsed := driver.ParseVMRef(key) + if parsed && ref.DriverID == driver.BuiltinReimsMacOSDriverID { + a.stopPacketBridge(name) + } + a.forgetComputerUseOwnedVM(key) + // A disabled driver's VMs may leave the list without being deleted. + if parsed && a.driverFor(driver.VMInfo{DriverID: ref.DriverID}) != nil { + a.discardMaterializedSecretsForVM(key) + } + a.mu.Lock() + delete(a.transitions, key) + delete(a.pendingChanges, key) + gt := a.guestTools + a.mu.Unlock() + if !parsed || ref.DriverID == driver.BuiltinReimsMacOSDriverID { + // These helpers are keyed by bare name and belong to macOS VMs only. + stopVMMonitor(name) + releaseVMTyping(name) + releaseVMThumbnail(name) + } else { + releaseVMTypingForDriver(ref.DriverID, ref.Name) + releaseVMThumbnailForDriver(ref.DriverID, ref.Name) + } + if parsed { + a.stateTable().Delete(ref) + } + a.cancelRebootWatcherKey(key) + if gt != nil { + gt.UnregisterVM(key) + } +} + +// imeTargets lists the running VMs the remote IME bridge can type into. It +// types through the macOS guest's tools. +func imeTargets(vms []driver.VMListItem) []host.IMETarget { + var targets []host.IMETarget + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 && driver.SupportsCapability(vm.Capabilities, driver.CapGuestTools) { + targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)}) + } + } + return targets +} + +func trayTooltip(loc i18n.Locale, vms []driver.VMListItem) string { + running := 0 + for _, vm := range vms { + if vm.State == "running" { + running++ + } + } + if running == 0 { + return "Reims-Go" + } + return i18n.M(i18n.EffectiveLocale(loc), "tray.running", i18n.Vars{"count": running}) +} + +// pinStarted applies the CPU affinity of VMs that started since the last tick. +// It returns the details it looked up, by VM key. +func (p *vmPoller) pinStarted(vms []driver.VMListItem, loc i18n.Locale, autoPin bool) map[string]driver.VMInfo { + details := make(map[string]driver.VMInfo) + for _, vm := range vms { + pid := vm.RunningPID() + if pid == 0 || p.pinned[pid] || driver.IsHosted(vm.Capabilities) || !driver.SupportsCapability(vm.Capabilities, driver.CapAffinity) { + continue + } + det, err := p.a.resolveVMInfo(vm.DriverID, vm.Name) + if err != nil { + // Try again next tick: the runtime may still be starting. + continue + } + p.pinned[pid] = true + vmDir := vm.Dir + if vmDir == "" { + vmDir = det.Directory + } + if det.Directory == "" { + det.Directory = vmDir + } + details[vmKeyForDriver(vm.DriverID, vm.Name)] = det + ref := driver.NewVMRef(vm.DriverID, vm.Name) + if line, _ := p.a.applyVMAffinity(loc, p.host, ref, vmDir, autoPin, pid, det.CPUs, false); line != "" { + if ref.DriverID == driver.BuiltinReimsMacOSDriverID { + p.a.emitLog(vm.Name, line) + } else { + p.a.emitVMLogForDriver(vm.DriverID, vm.Name, line) + } + } + } + return details +} + +func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + if svc != nil { + vms, err := svc.List(ctx) + out := make([]driver.VMListItem, 0, len(vms)) + for _, vm := range vms { + out = append(out, driver.VMListItem{ + Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State, + Capabilities: vm.Capabilities, GuestOS: vm.GuestOS, Phase: vm.Phase, Ready: vm.Ready, Endpoints: vm.Endpoints, + }) + } + return out, err + } + c, err := a.client() + if err != nil { + return nil, err + } + vms, err := c.List(ctx) + if err != nil { + return nil, err + } + for i := range vms { + vms[i].DriverID = driver.BuiltinReimsMacOSDriverID + } + enrichMacOSVMListStates(vms) + return vms, nil +} + +// 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 []driver.VMListItem, watched map[int]bool, onExit func()) { + running := make(map[int]bool, len(vms)) + for _, vm := range vms { + pid := vm.RunningPID() + if pid == 0 { + continue + } + 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) + } + } +} + +// runningPIDs is the set of process IDs of the running VMs. +func runningPIDs(vms []driver.VMListItem) map[int]bool { + running := make(map[int]bool, len(vms)) + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 { + running[pid] = true + } + } + return running +} + +// runningPIDByName is the process ID of the running VM called name, or 0. +func runningPIDByName(vms []driver.VMListItem, name string) int { + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 && vm.Name == name { + return pid + } + } + return 0 +} + +func prunePinnedPIDs(pinned map[int]bool, vms []driver.VMListItem) { + running := runningPIDs(vms) + maps.DeleteFunc(pinned, func(pid int, _ bool) bool { return !running[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. +func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) { + a.mu.Lock() + if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge { + vms := append([]driver.VMListItem(nil), a.lastVMs...) + err := a.lastVMListErr + a.mu.Unlock() + return vms, err + } + a.mu.Unlock() + return a.listVMsInternal(ctx) +} + +// polledVM looks name up in polledVMs. +func (a *App) polledVM(name string) (driver.VMListItem, bool) { + vms, err := a.polledVMs(context.Background()) + if err != nil { + return driver.VMListItem{}, false + } + for _, vm := range vms { + if vm.Name == name { + return vm, true + } + } + return driver.VMListItem{}, false +} + +func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { + vms, err := a.polledVMs(context.Background()) + if err != nil { + return driver.VMListItem{}, false + } + driverID = driver.CanonicalDriverID(driverID) + if driverID == "" { + driverID = driver.BuiltinReimsMacOSDriverID + } + for _, vm := range vms { + if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID { + return vm, true + } + } + return driver.VMListItem{}, false +} + +// wakePoll marks the polled list stale and runs pollVMs now. Call it after +// anything that changes which VMs exist or run. +func (a *App) wakePoll() { + a.mu.Lock() + a.lastVMsAt = time.Time{} + a.mu.Unlock() + select { + case a.pollWake <- struct{}{}: + default: + } +} diff --git a/internal/driver/driver.go b/internal/driver/driver.go index cc33f87..5052fc9 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -58,6 +58,12 @@ func HasCapability(caps []string, capability string) bool { return false } +// SupportsCapability is HasCapability for a listed VM. A list that carries no +// capabilities comes from reims-ctl, whose VMs support everything. +func SupportsCapability(caps []string, capability string) bool { + return len(caps) == 0 || HasCapability(caps, capability) +} + // IsHosted reports whether caps marks a driver-hosted VM. func IsHosted(caps []string) bool { return HasCapability(caps, CapHosted) } @@ -120,6 +126,15 @@ type VMListItem struct { Endpoints []VMEndpoint `json:"endpoints,omitempty"` } +// RunningPID is the VM's process ID, or 0 when it is not running or has no +// process on this host. +func (vm VMListItem) RunningPID() int { + if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + return 0 + } + return *vm.PID +} + // VMInfo is the generic cross-driver VM model (ยง5.3). type VMInfo struct { Name string `json:"name"`