196 lines
6.0 KiB
Go
196 lines
6.0 KiB
Go
package reims
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
)
|
|
|
|
// creatingMarker is written by upstream `reims-ctl create` while building a VM
|
|
// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451).
|
|
const creatingMarker = ".reims-ctl-creating"
|
|
|
|
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
|
|
// by a previously killed `reims-ctl create` run. It only removes a directory
|
|
// when all three safety conditions hold:
|
|
// 1. opts.Name is not present in registered VMs,
|
|
// 2. `.reims-ctl-creating` exists inside the directory, and
|
|
// 3. `vm.toml` does NOT exist inside the directory.
|
|
//
|
|
// Returns the removed path if cleaned, or "" if nothing was touched.
|
|
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
|
|
name := strings.TrimSpace(opts.Name)
|
|
if name == "" {
|
|
return "", nil
|
|
}
|
|
for _, vm := range registered {
|
|
if strings.EqualFold(vm.Name, name) {
|
|
return "", nil
|
|
}
|
|
}
|
|
target := strings.TrimSpace(opts.Dir)
|
|
if target == "" {
|
|
if strings.TrimSpace(xdgDataDir) == "" {
|
|
return "", nil
|
|
}
|
|
target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
|
|
}
|
|
markerInfo, err := os.Stat(filepath.Join(target, creatingMarker))
|
|
if err != nil || markerInfo.IsDir() {
|
|
return "", nil
|
|
}
|
|
if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil {
|
|
return "", nil
|
|
}
|
|
if err := os.RemoveAll(target); err != nil {
|
|
return "", err
|
|
}
|
|
return target, nil
|
|
}
|
|
|
|
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
|
|
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
|
|
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
|
|
// device"), which is unrelated to disk space.
|
|
func IsWHPXNoAcceleratorError(output string) bool {
|
|
return strings.Contains(output, "WHPX: No accelerator found") ||
|
|
strings.Contains(output, "failed to initialize whpx: No space left on device")
|
|
}
|
|
|
|
// IsWHPXNestedVirtError reports whether QEMU exited because WHPX failed to
|
|
// enable nested virtualization (e.g. hr=80370302 WHV_E_UNKNOWN_PROPERTY on
|
|
// Windows 11 builds that advertise Bank1.NestedVirtSupport but reject
|
|
// WHvPartitionPropertyCodeNestedVirtualization; qemu-reims-vgpu 4571bc5
|
|
// target/i386/whpx/whpx-all.c:3471-3484).
|
|
func IsWHPXNestedVirtError(output string) bool {
|
|
return strings.Contains(output, "WHPX: Failed to enable nested virtualization")
|
|
}
|
|
|
|
// DiagnoseGPULog inspects QEMU / reims-vgpu output for known Vulkan GPU
|
|
// compatibility or device-loss failures and returns a machine-readable code
|
|
// ("gpu_device_lost" | "gpu_vulkan_floor") and matching line excerpt.
|
|
func DiagnoseGPULog(output string) (code, detail string) {
|
|
if output == "" {
|
|
return "", ""
|
|
}
|
|
for _, rawLine := range strings.Split(output, "\n") {
|
|
line := strings.TrimSpace(rawLine)
|
|
if line == "" {
|
|
continue
|
|
}
|
|
if strings.Contains(line, "ERROR_DEVICE_LOST") ||
|
|
strings.Contains(line, "was lost at vkQueueSubmit2") ||
|
|
strings.Contains(line, "rt-device-lost-in-flight") {
|
|
return "gpu_device_lost", line
|
|
}
|
|
}
|
|
for _, rawLine := range strings.Split(output, "\n") {
|
|
line := strings.TrimSpace(rawLine)
|
|
if line == "" {
|
|
continue
|
|
}
|
|
low := strings.ToLower(line)
|
|
if strings.Contains(line, "VK_ERROR_INCOMPATIBLE_DRIVER") ||
|
|
strings.Contains(low, "no vulkan gpu found") ||
|
|
strings.Contains(low, "meets the floor") ||
|
|
strings.Contains(low, "below the floor") ||
|
|
strings.Contains(low, "no physical device") {
|
|
return "gpu_vulkan_floor", line
|
|
}
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
// HasKernelIrqchipArg reports whether extra-args already specifies a
|
|
// kernel-irqchip setting.
|
|
func HasKernelIrqchipArg(extraArgs string) bool {
|
|
return strings.Contains(strings.ToLower(extraArgs), "kernel-irqchip=")
|
|
}
|
|
|
|
// MergeKernelIrqchipOffArgs appends `-machine kernel-irqchip=off` to existing
|
|
// QEMU extra-args unless a kernel-irqchip setting is already present.
|
|
func MergeKernelIrqchipOffArgs(existing string) string {
|
|
trimmed := strings.TrimSpace(existing)
|
|
if HasKernelIrqchipArg(trimmed) {
|
|
return trimmed
|
|
}
|
|
const flag = "-machine kernel-irqchip=off"
|
|
if trimmed == "" {
|
|
return flag
|
|
}
|
|
return trimmed + " " + flag
|
|
}
|
|
|
|
type captureWriter struct {
|
|
mu sync.Mutex
|
|
buf bytes.Buffer
|
|
dst io.Writer
|
|
}
|
|
|
|
func (w *captureWriter) Write(p []byte) (int, error) {
|
|
w.mu.Lock()
|
|
if w.buf.Len() < 64*1024 {
|
|
w.buf.Write(p)
|
|
}
|
|
w.mu.Unlock()
|
|
if w.dst != nil {
|
|
return w.dst.Write(p)
|
|
}
|
|
return len(p), nil
|
|
}
|
|
|
|
func (w *captureWriter) String() string {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
return w.buf.String()
|
|
}
|
|
|
|
// StartWithCompat starts a VM and automatically recovers once if QEMU aborts
|
|
// with the WHPX nested-virtualization property error (hr=80370302) by writing
|
|
// `-machine kernel-irqchip=off` via `reims-ctl set` (D3) and retrying start.
|
|
func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error {
|
|
outCap := &captureWriter{dst: stdout}
|
|
errCap := &captureWriter{dst: stderr}
|
|
err := c.Start(ctx, name, outCap, errCap)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
combined := outCap.String() + "\n" + errCap.String()
|
|
if IsWHPXNoAcceleratorError(combined) {
|
|
msg := i18n.T(c.Locale, "err.whpx_no_hypervisor")
|
|
if onNote != nil {
|
|
onNote(msg)
|
|
}
|
|
return fmt.Errorf("%s (%w)", msg, err)
|
|
}
|
|
if gpuCode, _ := DiagnoseGPULog(combined); gpuCode != "" {
|
|
msg := i18n.T(c.Locale, "err."+gpuCode)
|
|
if onNote != nil {
|
|
onNote(msg)
|
|
}
|
|
return fmt.Errorf("%s (%w)", msg, err)
|
|
}
|
|
if !IsWHPXNestedVirtError(combined) {
|
|
return err
|
|
}
|
|
cur, serr := c.Show(ctx, name)
|
|
if serr != nil || HasKernelIrqchipArg(cur.ExtraArgs) {
|
|
return err
|
|
}
|
|
merged := MergeKernelIrqchipOffArgs(cur.ExtraArgs)
|
|
if setErr := c.Set(ctx, SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); setErr != nil {
|
|
return err
|
|
}
|
|
if onNote != nil {
|
|
onNote("WHPX host rejected nested virtualization property (hr=80370302); applied -machine kernel-irqchip=off and retrying start...")
|
|
}
|
|
return c.Start(ctx, name, stdout, stderr)
|
|
}
|