From 69803355bf3b9619067c06568c68f788d63e285c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sat, 28 Nov 2026 22:51:40 -0700 Subject: [PATCH] perf(shell): cut thumbnail cost and reims-ctl polling The VM page made the shell spawn about 84 reims-ctl processes a minute and pull a full 4K screendump every 5 s while a VM ran. - Scale reads *image.RGBA Pix directly: a 4K frame drops from ~80 ms and 8.3M allocations to ~10 ms and 2. - Thumbnails refresh every 15 s and skip the screendump while the VM's own window is in the foreground. - pollVMs polls every 2 s only while a VM starts or stops, else every 5 s; start, stop and delete wake it at once. - Stats, thumbnails and the heartbeat reuse the polled list instead of running their own `reims-ctl list`; the disk path from `show` is kept for a minute. Measured with two windows on the VM page: 67 -> 13 reims-ctl spawns a minute. Co-Authored-By: Claude Opus 5.5 --- app.go | 237 ++++++++++++++++++++-------- app_poll_test.go | 50 ++++++ frontend/src/components/VMPage.tsx | 7 +- internal/host/foreground_other.go | 6 + internal/host/foreground_windows.go | 17 ++ internal/thumb/thumb.go | 30 ++++ internal/thumb/thumb_test.go | 26 +++ stats_flow.go | 14 +- thumbnail_flow.go | 13 +- vm_monitor.go | 2 +- 10 files changed, 318 insertions(+), 84 deletions(-) create mode 100644 app_poll_test.go create mode 100644 internal/host/foreground_other.go create mode 100644 internal/host/foreground_windows.go diff --git a/app.go b/app.go index e4f9207..60b6de3 100644 --- a/app.go +++ b/app.go @@ -62,6 +62,9 @@ type App struct { trayMgr *tray.Manager allowQuit bool lastVMs []reims.VMListItem + lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale + pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick + diskPaths map[string]cachedDiskPath procSamples map[string]host.ProcessSample recentLogs []string needsSetup bool @@ -78,6 +81,8 @@ func NewApp() *App { transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), rebootWatchers: make(map[string]rebootWatcherEntry), + pollWake: make(chan struct{}, 1), + diskPaths: make(map[string]cachedDiskPath), procSamples: make(map[string]host.ProcessSample), } } @@ -148,9 +153,20 @@ func (a *App) shutdown(ctx context.Context) { } } +// 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 + pollSteady = 5 * 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) { - ticker := time.NewTicker(2 * time.Second) - defer ticker.Stop() + 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 @@ -163,81 +179,90 @@ func (a *App) pollVMs(ctx context.Context) { select { case <-ctx.Done(): return - case <-ticker.C: - vms, err := a.listVMsInternal(ctx) - if err != nil { - continue + case <-timer.C: + case <-a.pollWake: + } + a.mu.Lock() + next := pollSteady + if len(a.transitions) > 0 { + next = pollBusy + } + a.mu.Unlock() + timer.Reset(next) + vms, err := a.listVMsInternal(ctx) + if err != nil { + continue + } + type pinCandidate struct { + name string + pid int + } + var toPin []pinCandidate + a.mu.Lock() + loc := a.cfg.Locale + autoPin := a.cfg.AutoPinPCores + a.lastVMs = append([]reims.VMListItem(nil), vms...) + a.lastVMsAt = time.Now() + tm := a.trayMgr + runningCount := 0 + var b strings.Builder + var imeTargets []host.IMETarget + for _, vm := range vms { + if vm.State == "running" { + runningCount++ + if vm.PID != nil && *vm.PID > 0 { + imeTargets = append(imeTargets, host.IMETarget{ + VMName: vm.Name, + VMDir: vm.Dir, + PID: uint32(*vm.PID), + }) + } } - type pinCandidate struct { - name string - pid int - } - var toPin []pinCandidate - a.mu.Lock() - loc := a.cfg.Locale - autoPin := a.cfg.AutoPinPCores - a.lastVMs = append([]reims.VMListItem(nil), vms...) - tm := a.trayMgr - runningCount := 0 - var b strings.Builder - var imeTargets []host.IMETarget - for _, vm := range vms { - if vm.State == "running" { - runningCount++ - if vm.PID != nil && *vm.PID > 0 { - imeTargets = append(imeTargets, host.IMETarget{ - VMName: vm.Name, - VMDir: vm.Dir, - PID: uint32(*vm.PID), - }) + if tr, ok := a.transitions[vm.Name]; ok { + if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") { + delete(a.transitions, vm.Name) + if vm.State == "stopped" { + delete(a.pendingChanges, vm.Name) } } - if tr, ok := a.transitions[vm.Name]; ok { - if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") { - delete(a.transitions, vm.Name) - if vm.State == "stopped" { - delete(a.pendingChanges, vm.Name) - } - } - } - if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] { - if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 { - pinnedPIDs[*vm.PID] = true - toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID}) - } - } - fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name]) } - sig := b.String() - ib := a.imeBridge - a.mu.Unlock() - if ib != nil { - ib.SetTargets(imeTargets) + if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] { + if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 { + pinnedPIDs[*vm.PID] = true + toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID}) + } } - if tm != nil { - if runningCount > 0 { - if loc == i18n.ZhCN { - tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount)) - } else { - tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount)) - } + fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name]) + } + sig := b.String() + ib := a.imeBridge + a.mu.Unlock() + if ib != nil { + ib.SetTargets(imeTargets) + } + if tm != nil { + if runningCount > 0 { + if loc == i18n.ZhCN { + tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount)) } else { - tm.UpdateTooltip("Reims-Go") + tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount)) + } + } else { + tm.UpdateTooltip("Reims-Go") + } + } + for _, cand := range toPin { + vmCPUs := 0 + if c, cerr := a.client(); cerr == nil { + if det, derr := c.Show(ctx, cand.name); derr == nil { + vmCPUs = det.CPUs } } - for _, cand := range toPin { - vmCPUs := 0 - if c, cerr := a.client(); cerr == nil { - if det, derr := c.Show(ctx, cand.name); derr == nil { - vmCPUs = det.CPUs - } - } - a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs)) - } - if sig != lastSig { - lastSig = sig - wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) - } + a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs)) + } + if sig != lastSig { + lastSig = sig + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) } } } @@ -261,6 +286,76 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { return c.List(ctx) } +// 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) ([]reims.VMListItem, error) { + a.mu.Lock() + if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge { + vms := append([]reims.VMListItem(nil), a.lastVMs...) + a.mu.Unlock() + return vms, nil + } + a.mu.Unlock() + return a.listVMsInternal(ctx) +} + +// polledVM looks name up in polledVMs. +func (a *App) polledVM(name string) (reims.VMListItem, bool) { + vms, err := a.polledVMs(context.Background()) + if err != nil { + return reims.VMListItem{}, false + } + for _, vm := range vms { + if vm.Name == name { + return vm, true + } + } + return reims.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 { + path string + at time.Time +} + +const diskPathTTL = time.Minute + +// vmDiskPath resolves name's disk image path, reusing a recent answer. The +// path only changes through `reims-ctl set`, so at worst the disk-usage +// figure follows such a change a minute late. +func (a *App) vmDiskPath(ctx context.Context, c *reims.Client, name string) string { + a.mu.Lock() + cur, ok := a.diskPaths[name] + a.mu.Unlock() + if ok && time.Since(cur.at) < diskPathTTL { + return cur.path + } + d, err := c.Show(ctx, name) + if err != nil { + return "" + } + path := resolveVMDiskPath(d) + a.mu.Lock() + a.diskPaths[name] = cachedDiskPath{path: path, at: time.Now()} + a.mu.Unlock() + return path +} + func (a *App) emitLog(source, line string) { redacted := reims.RedactLogLine(line) ts := time.Now().Format("15:04:05") @@ -777,6 +872,7 @@ func (a *App) StartVM(name string) error { a.watchWin10ColdReboot(name, qmpAddr) } a.startVMMonitor(name, curDetail, startAt) + a.wakePoll() wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) return nil } @@ -810,6 +906,7 @@ func (a *App) StopVM(name string, force bool) error { a.mu.Lock() delete(a.pendingChanges, name) a.mu.Unlock() + a.wakePoll() wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) return nil } @@ -853,7 +950,9 @@ func (a *App) DeleteVM(name string, keepFiles bool) error { a.mu.Lock() delete(a.pendingChanges, name) delete(a.transitions, name) + delete(a.diskPaths, name) a.mu.Unlock() + a.wakePoll() wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) return nil } diff --git a/app_poll_test.go b/app_poll_test.go new file mode 100644 index 0000000..f189dbe --- /dev/null +++ b/app_poll_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "context" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" +) + +func TestPolledVMsReusesFreshPoll(t *testing.T) { + pid := 42 + a := &App{pollWake: make(chan struct{}, 1)} + a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}} + a.lastVMsAt = time.Now() + + vm, ok := a.polledVM("m0") + if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 { + t.Fatalf("polledVM = %+v, %v", vm, ok) + } + if _, ok := a.polledVM("missing"); ok { + t.Fatal("unknown VM should not be found") + } + + vms, _ := a.polledVMs(context.Background()) + vms[0].State = "stopped" + if a.lastVMs[0].State != "running" { + t.Fatal("polledVMs must return a copy, not the cached slice") + } +} + +func TestWakePollMarksStaleAndWakesOnce(t *testing.T) { + a := &App{pollWake: make(chan struct{}, 1)} + a.lastVMsAt = time.Now() + a.wakePoll() + a.wakePoll() // a second wake while one is pending must not block + if !a.lastVMsAt.IsZero() { + t.Fatal("wakePoll should mark the polled list stale") + } + select { + case <-a.pollWake: + default: + t.Fatal("wakePoll should signal pollVMs") + } + select { + case <-a.pollWake: + t.Fatal("pending wakes should coalesce into one") + default: + } +} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 7fb0eb5..3864fd0 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -83,8 +83,9 @@ export const VMPage: React.FC = ({ const running = state === 'running' const transitioning = state === 'starting' || state === 'stopping' - // Screen thumbnail (thumbnail_flow.go): a fresh frame every 5 s while the VM - // runs, otherwise the last frame saved. Skipped while the window is hidden. + // Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM + // runs, otherwise the last frame saved. Skipped while this window is hidden; + // the backend also skips it while the VM's own window is in front. const [thumb, setThumb] = useState(null) useEffect(() => { setThumb(null) }, [name]) useEffect(() => { @@ -94,7 +95,7 @@ export const VMPage: React.FC = ({ api.GetVMThumbnail(name).then((t) => { if (live && t.data_url) setThumb(t) }).catch(() => {}) } pull() - const timer = running ? window.setInterval(pull, 5000) : undefined + const timer = running ? window.setInterval(pull, 15000) : undefined return () => { live = false; if (timer) window.clearInterval(timer) } }, [name, running]) diff --git a/internal/host/foreground_other.go b/internal/host/foreground_other.go new file mode 100644 index 0000000..f896c14 --- /dev/null +++ b/internal/host/foreground_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package host + +// ForegroundPID is not implemented off Windows and always reports no owner. +func ForegroundPID() uint32 { return 0 } diff --git a/internal/host/foreground_windows.go b/internal/host/foreground_windows.go new file mode 100644 index 0000000..4acde18 --- /dev/null +++ b/internal/host/foreground_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package host + +import "unsafe" + +// ForegroundPID returns the process that owns the foreground window, or 0 +// when there is none (locked screen, desktop focused). +func ForegroundPID() uint32 { + hwnd, _, _ := procGetForegroundWindow.Call() + if hwnd == 0 { + return 0 + } + var pid uint32 + _, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) + return pid +} diff --git a/internal/thumb/thumb.go b/internal/thumb/thumb.go index 1324933..a91827d 100644 --- a/internal/thumb/thumb.go +++ b/internal/thumb/thumb.go @@ -98,6 +98,10 @@ func Scale(img image.Image, maxW int) image.Image { dh = 1 } dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) + if src, ok := img.(*image.RGBA); ok { + scaleRGBA(dst, src, sw, sh, dw, dh) + return dst + } for y := 0; y < dh; y++ { y0, y1 := y*sh/dh, (y+1)*sh/dh for x := 0; x < dw; x++ { @@ -118,6 +122,32 @@ func Scale(img image.Image, maxW int) image.Image { return dst } +// scaleRGBA is Scale's box filter for *image.RGBA, the type decodePPM +// returns. It reads Pix directly: going through img.At boxes every pixel +// in an interface, which for a 4K frame is about 8 million allocations. +func scaleRGBA(dst, src *image.RGBA, sw, sh, dw, dh int) { + for y := 0; y < dh; y++ { + y0, y1 := y*sh/dh, (y+1)*sh/dh + drow := dst.Pix[y*dst.Stride:] + for x := 0; x < dw; x++ { + x0, x1 := x*sw/dw, (x+1)*sw/dw + var r, g, bl, n uint32 + for sy := y0; sy < y1; sy++ { + row := src.Pix[sy*src.Stride+x0*4 : sy*src.Stride+x1*4] + for i := 0; i < len(row); i += 4 { + r, g, bl = r+uint32(row[i]), g+uint32(row[i+1]), bl+uint32(row[i+2]) + } + n += uint32(x1 - x0) + } + if n == 0 { + n = 1 + } + d := drow[x*4 : x*4+4] + d[0], d[1], d[2], d[3] = uint8(r/n), uint8(g/n), uint8(bl/n), 255 + } + } +} + // Blank reports whether a frame is (almost) one flat colour — a powered-off // or not-yet-drawn console — so the UI can keep its placeholder instead. func Blank(img image.Image) bool { diff --git a/internal/thumb/thumb_test.go b/internal/thumb/thumb_test.go index 4bd9fa8..7ae19e1 100644 --- a/internal/thumb/thumb_test.go +++ b/internal/thumb/thumb_test.go @@ -53,6 +53,32 @@ func TestScaleKeepsAspect(t *testing.T) { } } +// opaqueImage hides the *image.RGBA type so Scale takes its generic path. +type opaqueImage struct{ image.Image } + +func TestScaleRGBAMatchesGenericPath(t *testing.T) { + img := image.NewRGBA(image.Rect(0, 0, 1931, 1087)) // odd sizes: uneven boxes + for i := range img.Pix { + img.Pix[i] = byte(i*7 + i/4) + if i%4 == 3 { + img.Pix[i] = 255 + } + } + fast := Scale(img, 640).(*image.RGBA) + slow := Scale(opaqueImage{img}, 640).(*image.RGBA) + if !bytes.Equal(fast.Pix, slow.Pix) { + t.Fatal("RGBA fast path differs from the generic box filter") + } +} + +func BenchmarkScale4K(b *testing.B) { + img := image.NewRGBA(image.Rect(0, 0, 3840, 2160)) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + Scale(img, 640) + } +} + func TestBlank(t *testing.T) { flat := image.NewRGBA(image.Rect(0, 0, 200, 100)) if !Blank(flat) { diff --git a/stats_flow.go b/stats_flow.go index 65a4977..16eae34 100644 --- a/stats_flow.go +++ b/stats_flow.go @@ -57,7 +57,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) { return stats, err } ctx := context.Background() - vms, _ := c.List(ctx) + vms, _ := a.polledVMs(ctx) var pid int for _, vm := range vms { if vm.Name == name { @@ -70,13 +70,11 @@ func (a *App) GetVMStats(name string) (VMStats, error) { } stats.PID = pid - if d, err := c.Show(ctx, name); err == nil { - if diskPath := resolveVMDiskPath(d); diskPath != "" { - if du, err := host.InspectDiskUsage(diskPath); err == nil { - stats.DiskActualBytes = du.ActualBytes - stats.DiskVirtualBytes = du.VirtualBytes - stats.DiskFormat = du.Format - } + if diskPath := a.vmDiskPath(ctx, c, name); diskPath != "" { + if du, err := host.InspectDiskUsage(diskPath); err == nil { + stats.DiskActualBytes = du.ActualBytes + stats.DiskVirtualBytes = du.VirtualBytes + stats.DiskFormat = du.Format } } diff --git a/thumbnail_flow.go b/thumbnail_flow.go index be4049d..b4af98a 100644 --- a/thumbnail_flow.go +++ b/thumbnail_flow.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/thumb" ) @@ -59,8 +60,14 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) { if busy { return VMThumbnail{}, false } - d, err := a.GetVMDetail(name) - if err != nil || d.State != "running" || d.Directory == "" { + vm, ok := a.polledVM(name) + if !ok || vm.State != "running" || vm.Dir == "" { + return VMThumbnail{}, false + } + // The user is looking at the VM window itself, not this page: skip the + // screendump, which runs on QEMU's main loop and writes a full-size frame + // (about 25 MB at 4K) to disk. + if vm.PID != nil && *vm.PID > 0 && host.ForegroundPID() == uint32(*vm.PID) { return VMThumbnail{}, false } a.mu.Lock() @@ -74,7 +81,7 @@ func (a *App) captureThumb(name, path string) (VMThumbnail, bool) { ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) defer cancel() - format, err := qmp.ScreendumpVM(ctx, d.Directory, raw) + format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw) if err != nil { return VMThumbnail{}, false } diff --git a/vm_monitor.go b/vm_monitor.go index de0b3b4..8b8089a 100644 --- a/vm_monitor.go +++ b/vm_monitor.go @@ -187,7 +187,7 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti } func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) { - vms, err := a.listVMsInternal(ctx) + vms, err := a.polledVMs(ctx) if err != nil { return 0, true // keep watching on transient error }