Every VM action had two bindings: one by name and one by driver and name. The window used only the second, so the first is gone and the WithDriver suffix with it. Unused bindings and frontend exports are removed too. Tests now reject bindings the window never calls, stale generated bindings and unused frontend exports. TypeScript rejects unused locals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
278 lines
9.4 KiB
Go
278 lines
9.4 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/macos/installer"
|
|
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/networkmsg"
|
|
"github.com/Nwflower/reims-go/internal/packetbridge"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
)
|
|
|
|
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
|
defer func() {
|
|
var coded *i18n.CodedError
|
|
if errors.As(err, &coded) && strings.HasPrefix(coded.Code, "E_NETWORK_") {
|
|
err = networkmsg.Localize(err, a.locale())
|
|
}
|
|
}()
|
|
if err := a.requireMacOSEnabled(); err != nil {
|
|
return err
|
|
}
|
|
if issues := a.ValidateCreate(opts); len(issues) > 0 {
|
|
return fmt.Errorf("%s", issues[0].Message)
|
|
}
|
|
if opts.NetworkMode != "" {
|
|
enabled := opts.NetworkMode != "off"
|
|
opts.Network = &enabled
|
|
}
|
|
if opts.NetworkMode == "bridge" {
|
|
opts.SSHPort = 0
|
|
}
|
|
a.mu.Lock()
|
|
cfgCopy := *a.cfg
|
|
a.mu.Unlock()
|
|
active, err := rt.ResolveActive(&cfgCopy)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := reims.NewClient(&cfgCopy, *active)
|
|
|
|
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
|
// QMP wiring, and Win11 WHPX nested-virt fallback apply uniformly.
|
|
startAfterCreate := opts.Start
|
|
opts.Start = false
|
|
|
|
ctx, cancel := context.WithCancel(a.baseCtx())
|
|
defer cancel()
|
|
taskID, w, finishTask := a.ctlTaskWriter("vm-create", opts.Name, cancel)
|
|
if opts.NetworkMode == "bridge" {
|
|
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: networkmsg.Text(a.locale(), "log.create_network_prepare"), Percent: -1})
|
|
}
|
|
if err := a.prepareCreateNetwork(ctx, c, opts); err != nil {
|
|
finishTask(err)
|
|
return err
|
|
}
|
|
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
|
|
|
|
existingVMs, _ := c.List(ctx)
|
|
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
|
|
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
|
|
} else if removed != "" {
|
|
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
|
|
}
|
|
|
|
// Ensure any requested macOS installer is downloaded via installer.Client
|
|
// before invoking reims-ctl create, so the Installers page, sidebar, and
|
|
// concurrent downloads share live byte progress, queueing and deduplication.
|
|
// reims-ctl create checks the same shared installers directory and reuses
|
|
// the completed image without downloading again.
|
|
if dlKind, dlVersion := createInstallerTarget(opts); dlKind != "" {
|
|
ic := installer.NewClient(&cfgCopy, *active)
|
|
ic.Downloader = a.activeDownloader
|
|
cached, _ := ic.ListCached()
|
|
if installerDownloads.hasActive(dlKind, dlVersion) || !hasCompleteCachedInstaller(cached, dlKind, dlVersion) {
|
|
res, derr := a.ensureInstallerForTask(ctx, taskID, "vm-create", opts.Name, dlKind, dlVersion, func(dlCtx context.Context, onUpdate func(installer.Update)) (*installer.Result, error) {
|
|
if dlKind == "offline" {
|
|
return ic.DownloadOffline(dlCtx, dlVersion, onUpdate)
|
|
}
|
|
return ic.DownloadOnline(dlCtx, dlVersion, onUpdate)
|
|
})
|
|
if derr != nil {
|
|
if errors.Is(derr, context.Canceled) || ctx.Err() != nil {
|
|
finishTask(context.Canceled)
|
|
a.emitVMLog(opts.Name, "Create canceled.")
|
|
return context.Canceled
|
|
}
|
|
finishTask(derr)
|
|
a.emitVMLog(opts.Name, "Create error: "+derr.Error())
|
|
return derr
|
|
}
|
|
if res != nil && res.Image != "" {
|
|
a.emitVMLog(opts.Name, "Installer ready: "+res.Image)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Pre-fetch OcBinaryData with an idle-read timeout so slow GitHub links do
|
|
// not trigger reims-util's 180s HTTP-200 truncate-and-restart loop.
|
|
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
|
|
loggedPrefetch := false
|
|
perr := installer.EnsureCachedAsset(ctx, cfgCopy.XDGCacheDir(), installer.OcBinaryDataAsset, nil, func(u installer.Update) {
|
|
if !loggedPrefetch && u.Kind == installer.KindStep {
|
|
loggedPrefetch = true
|
|
a.emitVMLog(opts.Name, opts.Name+": "+u.Message)
|
|
}
|
|
tasks.update(taskID, u)
|
|
})
|
|
if perr != nil {
|
|
if errors.Is(perr, context.Canceled) || ctx.Err() != nil {
|
|
finishTask(context.Canceled)
|
|
a.emitVMLog(opts.Name, "Create canceled.")
|
|
return context.Canceled
|
|
}
|
|
a.emitVMLog(opts.Name, "Pre-fetch OpenCore resources skipped (reims-ctl will retry): "+perr.Error())
|
|
}
|
|
}
|
|
|
|
// Convert VMDK / RAW disks into qcow2 before invoking reims-ctl create.
|
|
var convertedTmp string
|
|
if opts.Disk != "" && reims.NeedsDiskConversion(opts.Disk) {
|
|
convertedTmp = filepath.Join(cfgCopy.TempDir(), fmt.Sprintf("import-%s-%d.qcow2", opts.Name, time.Now().Unix()))
|
|
defer os.Remove(convertedTmp)
|
|
a.emitVMLog(opts.Name, fmt.Sprintf("Converting %s to qcow2 via qemu-img...", filepath.Base(opts.Disk)))
|
|
env := rt.BuildChildEnv(&cfgCopy, *active)
|
|
if cerr := reims.ConvertDiskToQCOW2(ctx, active.QemuImgPath(), env, opts.Disk, convertedTmp, w, w); cerr != nil {
|
|
if ctx.Err() != nil {
|
|
cerr = context.Canceled
|
|
}
|
|
finishTask(cerr)
|
|
if errors.Is(cerr, context.Canceled) {
|
|
a.emitVMLog(opts.Name, "Create canceled.")
|
|
} else {
|
|
a.emitVMLog(opts.Name, "Disk conversion error: "+cerr.Error())
|
|
}
|
|
return cerr
|
|
}
|
|
opts.Disk = convertedTmp
|
|
opts.DiskMode = "copy"
|
|
}
|
|
|
|
err = c.Create(ctx, opts, w, w)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
err = context.Canceled
|
|
}
|
|
finishTask(err)
|
|
if errors.Is(err, context.Canceled) {
|
|
a.emitVMLog(opts.Name, "Create canceled.")
|
|
} else {
|
|
a.emitVMLog(opts.Name, "Create error: "+err.Error())
|
|
}
|
|
return err
|
|
}
|
|
createdDir := strings.TrimSpace(opts.Dir)
|
|
if det, serr := c.Show(ctx, opts.Name); serr == nil && det.Directory != "" {
|
|
createdDir = det.Directory
|
|
}
|
|
if createdDir == "" {
|
|
createdDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
|
}
|
|
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
|
|
finishTask(err)
|
|
return fmt.Errorf("record VM driver ownership: %w", err)
|
|
}
|
|
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
|
var parts []string
|
|
if postSet.DiskController != "" {
|
|
parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController))
|
|
}
|
|
if postSet.Capture != nil && !*postSet.Capture {
|
|
parts = append(parts, "capture=off")
|
|
}
|
|
a.emitVMLog(opts.Name, fmt.Sprintf("Applying VM defaults for %s (%s)...", opts.Name, strings.Join(parts, ", ")))
|
|
if serr := c.Set(ctx, postSet, w, w); serr != nil {
|
|
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply post-create defaults (%s): %v", strings.Join(parts, ", "), serr))
|
|
}
|
|
}
|
|
guestLang := strings.TrimSpace(opts.GuestLang)
|
|
if guestLang == "" && opts.SourceMode != "disk" {
|
|
guestLang = opencore.DefaultGuestLang(cfgCopy.Locale)
|
|
}
|
|
release := ""
|
|
if opts.SourceMode != "disk" {
|
|
release = strings.TrimSpace(opts.MacOS)
|
|
}
|
|
vmDir := ""
|
|
if guestLang != "" || release != "" {
|
|
vmDir = strings.TrimSpace(opts.Dir)
|
|
if d, serr := c.Show(ctx, opts.Name); serr == nil && d.Directory != "" {
|
|
vmDir = d.Directory
|
|
} else if vmDir == "" {
|
|
vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
|
}
|
|
}
|
|
if werr := reims.WriteReleaseRecord(vmDir, release); werr != nil {
|
|
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
|
|
}
|
|
if guestLang != "" {
|
|
prep, lerr := a.prep(opts.Name)
|
|
if lerr == nil {
|
|
lerr = prep.ApplyGuestLang(ctx, vmDir, guestLang, false)
|
|
}
|
|
if lerr != nil {
|
|
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not apply macOS language (%s): %v", guestLang, lerr))
|
|
}
|
|
}
|
|
if opts.NetworkMode == "bridge" {
|
|
if _, networkErr := a.applyVMNetwork(ctx, opts.Name, "bridge", opts.UplinkGUID); networkErr != nil {
|
|
err = networkmsg.Error("create_bridge_pending", networkErr, "name", opts.Name)
|
|
finishTask(err)
|
|
a.emitLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error())
|
|
a.emitStateChanged()
|
|
return err
|
|
}
|
|
}
|
|
finishTask(nil)
|
|
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
|
|
a.emitStateChanged()
|
|
if startAfterCreate && ctx.Err() == nil {
|
|
return a.StartVM(driver.BuiltinReimsMacOSDriverID, opts.Name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func createInstallerTarget(opts reims.CreateOpts) (kind, version string) {
|
|
if strings.TrimSpace(opts.Disk) != "" || strings.TrimSpace(opts.Installer) != "" {
|
|
return "", ""
|
|
}
|
|
if opts.SourceMode == "disk" || opts.SourceMode == "installer" {
|
|
return "", ""
|
|
}
|
|
v := strings.TrimSpace(opts.MacOS)
|
|
if v == "" {
|
|
return "", ""
|
|
}
|
|
if opts.Offline || opts.SourceMode == "offline" {
|
|
return "offline", v
|
|
}
|
|
return "online", v
|
|
}
|
|
|
|
// 在分配磁盘前准备依赖,真正应用时仍重新检查出口。
|
|
func (a *App) prepareCreateNetwork(ctx context.Context, c networkControlClient, opts reims.CreateOpts) error {
|
|
if opts.NetworkMode != "bridge" {
|
|
return nil
|
|
}
|
|
if !a.npcapPluginEnabled() {
|
|
return networkmsg.Error("plugin_disabled", nil)
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 20*time.Minute)
|
|
defer cancel()
|
|
adapters, err := packetbridge.ListAdapters(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
selected, err := selectPacketUplink(adapters, opts.UplinkGUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := a.ensureNpcap(ctx, c); err != nil {
|
|
return err
|
|
}
|
|
if err := packetbridge.CheckAdapter(selected.GUID, selected.Index); err != nil {
|
|
return err
|
|
}
|
|
return ctx.Err()
|
|
}
|