* 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
481 lines
15 KiB
Go
481 lines
15 KiB
Go
package app
|
|
|
|
// Finishing an offline install ejects the attached installer and re-enables
|
|
// guest networking (`reims-ctl create --help`, upstream 3731afd).
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/macos/installer"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
)
|
|
|
|
// isRecoveryModeActive reports whether d has an installer attached or an
|
|
// active/scheduled OpenCore boot-picker marker ("on" or "want").
|
|
func isRecoveryModeActive(d reims.VMDetail) bool {
|
|
if d.HasInstaller {
|
|
return true
|
|
}
|
|
return isRecoveryMarkerActive(d.Directory)
|
|
}
|
|
|
|
func isRecoveryMarkerActive(vmDir string) bool {
|
|
return startprep.IsRecoveryMarkerActive(vmDir)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
// EnterRecovery routes the macOS recovery action through the lifecycle service.
|
|
// The legacy path remains available for minimal embedding without a plugin manager.
|
|
func (a *App) EnterRecovery(name string) error {
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
if svc == nil {
|
|
return a.enterMacOSRecovery(name)
|
|
}
|
|
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result, _ := raw.(map[string]any)
|
|
running, _ := result["running"].(bool)
|
|
if running {
|
|
scheduled, _ := result["scheduled"].(bool)
|
|
if scheduled {
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{Field: "recovery", From: "off", To: "on"})
|
|
a.mu.Unlock()
|
|
}
|
|
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
|
} else {
|
|
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
|
}
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
// enterMacOSRecovery is the direct reims-ctl fallback when the lifecycle
|
|
// router is unconfigured; it enables OpenCore's boot picker (--boot-selection=true)
|
|
// immediately when stopped or queues a "want" marker when running.
|
|
func (a *App) enterMacOSRecovery(name string) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer release()
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
ctx := context.Background()
|
|
|
|
if c.IsRunning(ctx, d) {
|
|
marker := startprep.ReadRecoveryMarker(d.Directory)
|
|
if marker != "on" {
|
|
startprep.WriteRecoveryMarker(d.Directory, "want")
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
|
Field: "recovery",
|
|
From: "off",
|
|
To: "on",
|
|
})
|
|
a.mu.Unlock()
|
|
}
|
|
a.emitVMLog(name, "Recovery mode scheduled for "+name+": OpenCore boot picker will open on next start")
|
|
} else {
|
|
a.emitVMLog(name, "Enabling OpenCore boot picker for recovery mode...")
|
|
if err := c.UpdateOpenCore(ctx, name, true, w, w); err != nil {
|
|
return err
|
|
}
|
|
startprep.WriteRecoveryMarker(d.Directory, "on")
|
|
if prep, err := a.prep(name); err == nil {
|
|
prep.ReplayGuestLang(ctx, d.Directory)
|
|
}
|
|
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
|
|
}
|
|
a.emitStateChanged()
|
|
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
|
|
}
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
var d reims.VMDetail
|
|
if svc == nil {
|
|
var release func()
|
|
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer release()
|
|
} else {
|
|
d, err = c.Show(a.baseCtx(), 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.emitVMLog(name, line) })
|
|
ctx := context.Background()
|
|
|
|
base := filepath.Base(path)
|
|
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
|
|
if svc != nil {
|
|
err = a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
|
_, err := svc.InvokeAction(operationCtx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
|
|
return err
|
|
})
|
|
} else {
|
|
err = a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
|
return c.Insert(operationCtx, name, path, w, w)
|
|
})
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if c.IsRunning(ctx, d) {
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
|
Field: "installer",
|
|
From: "ejected",
|
|
To: "attached",
|
|
})
|
|
a.mu.Unlock()
|
|
}
|
|
a.emitStateChanged()
|
|
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, name, cancel)
|
|
a.emitVMLog(name, "Downloading Apple online recovery image (~1 GB) for "+name+"...")
|
|
go func() {
|
|
defer cancel()
|
|
res, err := a.ensureInstallerForTask(ctx, id, "recovery-download", name, "online", v, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
|
|
return ic.DownloadOnline(dlCtx, v, onUpdate)
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
|
|
a.emitVMLog(name, "Online recovery download paused; starting again continues where it stopped")
|
|
tasks.finish(id, "", context.Canceled)
|
|
} else {
|
|
a.emitVMLog(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.emitVMLog(name, "Failed to attach online recovery image: "+err.Error())
|
|
tasks.finish(id, "", err)
|
|
return
|
|
}
|
|
a.emitVMLog(name, "Online recovery image attached: "+attached)
|
|
tasks.finish(id, attached, nil)
|
|
}()
|
|
return id, nil
|
|
}
|
|
|
|
// applyFinishInstallResult mirrors driver finish_install deferred changes into
|
|
// App.pendingChanges, clears any stale provision-ready milestone, and records
|
|
// recovery-exit and wipe-warning logs consistently for GUI, CLI, and Host API.
|
|
func (a *App) applyFinishInstallResult(driverID, name string, result map[string]any) {
|
|
running, _ := result["running"].(bool)
|
|
if running {
|
|
var diffs []PendingChange
|
|
if value, _ := result["installer_ejected"].(bool); value {
|
|
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
|
}
|
|
if value, _ := result["network_enabled"].(bool); value {
|
|
diffs = append(diffs, PendingChange{Field: "network", From: "off", To: "on"})
|
|
}
|
|
if value, _ := result["upgraded_nvme"].(bool); value {
|
|
from, _ := result["disk_controller_from"].(string)
|
|
if from == "" {
|
|
from = "ahci"
|
|
}
|
|
diffs = append(diffs, PendingChange{Field: "disk_controller", From: from, To: "nvme"})
|
|
}
|
|
if value, _ := result["recovery_pending"].(bool); value {
|
|
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
|
}
|
|
if len(diffs) > 0 {
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKeyForDriver(driverID, name)] = append(a.pendingChanges[vmKeyForDriver(driverID, name)], diffs...)
|
|
a.mu.Unlock()
|
|
}
|
|
}
|
|
if wiped, ok := result["provision_wiped"].(bool); ok && !wiped {
|
|
if detail, _ := result["provision_wipe_error"].(string); detail != "" {
|
|
a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) while running; scheduled wipe for next start: "+detail)
|
|
}
|
|
}
|
|
a.clearTelemetryMilestone(vmKeyForDriver(driverID, name), "serial:provision_ready")
|
|
a.emitVMLog(name, "Exited recovery mode")
|
|
}
|
|
|
|
// FinishInstall exits recovery through the owning driver and mirrors deferred
|
|
// changes into the existing App pending-change model.
|
|
func (a *App) FinishInstall(name string) error {
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
if svc == nil {
|
|
return a.finishMacOSInstall(name)
|
|
}
|
|
vm, err := a.resolveVMInfo("", name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var raw any
|
|
err = a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
|
|
var invokeErr error
|
|
raw, invokeErr = svc.InvokeAction(ctx, vm.Ref(), "finish_install", nil)
|
|
return invokeErr
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result, _ := raw.(map[string]any)
|
|
a.applyFinishInstallResult(vm.DriverID, name, result)
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
// finishMacOSInstall 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) finishMacOSInstall(name string) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer release()
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
|
ctx := context.Background()
|
|
|
|
if d.HasInstaller {
|
|
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
|
if err := a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
|
return c.Eject(operationCtx, name, w, w)
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
stripped := reims.StripProvisionArgs(reims.StripOfflineHelperArgs(d.ExtraArgs))
|
|
setOpts := reims.SetOpts{Name: name}
|
|
needSet := false
|
|
upgradedNVMe := false
|
|
if !d.Network && d.NetworkMode != "bridge" && d.NetworkMode != "custom" {
|
|
on := true
|
|
setOpts.Network = &on
|
|
needSet = true
|
|
a.emitVMLog(name, "Turning the network on for "+name+"...")
|
|
}
|
|
if d.HasInstaller && strings.EqualFold(d.DiskController, "ahci") {
|
|
setOpts.DiskController = "nvme"
|
|
needSet = true
|
|
upgradedNVMe = true
|
|
a.emitVMLog(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
|
|
}
|
|
}
|
|
if err := installer.SecureRemoveProvisionImage(d.Directory); err != nil {
|
|
a.emitVMLog(name, "Warning: could not remove offline provisioning disk (REIMSPROV) now; scheduled wipe for next start: "+err.Error())
|
|
}
|
|
a.clearTelemetryMilestone(vmKey(name), "serial:provision_ready")
|
|
|
|
running := c.IsRunning(ctx, d)
|
|
marker := startprep.ReadRecoveryMarker(d.Directory)
|
|
if running {
|
|
var diffs []PendingChange
|
|
if d.HasInstaller {
|
|
diffs = append(diffs, PendingChange{Field: "installer", From: "attached", To: "ejected"})
|
|
}
|
|
if setOpts.Network != nil {
|
|
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":
|
|
startprep.WriteRecoveryMarker(d.Directory, "")
|
|
case "on":
|
|
startprep.WriteRecoveryMarker(d.Directory, "restore")
|
|
diffs = append(diffs, PendingChange{Field: "recovery", From: "on", To: "off"})
|
|
}
|
|
if len(diffs) > 0 {
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], diffs...)
|
|
a.mu.Unlock()
|
|
}
|
|
} else {
|
|
if marker == "on" || marker == "restore" {
|
|
a.emitVMLog(name, "Restoring OpenCore direct boot after exiting recovery mode...")
|
|
if err := c.UpdateOpenCore(ctx, name, false, w, w); err != nil {
|
|
a.emitVMLog(name, "Warning: could not disable OpenCore boot picker: "+err.Error())
|
|
} else {
|
|
startprep.WriteRecoveryMarker(d.Directory, "")
|
|
if prep, err := a.prep(name); err == nil {
|
|
prep.ReplayGuestLang(ctx, d.Directory)
|
|
}
|
|
}
|
|
} else if marker != "" {
|
|
startprep.WriteRecoveryMarker(d.Directory, "")
|
|
}
|
|
}
|
|
a.emitVMLog(name, "Exited recovery mode")
|
|
a.emitStateChanged()
|
|
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
|
|
}
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
var d reims.VMDetail
|
|
if svc == nil {
|
|
var release func()
|
|
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer release()
|
|
} else {
|
|
d, err = c.Show(a.baseCtx(), 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.emitVMLog(name, line) })
|
|
ctx := context.Background()
|
|
a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...")
|
|
if svc != nil {
|
|
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "upgrade_nvme", nil)
|
|
} else {
|
|
err = c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if c.IsRunning(ctx, d) {
|
|
a.mu.Lock()
|
|
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
|
|
Field: "disk_controller",
|
|
From: d.DiskController,
|
|
To: "nvme",
|
|
})
|
|
a.mu.Unlock()
|
|
}
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|