Files
Reims-Go/internal/app/vm_poll.go
T

449 lines
13 KiB
Go

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))
}
if svc := a.getInputService(); svc != nil {
var targets []host.IMETarget
for _, vm := range vms {
if pid := vm.RunningPID(); pid > 0 {
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)})
}
}
svc.SetTargets(targets)
}
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 != "" {
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)
}
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:
}
}