Files
Reims-Go/internal/app/vm_monitor.go
T
Nwflower c1b33c9c4f refactor(app): isolate native macOS adapters
Route generic App and CLI code through lifecycle and driver models. Move native macOS detail, create, settings and legacy flows into explicit files, share progress and redaction through host, and enforce the boundary with a file-scoped architecture ratchet.
2026-11-30 11:18:09 -07:00

375 lines
9.7 KiB
Go

package app
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// vmMonitors holds per-VM background log tailers & boot/install heartbeats.
var vmMonitors = struct {
mu sync.Mutex
seq uint64
entries map[string]struct {
id uint64
cancel context.CancelFunc
}
}{
entries: map[string]struct {
id uint64
cancel context.CancelFunc
}{},
}
func stopVMMonitor(name string) {
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
}
func stopAllVMMonitors() {
vmMonitors.mu.Lock()
for name, cur := range vmMonitors.entries {
cur.cancel()
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
}
func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
if detail.Directory == "" {
stopVMMonitor(name)
return
}
ctx, cancel := context.WithCancel(a.baseCtx())
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
}
vmMonitors.seq++
myID := vmMonitors.seq
vmMonitors.entries[name] = struct {
id uint64
cancel context.CancelFunc
}{id: myID, cancel: cancel}
vmMonitors.mu.Unlock()
go func() {
defer func() {
cancel()
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID {
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
}()
serialPath := filepath.Join(detail.Directory, "logs", "serial.log")
qemuPath := filepath.Join(detail.Directory, "logs", "qemu.log")
diskPath := filepath.Join(detail.Directory, "disk.qcow2")
// Only read logs belonging to this boot (ignore files last touched before StartVM).
serial := logTail{offset: initialLogOffset(serialPath, startAt)}
qemu := logTail{offset: initialLogOffset(qemuPath, startAt)}
seenEvents := map[string]bool{}
lastDiskSize := fileSizeBytes(diskPath)
var lastCPU time.Duration
var hasLastCPU bool
lastSampleAt := time.Now()
idleStreak := 0
stallWarned := false
logTicker := time.NewTicker(1500 * time.Millisecond)
hbTicker := time.NewTicker(30 * time.Second)
defer logTicker.Stop()
defer hbTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-logTicker.C:
loc := a.locale()
for _, line := range serial.read(serialPath) {
a.emitPluginLogLine(name, "serial", line)
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
seenEvents[key] = true
a.emitVMLog(name, msg)
}
}
for _, line := range qemu.read(qemuPath) {
a.emitPluginLogLine(name, "qemu", line)
if key, msg := parseQemuMilestone(loc, line); msg != "" {
if key != "" && seenEvents[key] {
continue
}
if key != "" {
seenEvents[key] = true
}
a.emitVMLog(name, msg)
}
}
case <-hbTicker.C:
loc := a.locale()
pid, running := a.currentVMPID(ctx, name)
if !running {
a.emitVMLog(name, i18n.T(loc, "monitor.exited"))
return
}
now := time.Now()
dt := now.Sub(lastSampleAt).Seconds()
if dt <= 0 {
dt = 30
}
lastSampleAt = now
diskNow := fileSizeBytes(diskPath)
diskDelta := diskNow - lastDiskSize
if diskDelta < 0 {
diskDelta = 0
}
lastDiskSize = diskNow
cpuPct := -1.0
if cpuNow, ok := host.ProcessCPUTime(uint32(pid)); ok {
if hasLastCPU && cpuNow >= lastCPU {
cpuPct = (cpuNow - lastCPU).Seconds() / dt * 100
}
lastCPU = cpuNow
hasLastCPU = true
}
elapsed := time.Since(startAt)
inEarlyOrInstall := vmInfoBool(detail, "has_installer") || elapsed < 15*time.Minute
if !inEarlyOrInstall {
continue
}
if diskDelta < 64*1024 && cpuPct >= 0 && cpuPct < 3.0 {
idleStreak++
} else {
idleStreak = 0
stallWarned = false
}
if msg := formatBootHeartbeat(loc, elapsed, diskNow, diskDelta, cpuPct); msg != "" {
a.emitVMLog(name, msg)
}
if idleStreak >= 3 && !stallWarned {
stallWarned = true
a.emitVMLog(name, i18n.T(loc, "monitor.stall_warn"))
}
}
}
}()
}
func (a *App) currentVMPID(ctx context.Context, name string) (int, bool) {
vms, err := a.polledVMs(ctx)
if err != nil {
return 0, true // keep watching on transient error
}
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
}
}
return 0, false
}
func initialLogOffset(path string, startAt time.Time) int64 {
info, err := os.Stat(path)
if err != nil {
return 0
}
// If the log file has not been rotated/modified since before StartVM, start at its end.
if info.ModTime().Before(startAt.Add(-500 * time.Millisecond)) {
return info.Size()
}
return 0
}
const maxMonitorLine = 64 << 10
type logTail struct {
offset int64
partial string
skipping bool // an oversized line continues into the next read
}
func (t *logTail) read(path string) []string {
f, err := os.Open(path)
if err != nil {
return nil
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil
}
// Log rotated or recreated (e.g., new boot overwrote serial.log / qemu.log).
if info.Size() < t.offset {
*t = logTail{}
}
if info.Size() == t.offset {
return nil
}
const maxChunk = 256 * 1024
data := make([]byte, min(info.Size()-t.offset, maxChunk))
n, err := f.ReadAt(data, t.offset)
if (err != nil && err != io.EOF) || n == 0 {
return nil
}
t.offset += int64(n)
var lines []string
for rest := string(data[:n]); rest != ""; {
line, after, complete := strings.Cut(rest, "\n")
rest = after
if t.skipping || len(t.partial)+len(line) > maxMonitorLine {
t.partial = ""
t.skipping = !complete
continue
}
if !complete {
t.partial = strings.Clone(t.partial + line)
break
}
if s := strings.TrimSpace(t.partial + line); s != "" {
lines = append(lines, s)
}
t.partial = ""
}
return lines
}
func parseSerialMilestone(loc i18n.Locale, line string) (key, msg string) {
switch {
case strings.Contains(line, "BdsDxe: starting Boot"):
return "serial:boot", i18n.T(loc, "monitor.serial.boot")
case strings.Contains(line, "#[EB|LOG:HANDOFF TO XNU]"), strings.Contains(line, "End of efiboot serial output"):
return "serial:xnu", i18n.T(loc, "monitor.serial.xnu")
default:
return "", ""
}
}
func parseQemuMilestone(loc i18n.Locale, line string) (key, msg string) {
// Skip verbose periodic rt-diag stat dumps.
if strings.Contains(line, "rt-diag") || strings.Contains(line, "rt-presents") {
return "", ""
}
if idx := strings.Index(line, "the rt platform's device: "); idx >= 0 {
rest := line[idx+len("the rt platform's device: "):]
if semi := strings.IndexByte(rest, ';'); semi >= 0 {
rest = rest[:semi]
}
return "qemu:gpu", i18n.M(loc, "monitor.qemu.gpu", i18n.Vars{"device": strings.TrimSpace(rest)})
}
if strings.Contains(line, "windows open through SDL") {
return "qemu:window", i18n.T(loc, "monitor.qemu.window")
}
if strings.Contains(line, "the device was reset") {
return "qemu:reset", i18n.T(loc, "monitor.qemu.reset")
}
if strings.Contains(line, "the control completion ring is full") {
return "qemu:ring-full", i18n.T(loc, "monitor.qemu.ring_full")
}
// Known benign WHPX advisories: keep out of the activity log so they don't look like errors.
if strings.Contains(line, "no pre-fault of the pool") ||
strings.Contains(line, "refuses the TSC deadline timer") {
return "qemu:benign", ""
}
low := strings.ToLower(line)
if strings.Contains(line, "WHPX:") ||
strings.Contains(line, " ERROR ") ||
strings.Contains(low, "error:") ||
strings.Contains(low, "fatal:") ||
strings.Contains(low, "failed to ") {
return "", "[QEMU] " + line
}
return "", ""
}
func formatBootHeartbeat(loc i18n.Locale, elapsed time.Duration, diskBytes, diskDelta int64, cpuPct float64) string {
dur := fmt.Sprintf("%dm%02ds", int(elapsed.Minutes()), int(elapsed.Seconds())%60)
diskStr := i18n.FormatNumber(loc, float64(diskBytes)/(1024*1024*1024), 2) + " GB"
deltaStr := ""
if diskDelta >= 1024*1024 {
deltaStr = " (+" + i18n.FormatNumber(loc, float64(diskDelta)/(1024*1024), 1) + " MB)"
}
if cpuPct >= 0 {
return i18n.M(loc, "monitor.heartbeat.cpu", i18n.Vars{
"dur": dur,
"disk": diskStr,
"delta": deltaStr,
"cpu": cpuPct,
})
}
return i18n.M(loc, "monitor.heartbeat.nocpu", i18n.Vars{
"dur": dur,
"disk": diskStr,
"delta": deltaStr,
})
}
func fileSizeBytes(path string) int64 {
info, err := os.Stat(path)
if err != nil {
return 0
}
return info.Size()
}
func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Report, qmpAddr string) {
a.mu.Lock()
rawLoc := a.cfg.Locale
rtCommit := a.cfg.ActiveRuntime
pinPCores := a.cfg.AutoPinPCores
a.mu.Unlock()
loc := i18n.EffectiveLocale(rawLoc)
if rtCommit == "" {
rtCommit = "auto"
}
irqMode := "default"
lowExtra := strings.ToLower(vmInfoString(detail, "extra_args"))
switch {
case strings.Contains(lowExtra, "kernel-irqchip=off"):
irqMode = "off"
case strings.Contains(lowExtra, "kernel-irqchip=on"):
irqMode = "on"
}
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
coldStr := i18n.T(loc, "monitor.start.off")
if qmpAddr != "" {
coldStr = i18n.T(loc, "monitor.start.on")
}
a.emitVMLog(name, i18n.M(loc, "monitor.start.summary", i18n.Vars{
"rt": rtCommit,
"cpus": detail.CPUs,
"mem": detail.Memory,
"avail": rep.CommitAvailGB,
"gfx": vmInfoString(detail, "graphics"),
"disk": strings.ToUpper(vmInfoString(detail, "disk_controller")),
"irq": irqMode,
"pin": pinStr,
"cold": coldStr,
}))
}