* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation * feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129) Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM. * feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion. * feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes * fix(app,host,macos,ui): address PR #134 automated review findings - Frontend & i18n: - Fix UTF-8/GBK mojibake in VMPage.tsx. - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure. - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable. - App / Sessions / Confirm / Lifecycle: - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits. - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization. - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session. - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts. - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing. - Host Takeover Hooks: - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures. - macOS Provisioning & Autoinstall Engine: - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures. - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints. - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages. * fix(app,cli,host,macos,ui): address PR #134 second automated review findings - CLI & Desktop Control Channel: - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners. - Merge live runners with on-disk checkpoints when listing status without a VM argument. - App Sessions, Confirmations, Downloads & Telemetry: - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted. - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling. - Revoke protected-phase grants when a VM disappears from poll results. - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback. - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors. - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots. - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV. - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging. - Host Takeover & Guest Tools: - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed. - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall. - macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner): - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry. - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush. - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified). - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds. - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O. - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit. - Frontend: - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs. * fix(app,cli,host,macos,ui): address PR #134 third automated review findings Addresses all confirmed findings from Review #6204465334 (commit d516350) with targeted regression tests and hardens verified COM vtable bindings: - App & Session Lifecycle: - Track hostPaused separately in agentSession so plugin host/session.update (paused_for_user=false) cannot clear physical user takeover or explicit PauseAgentSession holds; only host ResumeAgentSession or timed takeover expiry clears them. - Give each auto-install session watcher a monotonic watchGen + cancelable child context so restarting/resuming auto-install on the same VM cancels any superseded watcher and prevents stale timeout or secret cleanup. - Bound fast 500ms unbound-PID discovery for running VMs to sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind). - Keep non-blocking buffered confirm resolution send inside confirmMu for clear mutual exclusion with cancelPendingConfirmations. - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return and StartVM-failure paths in watchColdReboot. - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving install_guest_tools) whenever VM is stopped instead of reusing stale images. - CLI & macOS Provisioning / StartPrep: - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the VM is running or paused. - Guard live "/" root in postinstall against macOS Recovery/Installer (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope chmod 644 strictly to com.apple.keyboardtype.plist. - Reject unknown -* options in REIMSHELP/install.sh (including after --erase). - Defer clearing the one-shot REIMSPROV staged marker until after setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed. - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when checkpoint is already at StepDesktop. - Host Input & Session Overlay: - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED) in locked-input mode consistently with the mouse hook. - Clean up exited overlay entries in entry.run() and recreate dead entries on Manager.Upsert when CreateWindowExW fails or exits early. - Cache the static island base surface (shell + icons + DirectWrite text) and measured text metrics across breathing frames, raising timerBreathMs to 100ms. - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h / dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite rendering smoke test. - Autoinstall OCR, Rules, Watchdog & Runner: - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/ before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate whitelisted basenames in offline zip imports. - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait + channel wakeup in Recognize so Close() immediately cancels in-flight OCR. - Fall back to installed RapidOCR when WinOCR initialization fails in Open(), and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe. - Pause instead of pressing Return when post-TypeSecret login screenshot fails. - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume. - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word boundaries for short names (<4 runes) in RedactDiagnosticText, and honor rule verify.wait_change_ms with early exit on visual frame diff. * fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
694 lines
17 KiB
Go
694 lines
17 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:
|
|
}
|
|
}
|
|
|
|
type telemetryMilestone struct {
|
|
Key string `json:"key"`
|
|
Count int `json:"count"`
|
|
At string `json:"at"`
|
|
}
|
|
|
|
type vmTelemetryState struct {
|
|
milestones map[string]telemetryMilestone
|
|
qemuErrors []string
|
|
diskBytes int64
|
|
diskDeltaBytes int64
|
|
cpuPercent float64
|
|
coldRebootCount int
|
|
preserveNextBoot bool
|
|
updatedAt time.Time
|
|
}
|
|
|
|
func (a *App) ensureTelemetryLocked(key string) *vmTelemetryState {
|
|
if a.vmTelemetry == nil {
|
|
a.vmTelemetry = map[string]*vmTelemetryState{}
|
|
}
|
|
st := a.vmTelemetry[key]
|
|
if st == nil {
|
|
st = &vmTelemetryState{
|
|
milestones: map[string]telemetryMilestone{},
|
|
cpuPercent: -1,
|
|
}
|
|
a.vmTelemetry[key] = st
|
|
}
|
|
return st
|
|
}
|
|
|
|
func (a *App) recordTelemetryMilestone(key, milestoneKey string) {
|
|
if key == "" || milestoneKey == "" {
|
|
return
|
|
}
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
prev := st.milestones[milestoneKey]
|
|
prev.Key = milestoneKey
|
|
prev.Count++
|
|
prev.At = now
|
|
st.milestones[milestoneKey] = prev
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) recordTelemetryQemuError(key, line string) {
|
|
if key == "" || strings.TrimSpace(line) == "" {
|
|
return
|
|
}
|
|
redacted := host.RedactText(strings.TrimSpace(line))
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
st.qemuErrors = append(st.qemuErrors, redacted)
|
|
if len(st.qemuErrors) > 32 {
|
|
st.qemuErrors = st.qemuErrors[len(st.qemuErrors)-32:]
|
|
}
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) recordTelemetrySample(key string, diskBytes, diskDelta int64, cpuPct float64) {
|
|
if key == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
st.diskBytes = diskBytes
|
|
st.diskDeltaBytes = diskDelta
|
|
st.cpuPercent = cpuPct
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) recordTelemetryColdReboot(key string) {
|
|
if key == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
st.coldRebootCount++
|
|
st.preserveNextBoot = true
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) clearTelemetryColdRebootPreserve(key string) {
|
|
if key == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
if st := a.vmTelemetry[key]; st != nil {
|
|
st.preserveNextBoot = false
|
|
}
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) clearTelemetryMilestone(key, milestoneKey string) {
|
|
if key == "" || milestoneKey == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
if st := a.vmTelemetry[key]; st != nil && st.milestones != nil {
|
|
delete(st.milestones, milestoneKey)
|
|
st.updatedAt = time.Now()
|
|
}
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) resetTelemetryForBoot(key, vmDir string) {
|
|
if key == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
preserve := st.preserveNextBoot
|
|
st.preserveNextBoot = false
|
|
if !preserve {
|
|
prevReady, hadReady := st.milestones["serial:provision_ready"]
|
|
st.milestones = map[string]telemetryMilestone{}
|
|
if a.hasProvisionReadyMarker(vmDir) {
|
|
if !hadReady {
|
|
prevReady = telemetryMilestone{
|
|
Key: "serial:provision_ready",
|
|
Count: 1,
|
|
At: time.Now().UTC().Format(time.RFC3339),
|
|
}
|
|
}
|
|
st.milestones["serial:provision_ready"] = prevReady
|
|
}
|
|
st.qemuErrors = nil
|
|
} else if a.hasProvisionReadyMarker(vmDir) {
|
|
if _, hadReady := st.milestones["serial:provision_ready"]; !hadReady {
|
|
st.milestones["serial:provision_ready"] = telemetryMilestone{
|
|
Key: "serial:provision_ready",
|
|
Count: 1,
|
|
At: time.Now().UTC().Format(time.RFC3339),
|
|
}
|
|
}
|
|
}
|
|
st.diskDeltaBytes = 0
|
|
st.cpuPercent = -1
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
func (a *App) preserveTelemetryForResume(key, vmDir string) {
|
|
if key == "" {
|
|
return
|
|
}
|
|
a.telemetryMu.Lock()
|
|
st := a.ensureTelemetryLocked(key)
|
|
st.preserveNextBoot = false
|
|
if a.hasProvisionReadyMarker(vmDir) {
|
|
if _, hadReady := st.milestones["serial:provision_ready"]; !hadReady {
|
|
st.milestones["serial:provision_ready"] = telemetryMilestone{
|
|
Key: "serial:provision_ready",
|
|
Count: 1,
|
|
At: time.Now().UTC().Format(time.RFC3339),
|
|
}
|
|
}
|
|
}
|
|
st.diskDeltaBytes = 0
|
|
st.cpuPercent = -1
|
|
st.updatedAt = time.Now()
|
|
a.telemetryMu.Unlock()
|
|
}
|
|
|
|
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) {
|
|
a.startVMMonitorWithReset(name, detail, startAt, true)
|
|
}
|
|
|
|
func (a *App) resumeVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
|
|
a.startVMMonitorWithReset(name, detail, startAt, false)
|
|
}
|
|
|
|
func (a *App) startVMMonitorWithReset(name string, detail driver.VMInfo, startAt time.Time, resetTelemetry bool) {
|
|
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")
|
|
tKey := detail.Ref().Key()
|
|
if resetTelemetry {
|
|
a.resetTelemetryForBoot(tKey, detail.Directory)
|
|
} else {
|
|
a.preserveTelemetryForResume(tKey, detail.Directory)
|
|
}
|
|
|
|
// 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{}
|
|
var lastXNURecordedAt time.Time
|
|
xnuRecordedForBoot := false
|
|
|
|
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 != "" {
|
|
recordMilestone := true
|
|
switch key {
|
|
case "serial:boot":
|
|
xnuRecordedForBoot = false
|
|
case "serial:xnu":
|
|
// OpenCore/boot.efi logs both "#[EB|LOG:HANDOFF TO XNU]" and
|
|
// "End of efiboot serial output" milliseconds apart for one boot.
|
|
now := time.Now()
|
|
if xnuRecordedForBoot && now.Sub(lastXNURecordedAt) < 10*time.Second {
|
|
recordMilestone = false
|
|
} else {
|
|
xnuRecordedForBoot = true
|
|
lastXNURecordedAt = now
|
|
}
|
|
}
|
|
if recordMilestone {
|
|
a.recordTelemetryMilestone(tKey, key)
|
|
}
|
|
if !seenEvents[key] {
|
|
seenEvents[key] = true
|
|
a.emitVMLog(name, msg)
|
|
if key == "serial:provision_ready" {
|
|
a.writeProvisionReadyMarker(detail.Directory)
|
|
a.emitStateChangedEvent()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for _, line := range qemu.read(qemuPath) {
|
|
a.emitPluginLogLine(name, "qemu", line)
|
|
if key, msg := parseQemuMilestone(loc, line); msg != "" {
|
|
if key != "" {
|
|
a.recordTelemetryMilestone(tKey, key)
|
|
} else if strings.HasPrefix(msg, "[QEMU] ") {
|
|
a.recordTelemetryQemuError(tKey, strings.TrimPrefix(msg, "[QEMU] "))
|
|
}
|
|
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
|
|
}
|
|
a.recordTelemetrySample(tKey, diskNow, diskDelta, cpuPct)
|
|
|
|
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 (a *App) provisionReadyVMKeys() []string {
|
|
seen := map[string]bool{}
|
|
var out []string
|
|
a.telemetryMu.Lock()
|
|
for k, st := range a.vmTelemetry {
|
|
if st == nil {
|
|
continue
|
|
}
|
|
if _, ok := st.milestones["serial:provision_ready"]; ok && !seen[k] {
|
|
seen[k] = true
|
|
out = append(out, k)
|
|
}
|
|
}
|
|
a.telemetryMu.Unlock()
|
|
|
|
a.mu.Lock()
|
|
vms := append([]driver.VMListItem(nil), a.lastVMs...)
|
|
a.mu.Unlock()
|
|
for _, vm := range vms {
|
|
if vm.Dir == "" {
|
|
continue
|
|
}
|
|
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
|
if !seen[key] && a.hasProvisionReadyMarker(vm.Dir) {
|
|
seen[key] = true
|
|
out = append(out, key)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
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")
|
|
case strings.Contains(line, "REIMS_PROVISION_BOOT_OK"):
|
|
return "serial:provision_ready", i18n.T(loc, "monitor.serial.provision_ready")
|
|
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,
|
|
}))
|
|
}
|