683 lines
21 KiB
Go
683 lines
21 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"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/macos/guest"
|
|
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
|
"github.com/Nwflower/reims-go/internal/networkmsg"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
|
"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())
|
|
}
|
|
}()
|
|
}
|
|
|
|
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
|
|
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
|
|
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
|
|
// produce duplicate QEMU device IDs on upgrade.
|
|
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
|
s := reims.StripGuestToolsArgs(extraArgs)
|
|
s = reims.StripPacketBridgeArgs(s)
|
|
s = reims.StripGuestToolsNetworkArgs(s)
|
|
s = reims.StripOfflineHelperArgs(s)
|
|
s = qmp.StripLegacyWin10RebootArgs(s)
|
|
s = reims.StripIncomingDeferArgs(s)
|
|
return strings.TrimSpace(s)
|
|
}
|
|
|
|
func (a *App) startMacOSVM(name string) error {
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
prep, err := a.prep(name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := prep.Client
|
|
a.mu.Lock()
|
|
root := a.cfg.DataRoot
|
|
tmpDir := a.cfg.TempDir()
|
|
locale := a.cfg.Locale
|
|
a.mu.Unlock()
|
|
rep := host.Inspect(root)
|
|
if err := prep.CheckWHPX(rep); err != nil {
|
|
a.emitVMLog(name, "Start refused: "+err.Error())
|
|
return err
|
|
}
|
|
curDetail, release, err := startprep.LockVM(context.Background(), c, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
unlock := sync.OnceFunc(release)
|
|
defer unlock()
|
|
if err := prepareLegacyColdStart(context.Background(), c.Locale, name, tmpDir, curDetail, func(line string) {
|
|
a.emitVMLog(name, line)
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if releaseNet != nil {
|
|
defer releaseNet()
|
|
}
|
|
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
|
|
a.emitVMLog(name, "Start refused: "+err.Error())
|
|
return err
|
|
}
|
|
a.cancelRebootWatcher(name)
|
|
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
var qmpAddr string
|
|
if mgr != nil {
|
|
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
|
|
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
|
|
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
|
|
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
|
|
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
|
VMName: name,
|
|
VMSettingsKey: driver.NewVMRef(builtin.IDDriverReimsMacOS, name).Key(),
|
|
VMDir: curDetail.Directory,
|
|
DriverID: builtin.IDDriverReimsMacOS,
|
|
ExtraArgs: curDetail.ExtraArgs,
|
|
HasInstaller: curDetail.HasInstaller,
|
|
InstallerPath: curDetail.InstallerPath,
|
|
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
|
|
RuntimeCaps: rtCaps,
|
|
HostFacts: buildHostFacts(rep, rtCaps),
|
|
VMCaps: macosdriver.ReimsMacOSCapabilities,
|
|
State: curDetail.State,
|
|
})
|
|
if blockErr != nil {
|
|
a.emitVMLog(name, "Start blocked: "+blockErr.Error())
|
|
return blockErr
|
|
}
|
|
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
|
|
if ledgerErr != nil {
|
|
a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
|
|
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
|
}
|
|
// Reassign macOS-owned fragments from legacy builtin.core records to
|
|
// builtin.guest.macos before reconciling.
|
|
guest.MigrateLedger(ledger)
|
|
// Strip pre-ledger or out-of-band managed fragments so upgrading existing
|
|
// VMs never duplicates QEMU device IDs.
|
|
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
|
|
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
|
|
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep)
|
|
reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested))
|
|
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
|
|
for _, warn := range reconciled.Warnings {
|
|
a.emitVMLog(name, "[plugin] "+warn)
|
|
}
|
|
if len(reconciled.Env) > 0 {
|
|
c.Env = append(c.Env, reconciled.Env...)
|
|
}
|
|
if reconciled.Changed {
|
|
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
|
a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
|
|
} else {
|
|
curDetail.ExtraArgs = reconciled.ExtraArgs
|
|
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
|
}
|
|
} else {
|
|
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
|
|
}
|
|
for _, act := range reconciled.PostStart {
|
|
if act.Kind == "qmp.watch_cold_reboot" {
|
|
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
|
|
qmpAddr = addr
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil {
|
|
return err
|
|
}
|
|
a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name))
|
|
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
|
if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 {
|
|
c.Env = append(c.Env, env...)
|
|
}
|
|
}
|
|
if prep.Runtime.Manifest.HasCapability("window-file-drop") {
|
|
c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...)
|
|
}
|
|
prep.Prepare(context.Background(), name, rep, &curDetail)
|
|
if rep.NeedsColdRebootWorkaround {
|
|
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
|
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
|
_ = os.Remove(sockPath)
|
|
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
|
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
|
a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
|
} else {
|
|
qmpAddr = "unix:" + sockPath
|
|
curDetail.ExtraArgs = merged
|
|
}
|
|
}
|
|
ledger, err := plugin.LoadArgLedger(curDetail.Directory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS}
|
|
macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep)
|
|
reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested})
|
|
for _, warning := range reconciled.Warnings {
|
|
a.emitVMLog(name, warning)
|
|
}
|
|
if reconciled.Changed {
|
|
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
|
return err
|
|
}
|
|
if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil {
|
|
return err
|
|
}
|
|
curDetail.ExtraArgs = reconciled.ExtraArgs
|
|
}
|
|
}
|
|
|
|
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
|
|
vmstart.UsesFixedGuestMode(curDetail.Directory, rep.Displays, curDetail.Borderless, curDetail.Resolution) {
|
|
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
|
}
|
|
if prep.Runtime.Manifest.HasCapability("client-window-close") {
|
|
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
|
|
}
|
|
|
|
a.mu.Lock()
|
|
a.transitions[vmKey(name)] = "starting"
|
|
delete(a.pendingChanges, vmKey(name))
|
|
a.mu.Unlock()
|
|
a.emitStateChanged()
|
|
|
|
startAt := time.Now()
|
|
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
a.emitVMLog(name, "Starting "+name+"...")
|
|
err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
|
a.emitVMLog(name, msg)
|
|
})
|
|
unlock()
|
|
if err != nil {
|
|
a.mu.Lock()
|
|
delete(a.transitions, vmKey(name))
|
|
a.mu.Unlock()
|
|
a.emitVMLog(name, "Start error: "+err.Error())
|
|
a.emitStateChanged()
|
|
return err
|
|
}
|
|
if qmpAddr != "" && mgr == nil {
|
|
a.watchWin10ColdReboot(name, qmpAddr)
|
|
}
|
|
if mgr != nil {
|
|
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
|
VMName: name,
|
|
VMDir: curDetail.Directory,
|
|
DriverID: builtin.IDDriverReimsMacOS,
|
|
QMPAddr: qmpAddr,
|
|
})
|
|
}
|
|
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。
|
|
func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error {
|
|
ledger, err := plugin.LoadArgLedger(detail.Directory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}}
|
|
if detail.NetworkMode == "bridge" {
|
|
record, err := reims.ReadNetworkRecord(detail.Directory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if record.Corrupt {
|
|
return networkmsg.Error("record_invalid", nil)
|
|
}
|
|
if record.Pending {
|
|
return networkmsg.Error("packet_pending", nil)
|
|
}
|
|
mac, err := resolveVMNetworkMAC(ctx, c, *detail)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sockPath := record.SocketPath
|
|
if sockPath == "" {
|
|
sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock")
|
|
}
|
|
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}}
|
|
}
|
|
// 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。
|
|
extra := reims.StripPacketBridgeArgs(detail.ExtraArgs)
|
|
result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent})
|
|
for _, warning := range result.Warnings {
|
|
a.emitVMLog(detail.Name, warning)
|
|
}
|
|
if result.ExtraArgs != detail.ExtraArgs {
|
|
if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
|
return networkmsg.Error("config_save", err)
|
|
}
|
|
}
|
|
if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil {
|
|
return err
|
|
}
|
|
detail.ExtraArgs = result.ExtraArgs
|
|
return nil
|
|
}
|
|
|
|
// prepareLegacyColdStart guards the older start path against a stopped VM that
|
|
// still holds suspend artifacts. It drops provably orphaned files, then refuses
|
|
// the start while a recoverable snapshot remains: this path cannot resume one,
|
|
// and cold-starting over it would discard the guest's saved state. Resume or
|
|
// discard the snapshot from the UI first.
|
|
func prepareLegacyColdStart(ctx context.Context, locale i18n.Locale, name, tmpDir string, cur reims.VMDetail, log func(string)) error {
|
|
if cur.State != "stopped" {
|
|
return nil
|
|
}
|
|
suspended, err := reims.InspectSuspendState(cur.Directory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !suspended {
|
|
err := startprep.CleanStaleSuspendBeforeStart(ctx, cur.Directory, name, tmpDir, log, log)
|
|
if !errors.Is(err, reims.ErrSuspendStatePresent) {
|
|
return err
|
|
}
|
|
}
|
|
return i18n.NewCodedError(locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
|
|
}
|
|
|
|
func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
detail, err := c.Show(ctx, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
|
|
return a.stopMacOSVMLocked(operationCtx, name, force, c)
|
|
})
|
|
}
|
|
|
|
func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
|
|
a.cancelRebootWatcher(name)
|
|
stopVMMonitor(name)
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.transitions[vmKey(name)] = "stopping"
|
|
a.mu.Unlock()
|
|
if mgr != nil {
|
|
mgr.Registry().Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{
|
|
VMName: name,
|
|
DriverID: builtin.IDDriverReimsMacOS,
|
|
})
|
|
}
|
|
a.emitStateChanged()
|
|
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
|
var err error
|
|
if force {
|
|
err = c.StopForce(ctx, name, w, w)
|
|
} else {
|
|
err = c.Stop(ctx, name, w, w)
|
|
}
|
|
if err != nil {
|
|
a.mu.Lock()
|
|
delete(a.transitions, vmKey(name))
|
|
a.mu.Unlock()
|
|
a.emitVMLog(name, "Stop error: "+err.Error())
|
|
return err
|
|
}
|
|
a.stopPacketBridge(name)
|
|
a.mu.Lock()
|
|
delete(a.pendingChanges, vmKey(name))
|
|
a.mu.Unlock()
|
|
if mgr != nil {
|
|
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
|
|
VMName: name,
|
|
DriverID: builtin.IDDriverReimsMacOS,
|
|
})
|
|
}
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
// 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 {
|
|
vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
|
if resolveErr != nil {
|
|
return true, resolveErr
|
|
}
|
|
return true, a.startResolvedVMLocked(ctx, nil, vm)
|
|
}
|
|
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
return true, a.startResolvedVMLocked(ctx, svc, vm)
|
|
}
|
|
|
|
func (a *App) ejectMacOSInstaller(name string) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
detail, err := c.Show(context.Background(), name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
|
if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
|
return c.Eject(ctx, name, w, w)
|
|
}); err != nil {
|
|
a.emitVMLog(name, "Eject error: "+err.Error())
|
|
return err
|
|
}
|
|
a.emitVMLog(name, "Installer ejected.")
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
detail, err := c.Show(context.Background(), name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
removed := false
|
|
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
|
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
|
|
})
|
|
if removed {
|
|
releaseVMTyping(name)
|
|
releaseVMThumbnail(name)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
|
|
name := detail.Name
|
|
if detail.State != "running" {
|
|
a.cancelRebootWatcher(name)
|
|
stopVMMonitor(name)
|
|
a.stopPacketBridge(name)
|
|
}
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
|
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
|
|
return c.Delete(ctx, name, keepFiles, w, w)
|
|
}, func() (bool, error) {
|
|
vms, err := c.List(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
for _, vm := range vms {
|
|
if strings.EqualFold(vm.Name, name) {
|
|
return true, nil
|
|
}
|
|
}
|
|
return false, nil
|
|
})
|
|
if deleteErr != nil {
|
|
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
|
|
}
|
|
if !deleted {
|
|
return deleteErr
|
|
}
|
|
*removed = true
|
|
a.cancelRebootWatcher(name)
|
|
stopVMMonitor(name)
|
|
a.stopPacketBridge(name)
|
|
a.mu.Lock()
|
|
delete(a.pendingChanges, vmKey(name))
|
|
delete(a.transitions, vmKey(name))
|
|
delete(a.diskPaths, vmKey(name))
|
|
delete(a.procSamples, vmKey(name))
|
|
delMgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if delMgr != nil {
|
|
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
|
|
VMName: name,
|
|
DriverID: builtin.IDDriverReimsMacOS,
|
|
})
|
|
}
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return deleteErr
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return c.ReadLogs(context.Background(), name, serial)
|
|
}
|