Files
Reims-Go/install_flow.go
T
NwflowerandClaude Opus 5.5 331d0748a4 refactor(vmstart): share VM start preparation between GUI and CLI
New internal/vmstart holds the steps both front ends need: commit-memory
precheck, offline helper disk, recovery boot picker, guest-language replay,
WHPX nested-virt compatibility, and P-core pinning after start. app.go's
StartVM and the CLI's "vm start" / "vm create --start" (cmd/reims-go/start.go)
call it, replacing memcheck.go and the copies in install/opencore flows.
"vm start" now refuses a VM that is already running instead of rewriting its
OpenCore image. Guest Tools bridging and the Win10 cold-reboot watcher still
need a long-lived process and stay GUI-only (architecture.md 3.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:51:23 -07:00

362 lines
11 KiB
Go

package main
// Finishing an offline install (roadmap M2.3): take the installer out and turn
// the network back on, which an offline install keeps off so its installer
// downloads no update (`reims-ctl create --help`, upstream 3731afd).
import (
"context"
"errors"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// recoveryPickerMarkerFile tracks OpenCore ShowPicker state managed by
// reims-go's recovery-mode toggle inside the VM directory:
// - "want": EnterRecovery ran while VM was running; apply --boot-selection=true before next start.
// - "on": --boot-selection=true is active on opencore.qcow2.
// - "restore": FinishInstall ran while VM was running; apply --boot-selection=false before next start.
// - "": Normal direct boot (file absent).
func isRecoveryModeActive(d reims.VMDetail) bool {
if d.HasInstaller {
return true
}
m := vmstart.ReadRecoveryMarker(d.Directory)
return m == "on" || m == "want"
}
func (a *App) pickCachedRecoveryInstaller() (string, error) {
ic, err := a.installerClient()
if err != nil {
return "", err
}
items, err := ic.ListCached()
if err != nil {
return "", err
}
// ListCached sorts ascending by name; walk in reverse so newer versions win.
// Prefer complete offline installers, then online installers, then other .img/.dmg.
for _, wantKind := range []string{"offline", "online", "other"} {
for i := len(items) - 1; i >= 0; i-- {
it := items[i]
if it.Partial || it.Kind != wantKind {
continue
}
lower := strings.ToLower(it.Name)
if wantKind == "other" && !strings.HasSuffix(lower, ".img") && !strings.HasSuffix(lower, ".dmg") {
continue
}
return it.Path, nil
}
}
return "", nil
}
func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool {
if d.State == "running" {
return true
}
if list, err := c.List(ctx); err == nil {
for _, vm := range list {
if vm.Name == name && vm.State == "running" {
return true
}
}
}
return false
}
// EnterRecovery enables OpenCore's boot picker (--boot-selection=true) so the
// VM can boot macOS's built-in Recovery volume without needing an external
// installer image (upstream reims-util 7867384 sets HideAuxiliary=false).
// If the VM is running, the change is queued for the next start/restart.
func (a *App) EnterRecovery(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
if a.isVMRunning(ctx, c, name, d) {
marker := vmstart.ReadRecoveryMarker(d.Directory)
if marker != "on" {
vmstart.WriteRecoveryMarker(d.Directory, "want")
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
Field: "recovery",
From: "off",
To: "on",
})
a.mu.Unlock()
}
a.emitLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
} else {
a.emitLog(name, "Enabling OpenCore boot picker for recovery mode...")
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
return err
}
vmstart.WriteRecoveryMarker(d.Directory, "on")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
a.emitLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
// AttachInstaller attaches an installer/recovery image to the VM for its next
// start (`reims-ctl insert NAME PATH`). When installerPath is empty, the newest
// complete cached installer in the installers directory is used. Returns the
// attached file's base name.
func (a *App) AttachInstaller(name, installerPath string) (string, error) {
c, err := a.client()
if err != nil {
return "", err
}
d, err := a.GetVMDetail(name)
if err != nil {
return "", err
}
path := strings.TrimSpace(installerPath)
if path == "" {
path, err = a.pickCachedRecoveryInstaller()
if err != nil {
return "", err
}
if path == "" {
return "", errors.New("no cached installer image found")
}
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
base := filepath.Base(path)
a.emitLog(name, "Attaching installer image to "+name+": "+base)
if err := c.Insert(ctx, name, path, w, w); err != nil {
return "", err
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
Field: "installer",
From: "ejected",
To: "attached",
})
a.mu.Unlock()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return base, nil
}
// DownloadAndAttachOnlineRecovery downloads Apple's ~1 GB online recovery image
// (`reims-util online-installer`) in a background task and attaches it to the
// VM via `reims-ctl insert` as soon as it finishes.
func (a *App) DownloadAndAttachOnlineRecovery(name, version string) (string, error) {
ic, err := a.installerClient()
if err != nil {
return "", err
}
if _, err := a.GetVMDetail(name); err != nil {
return "", err
}
for _, t := range tasks.list() {
if t.Kind == "recovery-download" && t.Status == TaskRunning && t.Subject == name {
return t.ID, nil
}
}
v := strings.TrimSpace(version)
if v == "" {
v = "latest"
}
a.ensureTaskEmitter()
base := a.ctx
if base == nil {
base = context.Background()
}
ctx, cancel := context.WithCancel(base)
id := tasks.start("recovery-download", name, "", cancel)
a.emitLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
go func() {
defer cancel()
res, err := ic.DownloadOnline(ctx, v, func(u installer.Update) {
switch u.Kind {
case installer.KindStep, installer.KindNote:
a.emitLog(name, u.Message)
}
tasks.update(id, u)
})
if err != nil {
if ctx.Err() != nil {
a.emitLog(name, "Online recovery download paused; starting again continues where it stopped")
tasks.finish(id, "", context.Canceled)
} else {
a.emitLog(name, "Online recovery download error: "+err.Error())
tasks.finish(id, "", err)
}
return
}
tasks.update(id, installer.Update{
Kind: installer.KindStep,
Step: "attaching online recovery image",
Message: "attaching online recovery image",
Percent: -1,
})
attached, err := a.AttachInstaller(name, res.Image)
if err != nil {
a.emitLog(name, "Failed to attach online recovery image: "+err.Error())
tasks.finish(id, "", err)
return
}
a.emitLog(name, "Online recovery image attached: "+attached)
tasks.finish(id, attached, nil)
}()
return id, nil
}
// FinishInstall exits recovery mode: ejects any attached installer, removes
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
// (--boot-selection=false) if recovery mode enabled the boot picker.
func (a *App) FinishInstall(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
if d.HasInstaller {
a.emitLog(name, "Ejecting installer from "+name+"...")
if err := c.Eject(ctx, name, w, w); err != nil {
return err
}
}
stripped := reims.StripOfflineHelperArgs(d.ExtraArgs)
setOpts := reims.SetOpts{Name: name}
needSet := false
upgradedNVMe := false
if !d.Network {
on := true
setOpts.Network = &on
needSet = true
a.emitLog(name, "Turning the network on for "+name+"...")
}
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
setOpts.DiskController = "nvme"
needSet = true
upgradedNVMe = true
a.emitLog(name, "Upgrading disk controller for "+name+" from SATA/AHCI to NVMe...")
}
if stripped != d.ExtraArgs {
setOpts.ExtraArgs = &stripped
needSet = true
}
if needSet {
if err := c.Set(ctx, setOpts, w, w); err != nil {
return err
}
}
running := a.isVMRunning(ctx, c, name, d)
marker := vmstart.ReadRecoveryMarker(d.Directory)
if running {
var diffs []PendingChange
if d.HasInstaller {
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
}
if !d.Network {
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
}
if upgradedNVMe {
diffs = append(diffs, PendingChange{Field: "disk_controller", From: "ahci", To: "nvme"})
}
switch marker {
case "want":
vmstart.WriteRecoveryMarker(d.Directory, "")
case "on":
vmstart.WriteRecoveryMarker(d.Directory, "restore")
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
}
if len(diffs) > 0 {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], diffs...)
a.mu.Unlock()
}
} else {
if marker == "on" || marker == "restore" {
a.emitLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
a.emitLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
} else {
vmstart.WriteRecoveryMarker(d.Directory, "")
if prep, err := a.prep(name); err == nil {
prep.ReplayGuestLang(ctx, d.Directory)
}
}
} else if marker != "" {
vmstart.WriteRecoveryMarker(d.Directory, "")
}
}
a.emitLog(name, "Exited recovery mode")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
// UpgradeDiskToNVMe switches an existing installed VM from legacy SATA/AHCI to
// NVMe via `reims-ctl set --disk-controller nvme` (applies at next start if running).
func (a *App) UpgradeDiskToNVMe(name string) error {
c, err := a.client()
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
}
if d.HasInstaller {
return errors.New("exit recovery mode (eject installer) before switching disk controller")
}
if strings.EqualFold(d.DiskController, "nvme") {
return nil
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
ctx := context.Background()
a.emitLog(name, "Upgrading disk controller for "+name+" to NVMe...")
if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
a.mu.Lock()
a.pendingChanges[name] = append(a.pendingChanges[name], PendingChange{
Field: "disk_controller",
From: d.DiskController,
To: "nvme",
})
a.mu.Unlock()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}