package cli import ( "context" "encoding/json" "errors" "fmt" "os" "os/signal" "path/filepath" "time" "github.com/Nwflower/reims-go/internal/atomicfile" "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" "github.com/Nwflower/reims-go/internal/vmstart" ) // 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 func openCLILifecycle(cfg *config.Config) (*lifecycle.Service, func(), error) { mgr, router, err := openCLIPluginManager(cfg, false) if err != nil { return nil, nil, err } return lifecycle.New(mgr.Registry(), router, nil), mgr.Close, nil } // startVM resolves the VM, 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. // // 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。 func startVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err } if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, vm.DriverID, vm.Name) } if err := requireDirectNetwork(vm); err != nil { return err } _, err = svc.Start(vmstart.WithPrimaryDisplayOnly(ctx), vm.Ref(), os.Stdout, os.Stderr) return err } func actionVM(ctx context.Context, cfg *config.Config, driverID, name, action string, params map[string]any) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() _, err = svc.InvokeAction(ctx, driver.VMRef{DriverID: driverID, Name: name}, action, params) return err } func setVM(ctx context.Context, cfg *config.Config, driverID, name string, changes map[string]any) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() 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 { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() return svc.Delete(ctx, driver.VMRef{DriverID: driverID, Name: name}, keepFiles, os.Stdout, os.Stderr) } func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize string) (driver.DiskResizeResult, error) { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskResizeResult{}, err } defer closeService() return svc.ResizeDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, newSize, os.Stdout, os.Stderr) } func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (driver.DiskCompactResult, error) { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskCompactResult{}, err } defer closeService() return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr) } func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error { svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } defer closeService() 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 { return runInWindow(ctx, cfg, driverID, name, false) } func runInWindow(ctx context.Context, cfg *config.Config, driverID, name string, resume bool) error { prefix := "cli.start." if resume { prefix = "cli.resume." } // 使用管理器的规范目录,避免同目录的大小写或 Junction 别名使结果路径被拒绝。 if desktop, err := config.Load(""); err == nil && sameDataRoot(cfg.DataRoot, desktop.DataRoot) { copy := *cfg copy.DataRoot = desktop.DataRoot cfg = © } 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 resume { w.StartVM, w.ResumeVM = "", name } if hwnd := findWindow(); hwnd != 0 { fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, prefix+"handing_to_window", i18n.Vars{"name": name})) if err := sendToWindow(hwnd, w.Args(), 0); err != nil { return err } } else { w.Background = true fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, prefix+"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, prefix+"canceled", i18n.Vars{"name": name})) case errors.Is(err, context.DeadlineExceeded): return fmt.Errorf("%s", i18n.M(cfg.Locale, prefix+"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, prefix+"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 } return atomicfile.Write(path, b, 0o644) }