Files
Reims-Go/internal/app/vm_monitor.go
千川白浪 aac3979373 refactor: 收敛根目录布局并统一资源与脚本归属 (#203)
* refactor: 收敛根目录布局并统一资源与脚本归属

* fix: 停止监视器时等待显示定位协程退出
2026-12-05 06:34:01 -07:00

445 lines
11 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]vmMonitorEntry
}{
entries: map[string]vmMonitorEntry{},
}
type vmMonitorEntry struct {
id uint64
cancel context.CancelFunc
done chan struct{}
}
var (
vmMonitorStopTimeout = 5 * time.Second
vmMonitorPollTimeout = 5 * time.Second
)
func waitVMMonitorDone(done <-chan struct{}) {
if done == nil {
return
}
timeout := vmMonitorStopTimeout
if timeout <= 0 {
<-done
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
case <-timer.C:
}
}
func stopVMMonitor(name string) {
vmMonitors.mu.Lock()
cur, ok := vmMonitors.entries[name]
if ok {
cur.cancel()
}
vmMonitors.mu.Unlock()
if ok {
waitVMMonitorDone(cur.done)
}
}
func stopAllVMMonitors() {
vmMonitors.mu.Lock()
waiters := make([]chan struct{}, 0, len(vmMonitors.entries))
for _, cur := range vmMonitors.entries {
cur.cancel()
if cur.done != nil {
waiters = append(waiters, cur.done)
}
}
vmMonitors.mu.Unlock()
timeout := vmMonitorStopTimeout
if timeout <= 0 {
for _, done := range waiters {
<-done
}
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
for _, done := range waiters {
select {
case <-done:
case <-timer.C:
return
}
}
}
func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
if detail.Directory == "" {
stopVMMonitor(name)
return
}
ctx, cancel := context.WithCancel(a.baseCtx())
done := make(chan struct{})
var prevDone chan struct{}
var displayWG sync.WaitGroup
needsDisplayPosition := vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != ""
if needsDisplayPosition {
displayWG.Add(1)
}
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
prevDone = cur.done
}
vmMonitors.seq++
myID := vmMonitors.seq
vmMonitors.entries[name] = vmMonitorEntry{id: myID, cancel: cancel, done: done}
vmMonitors.mu.Unlock()
if prevDone != nil {
waitVMMonitorDone(prevDone)
}
if needsDisplayPosition {
go func() {
defer displayWG.Done()
positionCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
a.positionVMDisplayOnStart(positionCtx, detail, ticker.C, func(ctx context.Context) (int, error) {
return a.displayVMPID(ctx, detail.Ref())
})
}()
}
go func() {
defer func() {
cancel()
displayWG.Wait()
vmMonitors.mu.Lock()
close(done)
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()
hbCtx, hbCancel := context.WithTimeout(ctx, vmMonitorPollTimeout)
pid, running := a.currentVMPID(hbCtx, name)
hbCancel()
if ctx.Err() != nil {
return
}
if !running {
a.emitVMLog(name, i18n.T(loc, "monitor.exited"))
return
}
if pid <= 0 {
continue
}
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 {
pid := vm.RunningPID()
return pid, pid > 0
}
}
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) {
cfg := a.runtimeConfig()
rtCommit := cfg.ActiveRuntime
loc := i18n.EffectiveLocale(cfg.Locale)
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, cfg.AutoPinPCores, 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,
}))
}