Files
Reims-Go/internal/cli/start.go
T
Nwflower 7ba5e3fa9c feat(lifecycle): route VM starts through owning drivers
Change Driver.Start to StartRequest/StartResult with a compile-time macOS adapter assertion and registry-to-router coverage. Keep legacy Sidecar name alongside VMRef and grant argument privileges by driver ownership.

Move macOS preparation into ReimsMacOSDriver after hook veto, fail preparation errors before launch, and verify veto leaves OpenCore, recovery markers and ledgers unchanged.

Unify GUI, CLI and window list/start/stop through internal/lifecycle, select frontend VMs by VMRef, lazily initialize reims only in legacy CLI branches, and cover a second driver through App user entry points.
2026-11-30 08:34:20 -07:00

142 lines
4.5 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 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)
}