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.
This commit is contained in:
1 parent
25766a9cdb
commit
7ba5e3fa9c
26 files changed
+1038
-357
No files matched your search
@@ -81,7 +81,7 @@ flowchart TB
|
||||
## 4. 关键机制与安全边界
|
||||
|
||||
### 4.1 启动编排与单实例交接
|
||||
- `internal/vmstart` 承载 GUI 与 CLI 共用的启动步骤;只有常驻进程才能维持的能力(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` 启动隐藏到托盘的后台界面进程,结果经 `<DataRoot>\tmp\cli-start-*.json` 回传并带退出码返回。交接同时携带 `--start-driver=`,裸名称不再作为跨驱动的完整身份。
|
||||
- 仅在 CLI 显式指定 `--data-root` 时由命令进程直接启动,此时不包含 Guest Tools 桥接与 Win10 冷重启监视。
|
||||
- `reims-go.exe` 编译为 Windows GUI 子系统程序,命令行模式下保留调用方管道/文件句柄,缺失时通过 `AttachConsole` 挂载父控制台;在交互式 PowerShell/cmd 中加 `| Out-Host` 可等待命令执行完毕。
|
||||
|
||||
@@ -119,7 +119,7 @@ GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁
|
||||
|
||||
### 步骤 2:VM 引用与启动链路
|
||||
|
||||
**2a. `VMRef` 贯穿宿主(已落地)**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
|
||||
**2a. `VMRef` 身份、内部索引与 list/start/stop 用户入口已落地**(原计划在步骤 3,提前是因为统一启动入口就要按归属解析 VM)
|
||||
|
||||
- 引入 `VMRef{DriverID, Name}`;`Router.ResolveVM` 遇到多个同名结果时返回歧义错误;`ListAllVMs` 不再按名称去重。
|
||||
- 驱动在清单中声明 VM 根目录(第 3 节),路由与"驱动不可用"扫描遍历所有已声明的根。
|
||||
@@ -127,7 +127,7 @@ GUI 启动、首次设置、`SetDataRoot`、CLI 各自打开数据目录;迁
|
||||
- `PluginRecord.VMSettings` 的键改为 `VMRef` 的规范字符串,随版本 v3 迁移:已有键全部归属 `builtin.driver.reims-macos`。
|
||||
- 界面进程交接参数增加驱动;只给名称且不重名时仍可用。
|
||||
|
||||
**2b. 驱动自有准备与第三方意图分开**
|
||||
**2b. 驱动自有准备与第三方意图分开(启动链路已落地,Guest Tools 拆分待完成)**
|
||||
|
||||
- `Driver.Start` 改为接收启动请求:`VMRef`、第三方插件经 `vm.beforeStart` 给出的意图(参数片段、环境变量、启动后动作),以及日志输出。
|
||||
- 启动前检查(WHPX、运行时兼容)与启动准备由驱动自己完成。macOS 的离线辅助盘、恢复启动、引导语言、WHPX 兼容降级、Win10 冷重启、Guest Tools 辅助盘从 `vm.beforeStart` 移入 macOS 驱动的 `Start`,"先准备恢复环境,再写引导语言"的顺序由驱动保证。
|
||||
|
||||
@@ -271,7 +271,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
|
||||
| :--- | :--- | :--- |
|
||||
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
|
||||
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
|
||||
| `builtin.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 启动准备与冷重启 Hook + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.guest.macos` | `internal/macos/guest`、`internal/macos/installguide`、`macosdriver`、`vmstart.Prepare` 各步骤 | 静态 `guestDrivers` + `host.preflight` + 驱动内启动准备与冷重启意图 + 条件提供的 `ui.install-guide` 服务;设置 `install_guide`、`whpx_fallback`、`win10_cold_reboot` |
|
||||
| `builtin.core`(系统插件) | `internal/plugin/builtin/core.go` | `themes`:默认主题 |
|
||||
|
||||
> 下一步:Guest Tools 的 macOS 客体代理与辅助盘镜像迁入 macOS 插件,传输服务留在宿主;启动准备改由驱动自己执行。见 [guest-plugin-migration.md](guest-plugin-migration.md) 步骤 2。
|
||||
|
||||
+19
-16
@@ -195,8 +195,8 @@ export const App: React.FC = () => {
|
||||
setLoadError('')
|
||||
setSelected((cur) => {
|
||||
if (PAGE_IDS.includes(cur)) return cur
|
||||
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
|
||||
if ((s.vms ?? []).some((v) => vmRefKey(v) === cur || v.name === cur)) return cur
|
||||
return s.vms && s.vms.length > 0 ? vmRefKey(s.vms[0]) : HOST_ID
|
||||
})
|
||||
if (reloadDetail) setDetailRevision((revision) => revision + 1)
|
||||
} catch (e) {
|
||||
@@ -267,13 +267,13 @@ export const App: React.FC = () => {
|
||||
const vms = state?.vms ?? []
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[vmRefKey(v)] ?? v.state) === 'running').length
|
||||
const selectedVM = !PAGE_IDS.includes(selected)
|
||||
? vms.find((v) => v.name === selected)
|
||||
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], detailRevision])
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, state?.transitions[selectedVM ? vmRefKey(selectedVM) : ''], detailRevision])
|
||||
|
||||
// Display names (the VM's note, .reims-go-note): shown in place of the VM's
|
||||
// name in the sidebar and page title; the name itself stays the identifier.
|
||||
@@ -661,6 +661,9 @@ export const App: React.FC = () => {
|
||||
}
|
||||
|
||||
const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => {
|
||||
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
const actionDriverID = actionVM?.driver_id ?? ''
|
||||
name = actionVM?.name ?? name
|
||||
const activeBusy = activeVMBusy(name)
|
||||
if (
|
||||
activeBusy
|
||||
@@ -671,7 +674,7 @@ export const App: React.FC = () => {
|
||||
return
|
||||
}
|
||||
switch (action) {
|
||||
case 'start': return runVMAction(name, action, () => api.StartVM(name))
|
||||
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
|
||||
case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e))
|
||||
case 'fullscreen':
|
||||
return runVMAction(name, action, async () => {
|
||||
@@ -679,8 +682,8 @@ export const App: React.FC = () => {
|
||||
refreshVMStats(name, { window_fullscreen: isFullscreen })
|
||||
})
|
||||
case 'screenshot': return runVMAction(name, action, () => api.CopyVMScreenshot(name), tr('toastScreenshotCopied'))
|
||||
case 'stop': return runVMAction(name, action, () => api.StopVM(name, false), tr('toastStopped', { name }))
|
||||
case 'forceStop': return runVMAction(name, action, () => api.StopVM(name, true), tr('toastStopped', { name }))
|
||||
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.RestartVM(name))
|
||||
case 'eject': return runVMAction(name, action, () => api.EjectInstaller(name), tr('toastEjected'))
|
||||
case 'finishInstall': return runVMAction(name, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished'))
|
||||
@@ -706,16 +709,16 @@ export const App: React.FC = () => {
|
||||
|
||||
const onVMAction = (action: VMAction) => {
|
||||
if (!selectedVM) return
|
||||
return onVMActionFor(selectedVM.name, action, selectedVM.state === 'running')
|
||||
return onVMActionFor(vmRefKey(selectedVM), action, selectedVM.state === 'running')
|
||||
}
|
||||
|
||||
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
if (action === 'settings') {
|
||||
setSelected(name)
|
||||
api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
|
||||
return
|
||||
}
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
|
||||
onVMActionFor(name, action, st === 'running')
|
||||
}
|
||||
@@ -723,11 +726,11 @@ export const App: React.FC = () => {
|
||||
// The state's own main action (Start, or Show Window while running), shared by
|
||||
// Ctrl+Enter and a double-click in the sidebar.
|
||||
const primaryAction = (name: string) => {
|
||||
const vm = vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(name)) return
|
||||
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(name, 'start', false)
|
||||
else if (st === 'running') onVMActionFor(name, 'focus', true)
|
||||
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
|
||||
if (!vm || activeVMBusy(vm.name)) return
|
||||
const st = state?.transitions[vmRefKey(vm)] ?? vm.state
|
||||
if (st === 'stopped') onVMActionFor(vmRefKey(vm), 'start', false)
|
||||
else if (st === 'running') onVMActionFor(vmRefKey(vm), 'focus', true)
|
||||
}
|
||||
|
||||
const confirmDelete = (keepFiles: boolean) => {
|
||||
@@ -871,7 +874,7 @@ export const App: React.FC = () => {
|
||||
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
|
||||
else if (k === 'l') { e.preventDefault(); toggleLogs() }
|
||||
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) }
|
||||
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(vmRefKey(selectedVM)) }
|
||||
}
|
||||
useEffect(() => {
|
||||
const h = (e: KeyboardEvent) => shortcutRef.current(e)
|
||||
|
||||
@@ -50,7 +50,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -124,17 +124,17 @@ export const Sidebar: React.FC<Props> = ({
|
||||
const vmBusy = !!busyAction
|
||||
const label = displayNames[vm.name] || vm.name
|
||||
const trigger = navBtn(
|
||||
vm.name,
|
||||
vmRefKey(vm),
|
||||
label,
|
||||
<VersionArt shape="tile" major={macosMajors[vm.name] ?? null} name={label} />,
|
||||
'nav-icon-art',
|
||||
t(locale, `state_${st}` as I18nKey),
|
||||
statusKind(st),
|
||||
onActivate ? () => onActivate(vm.name) : undefined,
|
||||
onActivate ? () => onActivate(vmRefKey(vm)) : undefined,
|
||||
)
|
||||
if (!onVMContextAction) return trigger
|
||||
return (
|
||||
<Ctx.Root key={vm.name}>
|
||||
<Ctx.Root key={vmRefKey(vm)}>
|
||||
<Ctx.Trigger
|
||||
asChild
|
||||
onContextMenu={(e) => {
|
||||
@@ -156,51 +156,51 @@ export const Sidebar: React.FC<Props> = ({
|
||||
}}
|
||||
>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'start')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'start')}>
|
||||
<Play size={14} /> {tr('start')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
{running && (
|
||||
<>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'focus')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
|
||||
<AppWindow size={14} /> {tr('showWindow')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'fullscreen')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'fullscreen')}>
|
||||
<Maximize2 size={14} /> {tr('toggleFullscreen')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'screenshot')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
|
||||
<Camera size={14} /> {tr('copyScreenshot')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'stop')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
|
||||
<Square size={14} /> {tr('stop')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'restart')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'restart')}>
|
||||
<RotateCw size={14} /> {tr('restart')}
|
||||
</Ctx.Item>
|
||||
</>
|
||||
)}
|
||||
{(running || transitioning) && (
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vm.name, 'forceStop')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onVMContextAction(vmRefKey(vm), 'forceStop')}>
|
||||
<Power size={14} /> {tr('forceStop')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'settings')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
|
||||
<Settings size={14} /> {tr('settingsEllipsis')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openSharedFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openSharedFolder')}
|
||||
</Ctx.Item>
|
||||
{stopped && (
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vm.name, 'cloneVM')}>
|
||||
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'cloneVM')}>
|
||||
<CopyPlus size={14} /> {tr('cloneVM')}
|
||||
</Ctx.Item>
|
||||
)}
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vm.name, 'openFolder')}>
|
||||
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openFolder')}>
|
||||
<FolderOpen size={14} /> {tr('openFolder')}
|
||||
</Ctx.Item>
|
||||
<Ctx.Separator className="menu-sep" />
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || transitioning} onSelect={() => onVMContextAction(vm.name, 'delete')}>
|
||||
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
|
||||
<Trash size={14} /> {tr('delete')}
|
||||
</Ctx.Item>
|
||||
</Ctx.Content>
|
||||
|
||||
Vendored
+4
@@ -222,6 +222,10 @@ export function ShowMainWindow():Promise<void>;
|
||||
|
||||
export function StartVM(arg1:string):Promise<void>;
|
||||
|
||||
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
|
||||
|
||||
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
|
||||
|
||||
@@ -426,6 +426,14 @@ export function StartVM(arg1) {
|
||||
return window['go']['app']['App']['StartVM'](arg1);
|
||||
}
|
||||
|
||||
export function StartVMWithDriver(arg1, arg2) {
|
||||
return window['go']['app']['App']['StartVMWithDriver'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StopVMWithDriver(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['StopVMWithDriver'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function StopVM(arg1, arg2) {
|
||||
return window['go']['app']['App']['StopVM'](arg1, arg2);
|
||||
}
|
||||
|
||||
+15
-2
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
|
||||
@@ -109,6 +110,7 @@ type App struct {
|
||||
pluginMgr *plugin.Manager
|
||||
pluginMarket *plugin.MarketClient
|
||||
driverRouter *driver.Router
|
||||
lifecycleSvc *vmlifecycle.Service
|
||||
runtimeKinds *rt.KindRegistry
|
||||
uiHealth uiHealthState
|
||||
themeMode installguide.Theme
|
||||
@@ -487,6 +489,17 @@ func (a *App) client() (*reims.Client, error) {
|
||||
}
|
||||
|
||||
func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc != nil {
|
||||
vms, err := svc.List(ctx)
|
||||
out := make([]reims.VMListItem, 0, len(vms))
|
||||
for _, vm := range vms {
|
||||
out = append(out, reims.VMListItem{Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1378,7 +1391,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error {
|
||||
func (a *App) startVMLegacy(name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1530,7 +1543,7 @@ func (a *App) StartVM(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) StopVM(name string, force bool) error {
|
||||
func (a *App) stopVMLegacy(name string, force bool) error {
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func (a *App) emitLifecycleStateChanged() {
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) emitVMLogForDriver(driverID, name, line string) {
|
||||
a.emitLog(vmKeyForDriver(driverID, name), line)
|
||||
}
|
||||
|
||||
func (a *App) startHookPayload(_ context.Context, d driver.Driver, vm driver.VMInfo, base plugin.BeforeStartPayload) (plugin.BeforeStartPayload, error) {
|
||||
if d.ID() != builtin.IDDriverReimsMacOS {
|
||||
return base, nil
|
||||
}
|
||||
prep, err := a.prep(vm.Name)
|
||||
if err != nil {
|
||||
return base, err
|
||||
}
|
||||
caps := prep.Runtime.Manifest.EffectiveCapabilities()
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
base.RuntimeKind = prep.Runtime.Manifest.EffectiveKind()
|
||||
base.RuntimeCaps = caps
|
||||
base.HostFacts = buildHostFacts(rep, caps)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
func (a *App) currentDataRoot() string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.cfg.DataRoot
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error { return a.StartVMWithDriver("", name) }
|
||||
|
||||
func (a *App) StartVMWithDriver(driverID, name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
return a.startVMLegacy(name)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
var detail reims.VMDetail
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
detail, err = a.GetVMDetail(ref.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "starting"
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
startAt := time.Now()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
rep := host.Inspect(a.currentDataRoot())
|
||||
a.emitStartSummary(ref.Name, detail, rep, "")
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Starting "+ref.Name+"...")
|
||||
result, err := svc.Start(context.Background(), ref, w, w)
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Start error: "+err.Error())
|
||||
a.emitLifecycleStateChanged()
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind != "qmp.watch_cold_reboot" {
|
||||
continue
|
||||
}
|
||||
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
||||
a.watchWin10ColdReboot(ref.Name, addr)
|
||||
}
|
||||
}
|
||||
a.startVMMonitor(ref.Name, detail, startAt)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) StopVM(name string, force bool) error { return a.StopVMWithDriver("", name, force) }
|
||||
|
||||
func (a *App) StopVMWithDriver(driverID, name string, force bool) 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.stopVMLegacy(name, force)
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "stopping"
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Stop(context.Background(), ref, force, w, w); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
type appSecondDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
starts, stops int
|
||||
}
|
||||
|
||||
func (d *appSecondDriver) ID() string { return d.id }
|
||||
func (d *appSecondDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
|
||||
func (d *appSecondDriver) RuntimeKind() string { return "test-runtime" }
|
||||
func (d *appSecondDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
||||
func (d *appSecondDriver) Capabilities() []string { return nil }
|
||||
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil }
|
||||
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
||||
for _, vm := range d.vms {
|
||||
if vm.Name == name {
|
||||
return vm, nil
|
||||
}
|
||||
}
|
||||
return driver.VMInfo{}, os.ErrNotExist
|
||||
}
|
||||
func (d *appSecondDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
|
||||
d.starts++
|
||||
return driver.StartResult{}, nil
|
||||
}
|
||||
func (d *appSecondDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.stops++
|
||||
return nil
|
||||
}
|
||||
func (d *appSecondDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestAppSecondDriverUserEntry(t *testing.T) {
|
||||
const driverID = "test.driver.linux"
|
||||
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}}
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
|
||||
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, driverID, drv)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
router := driver.NewRouter(reg, nil)
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, router, nil),
|
||||
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
|
||||
vms, err := a.listVMsInternal(context.Background())
|
||||
if err != nil || len(vms) != 1 || vms[0].DriverID != driverID {
|
||||
t.Fatalf("list = %+v, %v", vms, err)
|
||||
}
|
||||
if err := a.StartVMWithDriver(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.StopVMWithDriver(driverID, "ubuntu", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.startHandedVM(driverID, "ubuntu"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if drv.starts != 2 || drv.stops != 1 {
|
||||
t.Fatalf("starts=%d stops=%d", drv.starts, drv.stops)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
@@ -201,6 +202,7 @@ func (a *App) initPlugins() {
|
||||
a.mu.Lock()
|
||||
a.pluginMgr = mgr
|
||||
a.driverRouter = drvRouter
|
||||
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
|
||||
a.runtimeKinds = kindReg
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -216,6 +218,8 @@ func (a *App) shutdownPlugins() {
|
||||
mgr := a.pluginMgr
|
||||
a.pluginMgr = nil
|
||||
a.pluginMarket = nil
|
||||
a.lifecycleSvc = nil
|
||||
a.driverRouter = nil
|
||||
a.mu.Unlock()
|
||||
i18n.SetPluginCatalogs(nil)
|
||||
if mgr != nil {
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/wailsapp/wails/v2/pkg/options"
|
||||
)
|
||||
|
||||
@@ -72,11 +71,7 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
|
||||
}
|
||||
|
||||
func (a *App) startHandedVM(driverID, name string) error {
|
||||
ref := driver.NewVMRef(driverID, name)
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("VM %q belongs to driver %q; its lifecycle is not available in the legacy window starter", name, ref.DriverID)
|
||||
}
|
||||
return a.StartVM(name)
|
||||
return a.StartVMWithDriver(driverID, name)
|
||||
}
|
||||
|
||||
// logCapture keeps the last few log lines one source emits while it is
|
||||
|
||||
+53
-13
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installer"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
@@ -375,16 +376,31 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
|
||||
}
|
||||
prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
var prep *vmstart.Prep
|
||||
var client *reims.Client
|
||||
var active *rt.Installed
|
||||
initReims := func() error {
|
||||
if prep != nil {
|
||||
return nil
|
||||
}
|
||||
p, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prep, client, active = p, p.Client, &p.Runtime
|
||||
return nil
|
||||
}
|
||||
client, active := prep.Client, &prep.Runtime
|
||||
ctx := context.Background()
|
||||
|
||||
switch args[0] {
|
||||
case "list":
|
||||
vms, err := client.ListRaw(ctx)
|
||||
mgr, router, err := openCLIPluginManager(cfg, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mgr.Close()
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
vms, err := svc.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -443,11 +459,16 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
return err
|
||||
}
|
||||
if *start {
|
||||
return drv.Start(ctx, name, os.Stdout, os.Stderr)
|
||||
svc := lifecycle.New(mgr.Registry(), router, nil)
|
||||
_, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
startAfterCreate := *start
|
||||
if err := initReims(); err != nil {
|
||||
return err
|
||||
}
|
||||
opts := reims.CreateOpts{
|
||||
Name: name,
|
||||
Dir: *dir,
|
||||
@@ -490,7 +511,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
}
|
||||
}
|
||||
if startAfterCreate {
|
||||
if err := startVM(ctx, cfg, prep, name, viaWindow); err != nil {
|
||||
if err := startVM(ctx, cfg, name, viaWindow); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -500,6 +521,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
fmt.Println(i18n.T(loc, "vm.install_guide.step3", name))
|
||||
return nil
|
||||
case "set":
|
||||
if err := initReims(); err != nil {
|
||||
return err
|
||||
}
|
||||
fs := flag.NewFlagSet("vm set", flag.ContinueOnError)
|
||||
cpus := fs.Int("cpus", 0, "vCPU count")
|
||||
mem := fs.String("memory", "", "RAM size")
|
||||
@@ -538,21 +562,37 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
}
|
||||
return nil
|
||||
case "start":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm start <name>")
|
||||
fs := flag.NewFlagSet("vm start", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return startVM(ctx, cfg, prep, args[1], viaWindow)
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm start [--driver <id>] <name>")
|
||||
}
|
||||
return startVMWithDriver(ctx, cfg, *driverID, fs.Arg(0), viaWindow)
|
||||
case "stop":
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
|
||||
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
|
||||
if fs.NArg() < 1 {
|
||||
return fmt.Errorf("usage: reims-go vm stop [--driver <id>] <name>")
|
||||
}
|
||||
return stopVM(ctx, cfg, *driverID, fs.Arg(0), false)
|
||||
case "eject":
|
||||
if err := initReims(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm eject <name>")
|
||||
}
|
||||
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
|
||||
case "type":
|
||||
if err := initReims(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Paste as keystrokes: the text argument, else stdin.
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
||||
|
||||
+21
-39
@@ -12,11 +12,8 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/macos/guest"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
)
|
||||
|
||||
// startHandoffTimeout bounds how long `vm start` waits for the window to
|
||||
@@ -31,51 +28,36 @@ const startHandoffTimeout = 5 * time.Minute
|
||||
//
|
||||
// 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, prep *vmstart.Prep, name string, viaWindow bool) error {
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
d, err := prep.Client.Show(ctx, name)
|
||||
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
|
||||
}
|
||||
if d.State == "running" {
|
||||
// Preparation rewrites extra-args and the OpenCore image; never under a live VM.
|
||||
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
|
||||
}
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := prep.CheckMemory(d.Memory, rep); err != nil {
|
||||
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, driver.BuiltinReimsMacOSDriverID, name)
|
||||
return startInWindow(ctx, cfg, vm.DriverID, vm.Name)
|
||||
}
|
||||
_, err = svc.Start(ctx, vm.Ref(), os.Stdout, os.Stderr)
|
||||
return err
|
||||
}
|
||||
|
||||
// Honour the core plugin's WHPX setting, as the window does.
|
||||
st := plugin.ReadState(cfg.DataRoot)
|
||||
prep.SkipWHPXFallback = !guest.SettingOnInState(st, guest.SettingWHPXFallback)
|
||||
prep.Prepare(ctx, name, rep, &d)
|
||||
if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
}); err != nil {
|
||||
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
|
||||
}
|
||||
vms, err := prep.Client.List(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
|
||||
vmDir := vm.Dir
|
||||
if vmDir == "" {
|
||||
vmDir = d.Directory
|
||||
}
|
||||
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
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 {
|
||||
|
||||
@@ -88,6 +88,21 @@ type SetRequest struct {
|
||||
Changes map[string]any `json:"changes,omitempty"`
|
||||
}
|
||||
|
||||
// StartRequest carries a VM reference, third-party start intents and log sinks.
|
||||
// Disk preparation belongs to the driver and runs only after hooks have finished.
|
||||
type StartRequest struct {
|
||||
Ref VMRef
|
||||
Intents []plugin.StartIntent
|
||||
ActivePlugins map[string]bool
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
}
|
||||
|
||||
// StartResult contains host-controlled actions to run after a successful start.
|
||||
type StartResult struct {
|
||||
PostStart []plugin.PostStartAction
|
||||
}
|
||||
|
||||
// Driver is the core contract implemented by both builtin.driver.reims-macos
|
||||
// and external L3 Sidecar guest drivers (such as Linux) (§5.3).
|
||||
type Driver interface {
|
||||
@@ -105,7 +120,7 @@ type Driver interface {
|
||||
Create(ctx context.Context, req CreateRequest, stdout, stderr io.Writer) error
|
||||
ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue
|
||||
Set(ctx context.Context, req SetRequest, stdout, stderr io.Writer) error
|
||||
Start(ctx context.Context, name string, stdout, stderr io.Writer) error
|
||||
Start(ctx context.Context, req StartRequest) (StartResult, error)
|
||||
Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error
|
||||
Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []Validation
|
||||
func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil }
|
||||
func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil }
|
||||
func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil }
|
||||
func (f *fakeDriver) Start(context.Context, string, io.Writer, io.Writer) error { return nil }
|
||||
func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { return StartResult{}, nil }
|
||||
func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
|
||||
func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
|
||||
|
||||
|
||||
@@ -28,11 +28,13 @@ func NewSidecarDriver(contrib plugin.GuestDriverContribution, sup *plugin.Sideca
|
||||
}
|
||||
}
|
||||
|
||||
func (d *SidecarDriver) ID() string { return d.contrib.ID }
|
||||
func (d *SidecarDriver) DisplayName() plugin.LocalizedText { return d.contrib.Name }
|
||||
func (d *SidecarDriver) RuntimeKind() string { return d.contrib.RuntimeKind }
|
||||
func (d *SidecarDriver) RuntimeAPIRange() string { return d.contrib.RuntimeAPIRange }
|
||||
func (d *SidecarDriver) Capabilities() []string { return append([]string(nil), d.contrib.Capabilities...) }
|
||||
func (d *SidecarDriver) ID() string { return d.contrib.ID }
|
||||
func (d *SidecarDriver) DisplayName() plugin.LocalizedText { return d.contrib.Name }
|
||||
func (d *SidecarDriver) RuntimeKind() string { return d.contrib.RuntimeKind }
|
||||
func (d *SidecarDriver) RuntimeAPIRange() string { return d.contrib.RuntimeAPIRange }
|
||||
func (d *SidecarDriver) Capabilities() []string {
|
||||
return append([]string(nil), d.contrib.Capabilities...)
|
||||
}
|
||||
func (d *SidecarDriver) CreateSchema() *plugin.SettingsSchema { return d.contrib.CreateSchema }
|
||||
func (d *SidecarDriver) SettingsSchema() *plugin.SettingsSchema { return d.contrib.SettingsSchema }
|
||||
|
||||
@@ -137,19 +139,21 @@ func (d *SidecarDriver) Set(ctx context.Context, req SetRequest, stdout, _ io.Wr
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *SidecarDriver) Start(ctx context.Context, name string, stdout, _ io.Writer) error {
|
||||
func (d *SidecarDriver) Start(ctx context.Context, req StartRequest) (StartResult, error) {
|
||||
var resp struct {
|
||||
Logs []string `json:"logs"`
|
||||
Logs []string `json:"logs"`
|
||||
PostStart []plugin.PostStartAction `json:"post_start"`
|
||||
}
|
||||
if err := d.sup.Call(ctx, "driver/start", map[string]any{"name": name}, &resp); err != nil {
|
||||
return err
|
||||
payload := map[string]any{"name": req.Ref.Name, "ref": req.Ref, "intents": req.Intents}
|
||||
if err := d.sup.Call(ctx, "driver/start", payload, &resp); err != nil {
|
||||
return StartResult{}, err
|
||||
}
|
||||
for _, l := range resp.Logs {
|
||||
if stdout != nil {
|
||||
_, _ = fmt.Fprintln(stdout, l)
|
||||
if req.Stdout != nil {
|
||||
_, _ = fmt.Fprintln(req.Stdout, l)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return StartResult{PostStart: resp.PostStart}, nil
|
||||
}
|
||||
|
||||
func (d *SidecarDriver) Stop(ctx context.Context, name string, force bool, stdout, _ io.Writer) error {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Package lifecycle provides the single driver-routed VM lifecycle used by GUI and CLI.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
type PayloadFn func(context.Context, driver.Driver, driver.VMInfo, plugin.BeforeStartPayload) (plugin.BeforeStartPayload, error)
|
||||
|
||||
type Service struct {
|
||||
reg *plugin.Registry
|
||||
router *driver.Router
|
||||
payloadFn PayloadFn
|
||||
}
|
||||
|
||||
func New(reg *plugin.Registry, router *driver.Router, payloadFn PayloadFn) *Service {
|
||||
return &Service{reg: reg, router: router, payloadFn: payloadFn}
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context) ([]driver.VMInfo, error) { return s.router.ListAllVMs(ctx) }
|
||||
|
||||
func (s *Service) Resolve(ctx context.Context, driverID, name string) (driver.Driver, driver.VMInfo, error) {
|
||||
if driverID != "" {
|
||||
return s.router.ResolveRef(ctx, driver.NewVMRef(driverID, name))
|
||||
}
|
||||
return s.router.ResolveVM(ctx, name)
|
||||
}
|
||||
|
||||
func defaultPayload(d driver.Driver, vm driver.VMInfo) plugin.BeforeStartPayload {
|
||||
p := plugin.BeforeStartPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID(),
|
||||
RuntimeKind: d.RuntimeKind(), VMCaps: d.Capabilities(), State: vm.State}
|
||||
if vm.DriverData != nil {
|
||||
p.ExtraArgs, _ = vm.DriverData["extra_args"].(string)
|
||||
p.HasInstaller, _ = vm.DriverData["has_installer"].(bool)
|
||||
p.InstallerPath, _ = vm.DriverData["installer_path"].(string)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (s *Service) Start(ctx context.Context, ref driver.VMRef, stdout, stderr io.Writer) (driver.StartResult, error) {
|
||||
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
ref = vm.Ref()
|
||||
payload := defaultPayload(d, vm)
|
||||
if s.payloadFn != nil {
|
||||
var payloadErr error
|
||||
payload, payloadErr = s.payloadFn(ctx, d, vm, payload)
|
||||
if payloadErr != nil {
|
||||
return driver.StartResult{}, payloadErr
|
||||
}
|
||||
}
|
||||
var intents []plugin.StartIntent
|
||||
var active map[string]bool
|
||||
if s.reg != nil {
|
||||
active = s.reg.ActivePluginIDs()
|
||||
intents, err = s.reg.Hooks().DispatchBeforeStart(ctx, payload)
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
}
|
||||
result, err := d.Start(ctx, driver.StartRequest{Ref: ref, Intents: intents, ActivePlugins: active, Stdout: stdout, Stderr: stderr})
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
if s.reg != nil {
|
||||
ev := plugin.VMEventPayload{VMName: ref.Name, VMDir: vm.Directory, DriverID: ref.DriverID}
|
||||
for _, action := range result.PostStart {
|
||||
if action.Kind == "qmp.watch_cold_reboot" {
|
||||
ev.QMPAddr, _ = action.Params["qmp_addr"].(string)
|
||||
}
|
||||
}
|
||||
s.reg.Hooks().DispatchObserve(plugin.EventVMAfterStart, ev)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) StartNamed(ctx context.Context, driverID, name string, stdout, stderr io.Writer) (driver.StartResult, error) {
|
||||
return s.Start(ctx, driver.VMRef{DriverID: driverID, Name: name}, stdout, stderr)
|
||||
}
|
||||
|
||||
func (s *Service) Stop(ctx context.Context, ref driver.VMRef, force bool, stdout, stderr io.Writer) error {
|
||||
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.reg != nil {
|
||||
s.reg.Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID()})
|
||||
}
|
||||
if err := d.Stop(ctx, ref.Name, force, stdout, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.reg != nil {
|
||||
s.reg.Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID()})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
type testDriver struct {
|
||||
id string
|
||||
vms []driver.VMInfo
|
||||
starts, stops int
|
||||
}
|
||||
|
||||
func (d *testDriver) ID() string { return d.id }
|
||||
func (d *testDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
|
||||
func (d *testDriver) RuntimeKind() string { return "test-runtime" }
|
||||
func (d *testDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
||||
func (d *testDriver) Capabilities() []string { return nil }
|
||||
func (d *testDriver) CreateSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *testDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
|
||||
func (d *testDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil }
|
||||
func (d *testDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
|
||||
for _, vm := range d.vms {
|
||||
if vm.Name == name {
|
||||
return vm, nil
|
||||
}
|
||||
}
|
||||
return driver.VMInfo{}, os.ErrNotExist
|
||||
}
|
||||
func (d *testDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *testDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
func (d *testDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
|
||||
return nil
|
||||
}
|
||||
func (d *testDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error { return nil }
|
||||
func (d *testDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
|
||||
d.starts++
|
||||
return driver.StartResult{}, nil
|
||||
}
|
||||
func (d *testDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
|
||||
d.stops++
|
||||
return nil
|
||||
}
|
||||
func (d *testDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return 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"},
|
||||
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
reg.RegisterGuestDriver(sc, d.id, d)
|
||||
return nil
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecondDriverListStartStop(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
drv := &testDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "ubuntu", DriverID: "test.driver.linux", State: "stopped"}}}
|
||||
registerTestDriver(t, reg, drv)
|
||||
reg.Reconcile(context.Background())
|
||||
svc := New(reg, driver.NewRouter(reg, nil), nil)
|
||||
vms, err := svc.List(context.Background())
|
||||
if err != nil || len(vms) != 1 || vms[0].DriverID != drv.id {
|
||||
t.Fatalf("List = %+v, %v", vms, err)
|
||||
}
|
||||
if _, err := svc.StartNamed(context.Background(), "", "ubuntu", io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.Stop(context.Background(), driver.NewVMRef(drv.id, "ubuntu"), false, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if drv.starts != 1 || drv.stops != 1 {
|
||||
t.Fatalf("starts=%d stops=%d", drv.starts, drv.stops)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVetoLeavesVMFilesUntouched(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
vmDir := t.TempDir()
|
||||
drv := &testDriver{id: "test.driver.macos", vms: []driver.VMInfo{{Name: "mac", DriverID: "test.driver.macos", Directory: vmDir, State: "stopped"}}}
|
||||
registerTestDriver(t, reg, drv)
|
||||
if err := reg.Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{ID: "vendor.guard", Version: "1.0.0", Permissions: []string{"vm:intent"}}, Desired: true,
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{Event: plugin.EventVMBeforeStart, Blocking: true, BlockingAllowed: true,
|
||||
Handler: func(context.Context, any) (any, error) { return plugin.StartIntent{BlockReason: "veto"}, nil }})
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
files := []string{"OpenCore.img", ".reims-go-recovery-picker", plugin.ArgLedgerFileName}
|
||||
before := map[string][]byte{}
|
||||
for _, name := range files {
|
||||
body := []byte("before-" + name)
|
||||
if err := os.WriteFile(filepath.Join(vmDir, name), body, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before[name] = body
|
||||
}
|
||||
svc := New(reg, driver.NewRouter(reg, nil), nil)
|
||||
_, err := svc.StartNamed(context.Background(), drv.id, "mac", io.Discard, io.Discard)
|
||||
if err == nil || !strings.Contains(err.Error(), "veto") {
|
||||
t.Fatalf("Start error = %v", err)
|
||||
}
|
||||
if drv.starts != 0 {
|
||||
t.Fatal("driver Start ran after veto")
|
||||
}
|
||||
for _, name := range files {
|
||||
got, readErr := os.ReadFile(filepath.Join(vmDir, name))
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if string(got) != string(before[name]) {
|
||||
t.Fatalf("%s changed after veto", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,21 +2,14 @@ package guest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"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/macosdriver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
func guestLocale(cb builtin.HostCallbacks) i18n.Locale {
|
||||
@@ -152,7 +145,12 @@ func Definition(ver string, cb builtin.HostCallbacks, desired bool) plugin.Plugi
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desired,
|
||||
Activate: func(ctx context.Context, sc *plugin.Scope) error {
|
||||
drv := macosdriver.NewReimsMacOSDriver(cb.GetConfig)
|
||||
drv := macosdriver.NewReimsMacOSDriver(cb.GetConfig, macosdriver.Options{
|
||||
OwnerID: ID,
|
||||
WHPXFallbackEnabled: func() bool { return settingOn(cb, SettingWHPXFallback) },
|
||||
ColdRebootEnabled: func() bool { return settingOn(cb, SettingWin10ColdReboot) },
|
||||
MigrateLedger: func(l *plugin.ArgLedger) { MigrateLedger(l) },
|
||||
})
|
||||
sc.Registry().RegisterGuestDriver(sc, IDDriver, drv)
|
||||
|
||||
hooks := sc.Registry().Hooks()
|
||||
@@ -173,37 +171,6 @@ func Definition(ver string, cb builtin.HostCallbacks, desired bool) plugin.Plugi
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
// One handler runs every start step in a fixed order. Guest language
|
||||
// must follow the recovery step, which may rebuild OpenCore.
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMBeforeStart,
|
||||
Builtin: true,
|
||||
Handler: func(ctx context.Context, raw any) (any, error) {
|
||||
p, ok := raw.(plugin.BeforeStartPayload)
|
||||
if !ok || p.DriverID != IDDriver {
|
||||
return nil, nil
|
||||
}
|
||||
in := plugin.StartIntent{PluginID: ID}
|
||||
stepOfflineHelper(cb, p, &in)
|
||||
stepRecoveryBoot(ctx, cb, p, &in)
|
||||
stepGuestLang(ctx, cb, p, &in)
|
||||
stepWHPXFallback(cb, p, &in)
|
||||
stepWin10ColdReboot(cb, p, &in)
|
||||
return in, nil
|
||||
},
|
||||
})
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStart,
|
||||
Builtin: true,
|
||||
Handler: func(_ context.Context, raw any) (any, error) {
|
||||
// QMPAddr is only set when stepWin10ColdReboot asked for the watcher.
|
||||
ev, ok := raw.(plugin.VMEventPayload)
|
||||
if ok && ev.QMPAddr != "" && cb.StartColdReboot != nil {
|
||||
cb.StartColdReboot(ev.VMName, ev.QMPAddr)
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
})
|
||||
hooks.Subscribe(sc, plugin.HookRegistration{
|
||||
Event: plugin.EventVMAfterStop,
|
||||
Builtin: true,
|
||||
@@ -230,85 +197,6 @@ const (
|
||||
keyWin10ColdReboot = "win10-cold-reboot"
|
||||
)
|
||||
|
||||
// stepOfflineHelper attaches the REIMSHELP helper disk while an offline
|
||||
// installer is attached and clears it otherwise.
|
||||
func stepOfflineHelper(cb builtin.HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if !p.HasInstaller || !reims.IsOfflineInstallerPath(p.InstallerPath) || cb.GetConfig == nil {
|
||||
in.ClearKeys = append(in.ClearKeys, keyOfflineHelper)
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
|
||||
if err != nil {
|
||||
in.Warnings = append(in.Warnings, i18n.M(guestLocale(cb), "core.start.warn.offline_helper_skipped", map[string]any{"err": err.Error()}))
|
||||
return
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: ID,
|
||||
Key: keyOfflineHelper,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath)),
|
||||
Builtin: true,
|
||||
Priority: 85,
|
||||
})
|
||||
}
|
||||
|
||||
// stepRecoveryBoot applies a recovery-mode switch recorded while the VM was
|
||||
// running; updating OpenCore needs a stopped VM.
|
||||
func stepRecoveryBoot(ctx context.Context, cb builtin.HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if p.VMDir == "" || cb.GetConfig == nil {
|
||||
return
|
||||
}
|
||||
marker := vmstart.ReadRecoveryMarker(p.VMDir)
|
||||
if marker != "want" && marker != "restore" {
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return
|
||||
}
|
||||
show := marker == "want"
|
||||
next := ""
|
||||
if show {
|
||||
next = "on"
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) {
|
||||
if cb.Log != nil {
|
||||
cb.Log(p.VMName, line)
|
||||
}
|
||||
})
|
||||
if err := reims.NewClient(&cfg, *active).UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
|
||||
in.Warnings = append(in.Warnings, i18n.M(guestLocale(cb), "core.start.warn.opencore_picker_failed", map[string]any{"err": err.Error()}))
|
||||
return
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(p.VMDir, next)
|
||||
}
|
||||
|
||||
// stepGuestLang writes the saved macOS language into OpenCore NVRAM. It runs
|
||||
// after stepRecoveryBoot because rebuilding OpenCore drops it.
|
||||
func stepGuestLang(ctx context.Context, cb builtin.HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if p.VMDir == "" || cb.GetConfig == nil {
|
||||
return
|
||||
}
|
||||
saved := opencore.ReadSavedGuestLang(p.VMDir)
|
||||
if saved == "" {
|
||||
return
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(p.VMDir)
|
||||
if ocPath == "" {
|
||||
return
|
||||
}
|
||||
cfg := cb.GetConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil || active == nil {
|
||||
return
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, *active)
|
||||
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
|
||||
in.Warnings = append(in.Warnings, i18n.M(guestLocale(cb), "core.start.warn.opencore_lang_failed", map[string]any{"err": err.Error()}))
|
||||
}
|
||||
}
|
||||
|
||||
// whpxFallbackNeeded reports whether the host rejects the nested-virt property
|
||||
// while kernel-irqchip=off is available and the cold-reboot path isn't used.
|
||||
func whpxFallbackNeeded(facts map[string]any) bool {
|
||||
@@ -326,53 +214,3 @@ func hasCap(caps []string, want string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// stepWHPXFallback adds kernel-irqchip=off on hosts that reject the
|
||||
// nested-virtualization property when the runtime can't tolerate that.
|
||||
func stepWHPXFallback(cb builtin.HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
if !settingOn(cb, SettingWHPXFallback) || !whpxFallbackNeeded(p.HostFacts) || hasCap(p.RuntimeCaps, "nested-virt-nonfatal") {
|
||||
in.ClearKeys = append(in.ClearKeys, keyKernelIrqchip)
|
||||
return
|
||||
}
|
||||
if reims.HasKernelIrqchipArg(p.ExtraArgs) {
|
||||
return // already there: ours from an earlier start, or written by the user
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: ID,
|
||||
Key: keyKernelIrqchip,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"},
|
||||
Builtin: true,
|
||||
Priority: 90,
|
||||
})
|
||||
in.Warnings = append(in.Warnings, i18n.T(guestLocale(cb), "core.start.warn.whpx_irqchip_applied"))
|
||||
}
|
||||
|
||||
// stepWin10ColdReboot adds -no-reboot with a private QMP socket on Windows 10
|
||||
// hosts without WHvResetPartition and asks for the reboot watcher.
|
||||
func stepWin10ColdReboot(cb builtin.HostCallbacks, p plugin.BeforeStartPayload, in *plugin.StartIntent) {
|
||||
needs, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
|
||||
if !needs || !settingOn(cb, SettingWin10ColdReboot) {
|
||||
in.ClearKeys = append(in.ClearKeys, keyWin10ColdReboot)
|
||||
return
|
||||
}
|
||||
tmpDir := ""
|
||||
if cb.GetConfig != nil {
|
||||
cfg := cb.GetConfig()
|
||||
tmpDir = cfg.TempDir()
|
||||
}
|
||||
sockPath := qmp.RebootSocketPath(p.VMDir, tmpDir, p.VMName)
|
||||
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
||||
_ = os.Remove(sockPath)
|
||||
in.Args = append(in.Args, plugin.ArgFragment{
|
||||
PluginID: ID,
|
||||
Key: keyWin10ColdReboot,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath)),
|
||||
Builtin: true,
|
||||
Priority: 95,
|
||||
})
|
||||
in.PostStart = append(in.PostStart, plugin.PostStartAction{
|
||||
PluginID: ID,
|
||||
Kind: "qmp.watch_cold_reboot",
|
||||
Params: map[string]any{"qmp_addr": "unix:" + sockPath},
|
||||
})
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/macos/installguide"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
@@ -46,6 +47,13 @@ func TestGuestPluginOwnsStaticDriverAndInstallGuide(t *testing.T) {
|
||||
if _, ok := reg.GuestDriver(IDDriver); !ok {
|
||||
t.Fatal("driver ID changed or was not registered")
|
||||
}
|
||||
router := driver.NewRouter(reg, nil)
|
||||
if drv, err := router.DriverByID(IDDriver); err != nil || drv.ID() != IDDriver {
|
||||
t.Fatalf("registered driver does not satisfy driver.Driver: %v, %v", drv, err)
|
||||
}
|
||||
if reg.Hooks().HasSubscribers(plugin.EventVMBeforeStart) {
|
||||
t.Fatal("macOS disk preparation must not run in vm.beforeStart")
|
||||
}
|
||||
if _, ok := reg.LookupService(ServiceInstallGuide); !ok {
|
||||
t.Fatal("install guide service missing")
|
||||
}
|
||||
@@ -60,66 +68,6 @@ func TestGuestPluginOwnsStaticDriverAndInstallGuide(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func dispatchStart(t *testing.T, settings map[string]any, facts map[string]any, caps []string) plugin.StartIntent {
|
||||
t.Helper()
|
||||
reg := plugin.NewRegistry(nil)
|
||||
if err := Register(reg, testCallbacks(t, settings), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(context.Background())
|
||||
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
||||
VMName: "mac1", VMDir: t.TempDir(), DriverID: IDDriver, RuntimeCaps: caps, HostFacts: facts,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, in := range intents {
|
||||
if in.PluginID == ID {
|
||||
return in
|
||||
}
|
||||
}
|
||||
t.Fatalf("no guest start intent in %+v", intents)
|
||||
return plugin.StartIntent{}
|
||||
}
|
||||
|
||||
func argKeys(in plugin.StartIntent) []string {
|
||||
var keys []string
|
||||
for _, a := range in.Args {
|
||||
keys = append(keys, a.Key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
var whpxHostFacts = map[string]any{
|
||||
"host.needs_cold_reboot": false, "host.whpx_irqchip": true, "host.whpx_nested_virt": false,
|
||||
}
|
||||
|
||||
func TestStartStepsAndWorkaroundSettings(t *testing.T) {
|
||||
in := dispatchStart(t, nil, whpxHostFacts, nil)
|
||||
if !slices.Equal(argKeys(in), []string{keyKernelIrqchip}) {
|
||||
t.Fatalf("args = %v", argKeys(in))
|
||||
}
|
||||
for _, k := range []string{keyOfflineHelper, keyWin10ColdReboot} {
|
||||
if !slices.Contains(in.ClearKeys, k) {
|
||||
t.Errorf("missing clear %q", k)
|
||||
}
|
||||
}
|
||||
in = dispatchStart(t, nil, whpxHostFacts, []string{"nested-virt-nonfatal"})
|
||||
if len(in.Args) != 0 || !slices.Contains(in.ClearKeys, keyKernelIrqchip) {
|
||||
t.Fatalf("capable runtime: %+v", in)
|
||||
}
|
||||
off := map[string]any{SettingWHPXFallback: false, SettingWin10ColdReboot: false}
|
||||
win10 := map[string]any{"host.needs_cold_reboot": true}
|
||||
in = dispatchStart(t, nil, win10, nil)
|
||||
if !slices.Contains(argKeys(in), keyWin10ColdReboot) || len(in.PostStart) != 1 {
|
||||
t.Fatalf("Win10: %+v", in)
|
||||
}
|
||||
in = dispatchStart(t, off, win10, nil)
|
||||
if len(in.Args) != 0 || len(in.PostStart) != 0 {
|
||||
t.Fatalf("disabled workarounds: %+v", in)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := plugin.NewStateStore(plugin.NewPluginsLayout(root).Root)
|
||||
|
||||
@@ -29,13 +29,27 @@ var ReimsMacOSCapabilities = []string{
|
||||
|
||||
// ReimsMacOSDriver adapts internal/macos/reims into the generic driver.Driver interface
|
||||
// as the compiled-in `builtin.driver.reims-macos` extension (§3.2, §5.3).
|
||||
type ReimsMacOSDriver struct {
|
||||
getConfig func() config.Config
|
||||
type Options struct {
|
||||
OwnerID string
|
||||
WHPXFallbackEnabled func() bool
|
||||
ColdRebootEnabled func() bool
|
||||
MigrateLedger func(*plugin.ArgLedger)
|
||||
}
|
||||
|
||||
type ReimsMacOSDriver struct {
|
||||
getConfig func() config.Config
|
||||
opts Options
|
||||
}
|
||||
|
||||
var _ driver.Driver = (*ReimsMacOSDriver)(nil)
|
||||
|
||||
// NewReimsMacOSDriver creates the built-in macOS driver adapter.
|
||||
func NewReimsMacOSDriver(getConfig func() config.Config) *ReimsMacOSDriver {
|
||||
return &ReimsMacOSDriver{getConfig: getConfig}
|
||||
func NewReimsMacOSDriver(getConfig func() config.Config, options ...Options) *ReimsMacOSDriver {
|
||||
var opts Options
|
||||
if len(options) > 0 {
|
||||
opts = options[0]
|
||||
}
|
||||
return &ReimsMacOSDriver{getConfig: getConfig, opts: opts}
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) ID() string { return driver.BuiltinReimsMacOSDriverID }
|
||||
@@ -46,7 +60,9 @@ func (d *ReimsMacOSDriver) DisplayName() plugin.LocalizedText {
|
||||
|
||||
func (d *ReimsMacOSDriver) RuntimeKind() string { return rt.DefaultKind }
|
||||
func (d *ReimsMacOSDriver) RuntimeAPIRange() string { return "^1.0.0" }
|
||||
func (d *ReimsMacOSDriver) Capabilities() []string { return append([]string(nil), ReimsMacOSCapabilities...) }
|
||||
func (d *ReimsMacOSDriver) Capabilities() []string {
|
||||
return append([]string(nil), ReimsMacOSCapabilities...)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) CreateSchema() *plugin.SettingsSchema {
|
||||
return nil // Uses the native macOS CreateWizard UI
|
||||
@@ -57,15 +73,20 @@ func (d *ReimsMacOSDriver) SettingsSchema() *plugin.SettingsSchema {
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) client() (*reims.Client, error) {
|
||||
c, _, err := d.startClient()
|
||||
return c, err
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) startClient() (*reims.Client, rt.Installed, error) {
|
||||
cfg := d.getConfig()
|
||||
active, err := rt.ResolveForKind(&cfg, d.RuntimeKind())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, rt.Installed{}, err
|
||||
}
|
||||
if err := rt.CheckCompatibility(d.RuntimeKind(), d.RuntimeAPIRange(), *active); err != nil {
|
||||
return nil, err
|
||||
return nil, rt.Installed{}, err
|
||||
}
|
||||
return reims.NewClient(&cfg, *active), nil
|
||||
return reims.NewClient(&cfg, *active), *active, nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
|
||||
@@ -82,6 +103,7 @@ func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
|
||||
out = append(out, driver.VMInfo{
|
||||
Name: it.Name,
|
||||
DriverID: d.ID(),
|
||||
Directory: it.Dir,
|
||||
DriverName: "macOS (Reims vGPU)",
|
||||
State: it.State,
|
||||
PID: it.PID,
|
||||
@@ -191,14 +213,6 @@ func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdou
|
||||
return c.Set(ctx, opts, stdout, stderr)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Start(ctx context.Context, name string, stdout, stderr io.Writer) error {
|
||||
c, err := d.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.StartWithCompat(ctx, name, stdout, stderr, nil)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error {
|
||||
c, err := d.client()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package macosdriver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"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/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
const (
|
||||
keyOfflineHelper = "reimshelp"
|
||||
keyKernelIrqchip = "kernel-irqchip"
|
||||
keyWin10ColdReboot = "win10-cold-reboot"
|
||||
)
|
||||
|
||||
func optionEnabled(fn func() bool) bool { return fn == nil || fn() }
|
||||
|
||||
func startLog(w io.Writer, line string) {
|
||||
if w != nil && strings.TrimSpace(line) != "" {
|
||||
_, _ = fmt.Fprintln(w, line)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (driver.StartResult, error) {
|
||||
ref := driver.NewVMRef(req.Ref.DriverID, req.Ref.Name)
|
||||
if ref.DriverID != d.ID() || ref.Name == "" || d.opts.OwnerID == "" {
|
||||
return driver.StartResult{}, fmt.Errorf("invalid macOS start request for %s:%s", ref.DriverID, ref.Name)
|
||||
}
|
||||
stdout, stderr := req.Stdout, req.Stderr
|
||||
if stdout == nil {
|
||||
stdout = io.Discard
|
||||
}
|
||||
if stderr == nil {
|
||||
stderr = io.Discard
|
||||
}
|
||||
c, active, err := d.startClient()
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
cur, err := c.Show(ctx, ref.Name)
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
cfg := d.getConfig()
|
||||
if cur.State == "running" {
|
||||
return driver.StartResult{}, errors.New(i18n.T(cfg.Locale, "vm.already_running", ref.Name))
|
||||
}
|
||||
rep := host.Inspect(cfg.DataRoot)
|
||||
prep, err := vmstart.New(cfg, func(line string) { startLog(stdout, line) })
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
prep.Client, prep.Runtime = c, active
|
||||
if err := prep.CheckWHPX(rep); err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
if err := prep.CheckMemory(cur.Memory, rep); err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
|
||||
ownerIntent, err := d.prepareStart(ctx, cfg, c, active, ref.Name, cur, rep, stdout)
|
||||
if err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
ledger, err := plugin.LoadArgLedger(cur.Directory)
|
||||
if err != nil {
|
||||
return driver.StartResult{}, fmt.Errorf("read start argument ledger: %w", err)
|
||||
}
|
||||
if d.opts.MigrateLedger != nil {
|
||||
d.opts.MigrateLedger(ledger)
|
||||
}
|
||||
baseArgs := stripLegacyManagedExtraArgs(cur.ExtraArgs)
|
||||
intents := append(append([]plugin.StartIntent(nil), req.Intents...), ownerIntent)
|
||||
reconciled := plugin.ReconcileStartIntentsForDriver(baseArgs, ledger, req.ActivePlugins, d.opts.OwnerID, intents)
|
||||
reconciled.Changed = strings.TrimSpace(cur.ExtraArgs) != reconciled.ExtraArgs
|
||||
for _, warning := range reconciled.Warnings {
|
||||
startLog(stderr, "[plugin] "+warning)
|
||||
}
|
||||
c.Env = append(c.Env, reconciled.Env...)
|
||||
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
|
||||
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
|
||||
}
|
||||
if reconciled.Changed {
|
||||
if err := c.Set(ctx, reims.SetOpts{Name: ref.Name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
|
||||
return driver.StartResult{}, fmt.Errorf("apply reconciled start arguments: %w", err)
|
||||
}
|
||||
}
|
||||
if err := plugin.SaveArgLedger(cur.Directory, ledger); err != nil {
|
||||
return driver.StartResult{}, fmt.Errorf("save start argument ledger: %w", err)
|
||||
}
|
||||
if err := c.StartWithCompat(ctx, ref.Name, stdout, stderr, func(msg string) { startLog(stderr, msg) }); err != nil {
|
||||
return driver.StartResult{}, err
|
||||
}
|
||||
return driver.StartResult{PostStart: reconciled.PostStart}, nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, c *reims.Client, active rt.Installed, name string, cur reims.VMDetail, rep host.Report, log io.Writer) (plugin.StartIntent, error) {
|
||||
in := plugin.StartIntent{PluginID: d.opts.OwnerID}
|
||||
if err := d.prepareOfflineHelper(cfg, cur, &in); err != nil {
|
||||
return in, err
|
||||
}
|
||||
if err := d.prepareRecoveryBoot(ctx, cfg, c, name, cur.Directory, log); err != nil {
|
||||
return in, err
|
||||
}
|
||||
if err := d.prepareGuestLang(ctx, cfg, active, cur.Directory); err != nil {
|
||||
return in, err
|
||||
}
|
||||
d.prepareWHPXFallback(cfg, active, cur, rep, &in)
|
||||
if err := d.prepareColdReboot(cfg, name, cur.Directory, rep, &in); err != nil {
|
||||
return in, err
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMDetail, in *plugin.StartIntent) error {
|
||||
if !cur.HasInstaller || !reims.IsOfflineInstallerPath(cur.InstallerPath) {
|
||||
in.ClearKeys = append(in.ClearKeys, keyOfflineHelper)
|
||||
return nil
|
||||
}
|
||||
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), cur.InstallerPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prepare offline install helper disk: %w", err)
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyOfflineHelper,
|
||||
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareRecoveryBoot(ctx context.Context, cfg config.Config, c *reims.Client, name, vmDir string, log io.Writer) error {
|
||||
marker := vmstart.ReadRecoveryMarker(vmDir)
|
||||
if marker != "want" && marker != "restore" {
|
||||
return nil
|
||||
}
|
||||
show, next := marker == "want", ""
|
||||
if show {
|
||||
next = "on"
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { startLog(log, line) })
|
||||
if err := c.UpdateOpenCore(ctx, name, show, w, w); err != nil {
|
||||
return fmt.Errorf("prepare OpenCore recovery boot picker: %w", err)
|
||||
}
|
||||
vmstart.WriteRecoveryMarker(vmDir, next)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareGuestLang(ctx context.Context, cfg config.Config, active rt.Installed, vmDir string) error {
|
||||
saved := opencore.ReadSavedGuestLang(vmDir)
|
||||
if saved == "" {
|
||||
return nil
|
||||
}
|
||||
ocPath := opencore.ResolveOpenCorePath(vmDir)
|
||||
if ocPath == "" {
|
||||
return nil
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, active)
|
||||
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
|
||||
return fmt.Errorf("apply macOS language %s to OpenCore: %w", saved, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareWHPXFallback(cfg config.Config, active rt.Installed, cur reims.VMDetail, rep host.Report, in *plugin.StartIntent) {
|
||||
needed := !rep.NeedsColdRebootWorkaround && rep.WHPXCaps.KernelIrqchipAvailable && !rep.WHPXCaps.NestedVirtProperty
|
||||
if !optionEnabled(d.opts.WHPXFallbackEnabled) || !needed || active.Manifest.HasCapability("nested-virt-nonfatal") {
|
||||
in.ClearKeys = append(in.ClearKeys, keyKernelIrqchip)
|
||||
return
|
||||
}
|
||||
if reims.HasKernelIrqchipArg(cur.ExtraArgs) {
|
||||
return
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyKernelIrqchip,
|
||||
Tokens: []string{"-machine", "kernel-irqchip=off"}, Builtin: true, Priority: 90})
|
||||
code := rep.WHPXCaps.NestedVirtProbeError
|
||||
if code == "" {
|
||||
code = "unsupported"
|
||||
}
|
||||
in.Warnings = append(in.Warnings, i18n.M(cfg.Locale, "vmstart.compat.nested_virt", i18n.Vars{"code": code}))
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir string, rep host.Report, in *plugin.StartIntent) error {
|
||||
if !rep.NeedsColdRebootWorkaround || !optionEnabled(d.opts.ColdRebootEnabled) {
|
||||
in.ClearKeys = append(in.ClearKeys, keyWin10ColdReboot)
|
||||
return nil
|
||||
}
|
||||
sockPath := qmp.RebootSocketPath(vmDir, cfg.TempDir(), name)
|
||||
if err := os.MkdirAll(filepath.Dir(sockPath), 0o755); err != nil {
|
||||
return fmt.Errorf("prepare cold-reboot socket: %w", err)
|
||||
}
|
||||
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("replace cold-reboot socket: %w", err)
|
||||
}
|
||||
in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyWin10ColdReboot,
|
||||
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath)), Builtin: true, Priority: 95})
|
||||
in.PostStart = append(in.PostStart, plugin.PostStartAction{PluginID: d.opts.OwnerID,
|
||||
Kind: "qmp.watch_cold_reboot", Params: map[string]any{"qmp_addr": "unix:" + sockPath}})
|
||||
return nil
|
||||
}
|
||||
|
||||
func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
s := reims.StripGuestToolsArgs(extraArgs)
|
||||
s = reims.StripOfflineHelperArgs(s)
|
||||
s = qmp.StripLegacyWin10RebootArgs(s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package macosdriver
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func argKeys(in plugin.StartIntent) []string {
|
||||
keys := make([]string, 0, len(in.Args))
|
||||
for _, arg := range in.Args {
|
||||
keys = append(keys, arg.Key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func TestPrepareWorkaroundsHonourSettingsAndRuntime(t *testing.T) {
|
||||
whpx, cold := true, true
|
||||
d := &ReimsMacOSDriver{opts: Options{OwnerID: "test.macos",
|
||||
WHPXFallbackEnabled: func() bool { return whpx }, ColdRebootEnabled: func() bool { return cold }}}
|
||||
rep := host.Report{WHPXCaps: host.WHPXCapabilities{KernelIrqchipAvailable: true, NestedVirtProperty: false}}
|
||||
var in plugin.StartIntent
|
||||
d.prepareWHPXFallback(config.Config{}, rt.Installed{}, reims.VMDetail{}, rep, &in)
|
||||
if !slices.Equal(argKeys(in), []string{keyKernelIrqchip}) {
|
||||
t.Fatalf("WHPX args = %+v", in.Args)
|
||||
}
|
||||
for _, key := range []string{keyOfflineHelper, keyWin10ColdReboot} {
|
||||
in.ClearKeys = append(in.ClearKeys, key)
|
||||
}
|
||||
in = plugin.StartIntent{}
|
||||
d.prepareWHPXFallback(config.Config{}, rt.Installed{Manifest: rt.Manifest{Capabilities: []string{"nested-virt-nonfatal"}}}, reims.VMDetail{}, rep, &in)
|
||||
if len(in.Args) != 0 || !slices.Contains(in.ClearKeys, keyKernelIrqchip) {
|
||||
t.Fatalf("capable runtime = %+v", in)
|
||||
}
|
||||
whpx = false
|
||||
in = plugin.StartIntent{}
|
||||
d.prepareWHPXFallback(config.Config{}, rt.Installed{}, reims.VMDetail{}, rep, &in)
|
||||
if len(in.Args) != 0 {
|
||||
t.Fatalf("disabled WHPX fallback = %+v", in)
|
||||
}
|
||||
|
||||
rep.NeedsColdRebootWorkaround = true
|
||||
root := t.TempDir()
|
||||
cfg := config.Config{DataRoot: root}
|
||||
in = plugin.StartIntent{}
|
||||
if err := d.prepareColdReboot(cfg, "mac", root, rep, &in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Contains(argKeys(in), keyWin10ColdReboot) || len(in.PostStart) != 1 {
|
||||
t.Fatalf("cold reboot = %+v", in)
|
||||
}
|
||||
cold = false
|
||||
in = plugin.StartIntent{}
|
||||
if err := d.prepareColdReboot(cfg, "mac", root, rep, &in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(in.Args) != 0 || len(in.PostStart) != 0 {
|
||||
t.Fatalf("disabled cold reboot = %+v", in)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReconcileStartIntentsForDriverUsesOwnershipNotPrefix(t *testing.T) {
|
||||
const owner = "vendor.guest.macos"
|
||||
frag := func(key string) ArgFragment {
|
||||
return ArgFragment{Key: key, Tokens: []string{"-drive", "file=" + key + ".img,if=none,id=" + key}, Priority: 1}
|
||||
}
|
||||
intents := []StartIntent{
|
||||
{PluginID: owner, Args: []ArgFragment{frag("owner-disk")}, Env: map[string]string{"REIMS_VGPU_LOG": "debug"}, PostStart: []PostStartAction{{Kind: "qmp.watch_cold_reboot"}}},
|
||||
{PluginID: "vendor.other", Args: []ArgFragment{frag("other-disk")}, Env: map[string]string{"REIMS_VGPU_LOG": "other"}},
|
||||
}
|
||||
ledger := &ArgLedger{Version: 1, Owners: map[string][]ArgFragment{}}
|
||||
res := ReconcileStartIntentsForDriver("", ledger, map[string]bool{owner: true, "vendor.other": true}, owner, intents)
|
||||
if !strings.Contains(res.ExtraArgs, "owner-disk.img") || strings.Contains(res.ExtraArgs, "other-disk.img") {
|
||||
t.Fatalf("extra args = %q; warnings = %+v", res.ExtraArgs, res.Warnings)
|
||||
}
|
||||
if len(ledger.Owners[owner]) != 1 || !ledger.Owners[owner][0].Builtin {
|
||||
t.Fatalf("owner ledger = %+v", ledger.Owners)
|
||||
}
|
||||
if len(res.PostStart) != 1 {
|
||||
t.Fatalf("post start = %+v", res.PostStart)
|
||||
}
|
||||
foundEnv := false
|
||||
for _, env := range res.Env {
|
||||
if env == "REIMS_VGPU_LOG=debug" {
|
||||
foundEnv = true
|
||||
}
|
||||
}
|
||||
if !foundEnv {
|
||||
t.Fatalf("owner env missing: %+v", res.Env)
|
||||
}
|
||||
}
|
||||
@@ -348,6 +348,16 @@ func sanitizeEnvPrefix(pluginID string) string {
|
||||
// validates option allowlists & env prefixes, updates the ledger, and returns
|
||||
// the single merged extra-args string ready for one `reims-ctl set` call (§4.4).
|
||||
func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, intents []StartIntent) ReconcileResult {
|
||||
return reconcileStartIntents(currentExtraArgs, ledger, activePlugins, "", intents)
|
||||
}
|
||||
|
||||
// ReconcileStartIntentsForDriver additionally grants the owning driver control
|
||||
// of its own VM, without trusting other external plugins by ID prefix.
|
||||
func ReconcileStartIntentsForDriver(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, driverOwner string, intents []StartIntent) ReconcileResult {
|
||||
return reconcileStartIntents(currentExtraArgs, ledger, activePlugins, driverOwner, intents)
|
||||
}
|
||||
|
||||
func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, driverOwner string, intents []StartIntent) ReconcileResult {
|
||||
if ledger == nil {
|
||||
ledger = &ArgLedger{Version: 1, Owners: map[string][]ArgFragment{}}
|
||||
}
|
||||
@@ -386,7 +396,8 @@ func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
|
||||
|
||||
for _, intent := range intents {
|
||||
pid := intent.PluginID
|
||||
isBuiltin := strings.HasPrefix(pid, "builtin.")
|
||||
isOwner := driverOwner != "" && pid == driverOwner
|
||||
isBuiltin := isOwner || strings.HasPrefix(pid, "builtin.")
|
||||
res.Warnings = append(res.Warnings, intent.Warnings...)
|
||||
for _, ps := range intent.PostStart {
|
||||
if !isBuiltin && (ps.Kind == "qmp.watch_cold_reboot" || ps.Kind == "guesttools.sync") {
|
||||
@@ -421,7 +432,9 @@ func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
|
||||
var valid []ArgFragment
|
||||
for _, frag := range intent.Args {
|
||||
frag.PluginID = pid
|
||||
if !isBuiltin {
|
||||
if isOwner {
|
||||
frag.Builtin = true
|
||||
} else if !isBuiltin {
|
||||
frag.Builtin = false
|
||||
}
|
||||
if err := ValidateArgFragment(frag); err != nil {
|
||||
@@ -444,7 +457,7 @@ func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
|
||||
}
|
||||
|
||||
for k, v := range intent.Env {
|
||||
if !ValidateEnvKey(pid, k) {
|
||||
if !ValidateEnvKey(pid, k) && !(isOwner && AllowedHostEnvVars[k]) {
|
||||
res.Warnings = append(res.Warnings, fmt.Sprintf("plugin %s env %q rejected (outside namespace/allowlist)", pid, k))
|
||||
continue
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user