diff --git a/docs/architecture.md b/docs/architecture.md index c98029a..d9e4a54 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -82,7 +82,7 @@ flowchart TB ## 4. 关键机制与安全边界 ### 4.1 启动编排与单实例交接 -- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启和删除:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。 +- `internal/lifecycle` 统一 GUI、CLI 与窗口交接的 VM 列表、详情、设置、启动、停止、重启、删除、介质动作和日志读取:按 `VMRef` 解析所属驱动,先收集第三方 Hook,否决时不调用驱动,成功后再发事件。macOS 的启动前检查、参数账本与磁盘准备由 `internal/macos/macosdriver` 自己完成,准备失败即中止;`internal/vmstart` 保留共享检查与旧回退。只有常驻进程才能维持的能力(Guest Tools 桥接、Win10 冷重启监视)由界面进程托管。 - CLI 执行 `vm start` 时,默认交由桌面进程启动:界面已在运行时通过 Wails 单实例锁(`WM_COPYDATA`)发消息不弹窗拉起;未运行时以 `--background` 启动隐藏到托盘的后台界面进程,结果经 `\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。 - 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。 - `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。 diff --git a/docs/guest-plugin-migration.md b/docs/guest-plugin-migration.md index aa61e3c..f296bec 100644 --- a/docs/guest-plugin-migration.md +++ b/docs/guest-plugin-migration.md @@ -147,7 +147,7 @@ GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁 - 第三方插件否决启动时,VM 目录与 OpenCore 镜像未被修改。 - 测试驱动在相同宿主探测结果下,不会收到 OpenCore、辅助盘或冷重启参数。 -### 步骤 3:其余入口统一路由(列表、生命周期、Show/Set 已落地,其余入口待完成) +### 步骤 3:其余入口统一路由(列表、生命周期、Show/Set、介质与日志已落地,其余入口待完成) - **后端**:VM 列表与轮询、详情、创建、设置、停止、重启、删除、日志、弹出安装介质,以及快照、克隆、磁盘、缩略图、统计、排障采集、亲和性等流程,全部经生命周期模块按 `VMRef` 路由。 - **CLI**:`vm` 子命令全部走驱动层,重名时要求 `--driver`。顶层 `installer` 子命令改由 macOS 插件经 `commands` 扩展点贡献,宿主 CLI 提供插件命令转发。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3f2f503..441f3ef 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -529,7 +529,8 @@ export const App: React.FC = () => { const loadVMLog = async (serial: boolean, name = selectedVM?.name) => { if (!name) return try { - const text = await api.ReadVMLogs(name, serial) + const logDriverID = vms.find((v) => v.name === name)?.driver_id ?? '' + const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial) if (serial) setSerialLog(text) else setQemuLog(text) } catch (e) { @@ -685,7 +686,7 @@ export const App: React.FC = () => { case 'stop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) case 'forceStop': return runVMAction(name, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) case 'restart': return runVMAction(name, action, () => api.RestartVMWithDriver(actionDriverID, name)) - case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected')) + case 'eject': return runVMAction(name, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected')) case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished')) case 'enterRecovery': return runVMAction(name, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery')) case 'attachInstaller': return attachInstaller(name, isRunning) diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index 4288b21..7575a97 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -222,6 +222,10 @@ export function ShowMainWindow():Promise; export function GetVMInfo(arg1:string,arg2:string):Promise; +export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise; + +export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise; + export function StartVM(arg1:string):Promise; export function StartVMWithDriver(arg1:string,arg2:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 1f71da2..6b9b39a 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -426,6 +426,14 @@ export function GetVMInfo(arg1, arg2) { return window['go']['app']['App']['GetVMInfo'](arg1, arg2); } +export function EjectInstallerWithDriver(arg1, arg2) { + return window['go']['app']['App']['EjectInstallerWithDriver'](arg1, arg2); +} + +export function ReadVMLogsWithDriver(arg1, arg2, arg3) { + return window['go']['app']['App']['ReadVMLogsWithDriver'](arg1, arg2, arg3); +} + export function StartVM(arg1) { return window['go']['app']['App']['StartVM'](arg1); } diff --git a/internal/app/app.go b/internal/app/app.go index 64f26c7..25a8147 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1644,7 +1644,7 @@ func (a *App) restartVMLegacy(name string) (stopped bool, err error) { return true, a.StartVM(name) } -func (a *App) EjectInstaller(name string) error { +func (a *App) ejectInstallerLegacy(name string) error { c, err := a.client() if err != nil { return err @@ -1712,6 +1712,10 @@ func (a *App) OpenVMFolder(name string) error { } func (a *App) ReadVMLogs(name string, serial bool) (string, error) { + return a.ReadVMLogsWithDriver("", name, serial) +} + +func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) { c, err := a.client() if err != nil { return "", err diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 52b4660..c10f305 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -10,6 +10,7 @@ import ( "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" @@ -146,7 +147,15 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) { base := filepath.Base(path) a.emitVMLog(name, "Attaching installer image to "+name+": "+base) - if err := c.Insert(ctx, name, path, w, w); err != nil { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + if svc != nil { + _, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path}) + } else { + err = c.Insert(ctx, name, path, w, w) + } + if err != nil { return "", err } if a.isVMRunning(ctx, c, name, d) { @@ -339,7 +348,15 @@ func (a *App) UpgradeDiskToNVMe(name string) error { w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) ctx := context.Background() a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...") - if err := c.Set(ctx, reims.SetOpts{Name: name, DiskController: "nvme"}, w, w); err != nil { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + 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 a.isVMRunning(ctx, c, name, d) { diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index e3d0642..78b8ddd 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -184,6 +184,36 @@ func (a *App) StopVMWithDriver(driverID, name string, force bool) error { return nil } +func (a *App) EjectInstaller(name string) error { return a.EjectInstallerWithDriver("", name) } + +func (a *App) EjectInstallerWithDriver(driverID, name string) error { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + if svc == nil { + if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { + return errors.New("driver is unavailable without the plugin manager") + } + return a.ejectInstallerLegacy(name) + } + _, err := svc.InvokeAction(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, "eject", nil) + if err == nil { + a.wakePoll() + a.emitLifecycleStateChanged() + } + return err +} + +func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string, error) { + a.mu.Lock() + svc := a.lifecycleSvc + a.mu.Unlock() + if svc == nil { + return a.readVMLogsLegacy(name, serial) + } + return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial) +} + func (a *App) RestartVMWithDriver(driverID, name string) error { a.mu.Lock() svc := a.lifecycleSvc diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 16f82b7..6f0f591 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -587,13 +587,15 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e } return deleteVM(ctx, cfg, *driverID, fs.Arg(0), *keepFiles) case "eject": - if err := initReims(); err != nil { + fs := flag.NewFlagSet("vm eject", flag.ContinueOnError) + driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") + if err := fs.Parse(args[1:]); err != nil { return err } - if len(args) < 2 { - return fmt.Errorf("usage: reims-go vm eject ") + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm eject [--driver ] ") } - return client.Eject(ctx, args[1], os.Stdout, os.Stderr) + return actionVM(ctx, cfg, *driverID, fs.Arg(0), "eject", nil) case "type": if err := initReims(); err != nil { return err diff --git a/internal/cli/start.go b/internal/cli/start.go index 77470a8..bbc1629 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -50,6 +50,17 @@ func startVMWithDriver(ctx context.Context, cfg *config.Config, driverID, name s return err } +func actionVM(ctx context.Context, cfg *config.Config, driverID, name, action string, params 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) + _, 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 { mgr, router, err := openCLIPluginManager(cfg, false) if err != nil { diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 4e93c9f..db209f3 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -138,6 +138,11 @@ type ActionDriver interface { InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) } +// LogDriver exposes driver-owned serial and QEMU logs. +type LogDriver interface { + ReadLogs(context.Context, string, bool) (string, error) +} + // RenamedDriverIDs maps a driver ID that VM owner markers may still carry // to the ID that now provides that driver, for when a driver moves to // another plugin (e.g. the built-in macOS driver becoming a market plugin, diff --git a/internal/lifecycle/lifecycle.go b/internal/lifecycle/lifecycle.go index 5822fe7..f31784c 100644 --- a/internal/lifecycle/lifecycle.go +++ b/internal/lifecycle/lifecycle.go @@ -97,6 +97,30 @@ func (s *Service) StartNamed(ctx context.Context, driverID, name string, stdout, return s.Start(ctx, driver.VMRef{DriverID: driverID, Name: name}, stdout, stderr) } +func (s *Service) InvokeAction(ctx context.Context, ref driver.VMRef, action string, params map[string]any) (any, error) { + d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name) + if err != nil { + return nil, err + } + actions, ok := d.(driver.ActionDriver) + if !ok { + return nil, fmt.Errorf("driver %q does not support action %q", d.ID(), action) + } + return actions.InvokeAction(ctx, vm.Name, action, params) +} + +func (s *Service) ReadLogs(ctx context.Context, ref driver.VMRef, serial bool) (string, error) { + d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name) + if err != nil { + return "", err + } + logs, ok := d.(driver.LogDriver) + if !ok { + return "", fmt.Errorf("driver %q does not expose VM logs", d.ID()) + } + return logs.ReadLogs(ctx, vm.Name, serial) +} + func (s *Service) Delete(ctx context.Context, ref driver.VMRef, keepFiles bool, stdout, stderr io.Writer) error { d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name) if err != nil { diff --git a/internal/lifecycle/lifecycle_test.go b/internal/lifecycle/lifecycle_test.go index 83cb43a..306e7c2 100644 --- a/internal/lifecycle/lifecycle_test.go +++ b/internal/lifecycle/lifecycle_test.go @@ -57,6 +57,13 @@ func (d *testDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) e } func (d *testDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } + +func (d *testDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) { return action, nil } +func (d *testDriver) ReadLogs(_ context.Context, _ string, serial bool) (string, error) { + if serial { return "serial-log", nil } + return "qemu-log", nil +} + func registerTestDriver(t *testing.T, reg *plugin.Registry, d *testDriver) { t.Helper() if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: d.id + ".plugin", Version: "1.0.0"}, @@ -84,6 +91,8 @@ func TestSecondDriverListStartStop(t *testing.T) { if err := svc.Set(context.Background(), driver.NewVMRef(drv.id, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil { t.Fatal(err) } + if got, err := svc.InvokeAction(context.Background(), driver.NewVMRef(drv.id, "ubuntu"), "eject", nil); err != nil || got != "eject" { t.Fatalf("InvokeAction = %v, %v", got, err) } + if got, err := svc.ReadLogs(context.Background(), driver.NewVMRef(drv.id, "ubuntu"), true); err != nil || got != "serial-log" { t.Fatalf("ReadLogs = %q, %v", got, err) } if err := svc.Stop(context.Background(), driver.NewVMRef(drv.id, "ubuntu"), false, io.Discard, io.Discard); err != nil { t.Fatal(err) } diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index 1879c32..7516212 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -258,6 +258,42 @@ func (d *ReimsMacOSDriver) Delete(ctx context.Context, name string, keepFiles bo return c.Delete(ctx, name, keepFiles, stdout, stderr) } +func (d *ReimsMacOSDriver) InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) { + c, err := d.client() + if err != nil { + return nil, err + } + switch action { + case "eject": + return nil, c.Eject(ctx, vmName, io.Discard, io.Discard) + case "insert": + path, _ := params["path"].(string) + if path == "" { + return nil, fmt.Errorf("insert requires a non-empty path") + } + return nil, c.Insert(ctx, vmName, path, io.Discard, io.Discard) + case "upgrade_nvme": + det, err := c.Show(ctx, vmName) + if err != nil { + return nil, err + } + if det.HasInstaller { + return nil, fmt.Errorf("exit recovery mode before switching disk controller") + } + return nil, c.Set(ctx, reims.SetOpts{Name: vmName, DiskController: "nvme"}, io.Discard, io.Discard) + default: + return nil, fmt.Errorf("unknown macOS action %q", action) + } +} + +func (d *ReimsMacOSDriver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) { + c, err := d.client() + if err != nil { + return "", err + } + return c.ReadLogs(ctx, name, serial) +} + func decodeMap(m map[string]any, dst any) error { if len(m) == 0 { return nil