Files
Reims-Go/internal/cli/start.go
T
Nwflower b6fde8fd4b feat(lifecycle): route VM details and settings by driver
Resolve details through driver.Show with a generic GetVMInfo binding, and validate/apply changes through lifecycle.Set in App and CLI.

Move guest language and OpenCore replay into ReimsMacOSDriver.Set, preserving legacy fallbacks and adding second-driver detail/settings acceptance.
2026-11-30 09:04:14 -07:00

162 lines
5.3 KiB
Go

package cli
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/lifecycle"
)
// startHandoffTimeout bounds how long `vm start` waits for the window to
// report back. Preparation can rebuild the OpenCore image before QEMU starts.
const startHandoffTimeout = 5 * time.Minute
// startVM checks the VM can start, then hands it to the desktop window: the
// one already running, or a new one in the tray (`--background`). The window
// runs the GUI's StartVM, so a VM started from the command line gets Guest
// Tools and the Win10 cold-reboot watcher too; both need a process that stays
// up after this command exits.
//
// viaWindow is false when --data-root points elsewhere than the window's
// data root could; the VM then starts here, without those two.
func startVM(ctx context.Context, cfg *config.Config, name string, viaWindow bool) error {
return startVMWithDriver(ctx, cfg, "", name, viaWindow)
}
func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
if viaWindow && windowHandoffWorks {
return startInWindow(ctx, cfg, vm.DriverID, vm.Name)
}
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
return err
}
func setVM(ctx context.Context, cfg *config.Config, driverID, name string, changes map[string]any) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
return svc.Set(ctx, driver.VMRef{DriverID: driverID, Name: name}, changes, os.Stdout, os.Stderr)
}
func deleteVM(ctx context.Context, cfg *config.Config, driverID, name string, keepFiles bool) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
return svc.Delete(ctx, driver.VMRef{DriverID: driverID, Name: name}, keepFiles, os.Stdout, os.Stderr)
}
func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr)
}
func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error {
if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil {
return err
}
result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano()))
w := WindowArgs{StartVM: name, StartDriver: driverID, StartResult: result}
if hwnd := findWindow(); hwnd != 0 {
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
if err := sendToWindow(hwnd, w.Args()); err != nil {
return err
}
} else {
w.Background = true
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.spawning_tray", i18n.Vars{"name": name}))
if err := spawnWindow(w.Args()); err != nil {
return err
}
}
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
res, err := waitStartResult(ctx, result, startHandoffTimeout)
switch {
case errors.Is(err, context.Canceled):
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.canceled", i18n.Vars{"name": name}))
case errors.Is(err, context.DeadlineExceeded):
return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout}))
case err != nil:
return err
}
if !res.OK {
return errors.New(res.Error)
}
// Guest Tools only connects once macOS is up and its agent runs, so say
// what this process can know: who now looks after the VM.
fmt.Println(i18n.M(cfg.Locale, "cli.start.managed_ok", i18n.Vars{"name": name}))
return nil
}
// waitStartResult polls for the window's StartResult file and removes it.
// The window writes it with a rename, so any file seen is complete.
func waitStartResult(ctx context.Context, path string, timeout time.Duration) (StartResult, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
for {
if b, err := os.ReadFile(path); err == nil {
_ = os.Remove(path)
var res StartResult
if err := json.Unmarshal(b, &res); err != nil {
return StartResult{}, fmt.Errorf("unreadable start result %s: %w", path, err)
}
return res, nil
}
select {
case <-ctx.Done():
return StartResult{}, ctx.Err()
case <-tick.C:
}
}
}
// WriteStartResult is the window's side of waitStartResult.
func WriteStartResult(path string, startErr error) error {
res := StartResult{OK: startErr == nil}
if startErr != nil {
res.Error = startErr.Error()
}
b, err := json.Marshal(res)
if err != nil {
return err
}
part := path + ".part"
if err := os.WriteFile(part, b, 0o644); err != nil {
return err
}
return os.Rename(part, path)
}