Files
Reims-Go/internal/macos/reims/compat.go
T

373 lines
11 KiB
Go

package reims
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"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"
// ResolveCreateTargetDir returns the directory `reims-ctl create` will claim
// for opts (opts.Dir if set, otherwise <xdgDataDir>/reims-ctl/vms/<name>).
func ResolveCreateTargetDir(xdgDataDir string, opts CreateOpts) string {
if target := strings.TrimSpace(opts.Dir); target != "" {
return filepath.Clean(config.ExpandHomePath(target))
}
name := strings.TrimSpace(opts.Name)
if name == "" || !reVMName.MatchString(name) || strings.TrimSpace(xdgDataDir) == "" {
return ""
}
return filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
// IsAbortedCreateDir reports whether dir holds a `.reims-ctl-creating` marker
// without `vm.toml`, indicating a previously killed `reims-ctl create` run.
func IsAbortedCreateDir(dir string) bool {
if strings.TrimSpace(dir) == "" {
return false
}
markerInfo, err := os.Stat(filepath.Join(dir, creatingMarker))
if err != nil || markerInfo.IsDir() {
return false
}
_, err = os.Stat(filepath.Join(dir, "vm.toml"))
return errors.Is(err, os.ErrNotExist)
}
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
// by a previously killed `reims-ctl create` run. It only removes a directory
// when the name and directory are unregistered and the directory contains
// `.reims-ctl-creating` without `vm.toml`.
//
// 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 := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" || !IsAbortedCreateDir(target) || containsRegisteredVMDir(target, registered) {
return "", nil
}
if err := os.RemoveAll(target); err != nil {
return "", err
}
return target, nil
}
var (
targetDirStat = os.Stat
targetDirReadOne = readDirHasEntries
)
func readDirHasEntries(dir string) (bool, error) {
f, err := os.Open(dir)
if err != nil {
return false, err
}
entries, readErr := f.ReadDir(1)
_ = f.Close()
if readErr != nil && !errors.Is(readErr, io.EOF) {
return false, readErr
}
return len(entries) > 0, nil
}
// ValidateCreateTargetDir checks whether the directory `reims-ctl create` will
// claim already exists with conflicting contents. Empty directories and
// unregistered aborted-create directories (cleaned by CleanAbortedCreateDir)
// are allowed.
func ValidateCreateTargetDir(xdgDataDir string, opts CreateOpts, registered []VMListItem, loc i18n.Locale) *ValidationIssue {
target := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" {
return nil
}
name := strings.TrimSpace(opts.Name)
customDir := strings.TrimSpace(opts.Dir) != ""
isRegistered := false
for _, vm := range registered {
if strings.EqualFold(vm.Name, name) {
isRegistered = true
break
}
}
// When the name itself is already registered and no custom dir was chosen,
// name_taken already reports the conflict on the name field.
if isRegistered && !customDir {
return nil
}
info, err := targetDirStat(target)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !info.IsDir() {
return &ValidationIssue{
Field: "dir",
Code: "dir_not_directory",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_not_directory", i18n.Vars{"dir": target}),
}
}
nonEmpty, readErr := targetDirReadOne(target)
if readErr != nil {
if errors.Is(readErr, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !nonEmpty {
return nil
}
if !isRegistered && IsAbortedCreateDir(target) && !containsRegisteredVMDir(target, registered) {
return nil
}
msgKey := "validate.default_dir_not_empty"
if customDir {
msgKey = "validate.dir_not_empty"
}
return &ValidationIssue{
Field: "dir",
Code: "dir_not_empty",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, msgKey, i18n.Vars{"dir": target}),
}
}
func containsRegisteredVMDir(target string, registered []VMListItem) bool {
absTarget := absoluteDiskPath(target)
for _, vm := range registered {
if vm.Dir == "" {
continue
}
absVM := absoluteDiskPath(vm.Dir)
if pathInDirectory(target, vm.Dir) || pathInDirectory(absTarget, absVM) ||
pathInDirectory(vm.Dir, target) || pathInDirectory(absVM, absTarget) {
return true
}
}
return false
}
// 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")
}
// 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()
}
var driverStoreICDPattern = regexp.MustCompile(`^([a-z]:/(?:[^/]+/)*driverstore/filerepository)/([^/]+)_[0-9a-f]{8,}/([^/]+(?:/[^/]+)*)$`)
func parseDriverStoreICD(raw string) []string {
cleaned := path.Clean(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(raw), `\`, "/")))
return driverStoreICDPattern.FindStringSubmatch(cleaned)
}
// ResolveStaleDriverStoreICD matches a stale ICD to the same driver package and
// relative path, provided exactly one physical adapter matches and is usable.
func ResolveStaleDriverStoreICD(oldPath string, gpus []host.GPUInfo) (newPath string, ambiguous bool) {
old := parseDriverStoreICD(oldPath)
if old == nil {
return "", false
}
var matched []host.GPUInfo
for _, gpu := range gpus {
if gpu.Kind == host.GPUVirtual {
continue
}
candidate := parseDriverStoreICD(gpu.VulkanICD)
if candidate != nil && slices.Equal(candidate[1:], old[1:]) {
matched = append(matched, gpu)
}
}
if len(matched) != 1 {
return "", len(matched) > 1
}
gpu := matched[0]
// Warning grades can also come from PCI IDs alone. A Vulkan version
// confirms that the adapter was probed.
if gpu.VulkanVersion == "" || (gpu.Compat != host.GPUCompatSupported && gpu.Compat != host.GPUCompatWarn) {
return "", false
}
return gpu.VulkanICD, false
}
func (c *Client) reconcileStaleGPUICD(ctx context.Context, name string, stderr io.Writer, onNote func(string)) error {
detail, err := c.Show(ctx, name)
if err != nil || detail.Graphics != "reims-vgpu" || detail.State == "running" {
return nil
}
oldPath := strings.TrimSpace(detail.GPU)
if !strings.HasSuffix(strings.ToLower(oldPath), ".json") {
return nil
}
stat := c.statFile
if stat == nil {
stat = os.Stat
}
if _, err := stat(oldPath); !errors.Is(err, os.ErrNotExist) {
return nil
}
probe := c.probeGPUs
if probe == nil {
probe = host.ProbeVulkanGPUs
}
if onNote == nil && stderr != nil {
onNote = func(msg string) { fmt.Fprintln(stderr, msg) }
}
newPath, _ := ResolveStaleDriverStoreICD(oldPath, probe())
if newPath == "" {
msg := i18n.M(c.Locale, "err.gpu_icd_stale", i18n.Vars{"path": oldPath})
if onNote != nil {
onNote(msg)
}
return errors.New(msg)
}
var setErrBuf bytes.Buffer
if err := c.Set(ctx, SetOpts{Name: name, GPU: newPath}, io.Discard, &setErrBuf); err != nil {
if detail := strings.TrimSpace(setErrBuf.String()); detail != "" {
return fmt.Errorf("reims-ctl set %s --gpu: %w (%s)", name, err, detail)
}
return fmt.Errorf("reims-ctl set %s --gpu: %w", name, err)
}
if onNote != nil {
onNote(i18n.M(c.Locale, "compat.gpu_icd_rebound", i18n.Vars{"old": oldPath, "new": newPath}))
}
return nil
}
// StartWithCompat checks the configured Vulkan ICD before starting a VM and
// automatically recovers once if QEMU aborts with the WHPX nested-virtualization
// property error (hr=80370302) by setting `-machine kernel-irqchip=off` via
// `reims-ctl set` and retrying start.
func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stderr io.Writer, onNote func(string)) error {
if err := c.reconcileStaleGPUICD(ctx, name, stderr, onNote); err != nil {
return err
}
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, _ := host.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)
}