Files
Reims-Go/internal/app/macos_lifecycle_native.go
千川白浪 107a8d73e0 refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 (#200)
* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积

* fix: preserve download recovery and bound PBZX decoding

Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
2026-12-05 20:54:41 +08:00

219 lines
5.8 KiB
Go

package app
import (
"context"
"errors"
"fmt"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart"
)
const (
vmExitWaitTimeout = 12 * time.Second
vmMemoryReclaimWaitTimeout = 15 * time.Second
)
func (a *App) cachedVMPID(name string) int {
a.mu.Lock()
defer a.mu.Unlock()
return runningPIDByName(a.lastVMs, name)
}
func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) {
if pid <= 0 || timeout <= 0 {
return
}
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
_ = host.WaitProcessExit(waitCtx, uint32(pid), qemuImage)
}
func (a *App) waitForCommitMemoryReclaim(ctx context.Context, c *reims.Client, name, logPrefix string) {
if ctx.Err() != nil || c == nil {
return
}
detail, err := c.Show(ctx, name)
if err != nil || detail.Memory == "" {
return
}
vmstart.WaitForCommitMemory(ctx, detail.Memory, vmMemoryReclaimWaitTimeout, func(availGB, neededGB float64) {
a.emitVMLog(name, fmt.Sprintf("%s: waiting for Windows to release VM memory (available %.1f GB, need %.1f GB)...", logPrefix, availGB, neededGB))
})
}
func (a *App) cancelRebootWatcher(name string) { a.cancelRebootWatcherKey(vmKey(name)) }
func (a *App) cancelRebootWatcherKey(key string) {
a.mu.Lock()
if entry, ok := a.rebootWatchers[key]; ok {
entry.cancel()
delete(a.rebootWatchers, key)
}
a.mu.Unlock()
}
func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
a.cancelRebootWatcher(name)
baseCtx := a.ctx
if baseCtx == nil {
baseCtx = context.Background()
}
watchCtx, cancel := context.WithCancel(baseCtx)
a.mu.Lock()
a.nextWatcherID++
myID := a.nextWatcherID
a.rebootWatchers[vmKey(name)] = rebootWatcherEntry{id: myID, cancel: cancel}
a.mu.Unlock()
go func() {
defer func() {
cancel()
a.mu.Lock()
if cur, ok := a.rebootWatchers[vmKey(name)]; ok && cur.id == myID {
delete(a.rebootWatchers, vmKey(name))
}
a.mu.Unlock()
}()
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
if err != nil {
if watchCtx.Err() == nil {
a.emitVMLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
}
return
}
if reason != "guest-reset" {
if reason != "" {
a.emitVMLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
}
return
}
a.mu.Lock()
tr := a.transitions[vmKey(name)]
a.mu.Unlock()
if tr == "stopping" || tr == "suspending" {
return
}
a.emitVMLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
oldPID := a.cachedVMPID(name)
c, err := a.client()
if err != nil {
a.emitVMLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
return
}
// Wait for QEMU to finish exiting cleanly under -no-reboot. Wait on the
// OS process handle when known so we don't race against QEMU teardown
// even if `reims-ctl list` reports stopped early.
deadline := time.Now().Add(vmExitWaitTimeout)
waitedPID := 0
if oldPID > 0 {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
}
for time.Now().Before(deadline) {
if watchCtx.Err() != nil {
return
}
vms, err := c.List(watchCtx)
if err == nil {
stopped := false
for _, vm := range vms {
if vm.Name != name {
continue
}
if vm.PID != nil && *vm.PID > 0 && oldPID == 0 {
oldPID = *vm.PID
}
if vm.State == "stopped" {
stopped = true
}
break
}
if stopped {
break
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
continue
}
}
select {
case <-watchCtx.Done():
return
case <-time.After(300 * time.Millisecond):
}
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
}
if watchCtx.Err() != nil {
return
}
a.waitForCommitMemoryReclaim(watchCtx, c, name, "Win10 WHPX cold-reboot")
if watchCtx.Err() != nil {
return
}
if err := a.StartVM(driver.BuiltinReimsMacOSDriverID, name); err != nil {
a.emitVMLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
}
}()
}
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
// process and its committed memory to go away before starting again.
func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) {
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
if err != nil {
return false, err
}
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
stopped, err = a.restartMacOSVMLocked(operationCtx, name)
return err
})
return stopped, err
}
func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bool, err error) {
oldPID := a.cachedVMPID(name)
if err := a.stopVM(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
return false, err
}
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
if c, err := a.client(); err == nil {
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
}
if err := ctx.Err(); err != nil {
return true, err
}
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return true, errors.New("driver lifecycle is not initialized")
}
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
if err != nil {
return true, err
}
return true, a.startResolvedVMLocked(ctx, svc, vm)
}
// OpenVMFolder shows the VM's directory in File Explorer.
func (a *App) OpenVMFolder(name string) error {
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
return host.OpenFolder(d.Directory)
}