- M5.5: add pure-Go internal/opencore reader/in-place patcher for OpenCore NVRAM prev-lang:kbd with sidecar persistence, automatic replay after update-opencore/graphics changes/CoW clones, wizard/settings/CLI (--guest-lang) support - M5.6: add stopped VM disk resize (qemu-img resize + dynamic macOS APFS expand command) and standalone qcow2 compaction (backing-file guard, free-space check, qemu-img check, atomic swap) in GUI Settings and CLI (vm resize/compact) - M5.9: add Win32 winmm audio output/input device probing, fix reims-ctl show audio_backend parsing, expose audio backend selector (auto/dsound/none) and latency/mic diagnostics in Settings & CLI - UI & thumbnails: add QMP screendump VM thumbnails (internal/thumb, thumbnail_flow.go), VMPage/CreateWizard layout polish, and docs/ui-audit.md - Update docs/roadmap.md for M5.5, M5.6, and M5.9
300 lines
10 KiB
Go
300 lines
10 KiB
Go
package reims
|
|
|
|
import (
|
|
"context"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
)
|
|
|
|
// GuestAPFSExpandCommand repairs the GPT backup header moved by `qemu-img resize`
|
|
// and grows the APFS container backing `/` to fill the newly expanded disk,
|
|
// regardless of whether macOS assigned the system disk to disk0, disk1, or disk2.
|
|
const GuestAPFSExpandCommand = `P=$(diskutil info / | awk '/APFS Container:/{print $3}'); S=$(diskutil apfs list "$P" | awk '/APFS Physical Store Disk:/{print $5}'); D=${S%s*}; diskutil repairDisk "$D" && diskutil apfs resizeContainer "$S" 0`
|
|
|
|
type DiskResizeResult struct {
|
|
Path string `json:"path"`
|
|
OldVirtualBytes uint64 `json:"old_virtual_bytes"`
|
|
NewVirtualBytes uint64 `json:"new_virtual_bytes"`
|
|
GuestExpandCmd string `json:"guest_expand_cmd"`
|
|
}
|
|
|
|
type DiskCompactResult struct {
|
|
Path string `json:"path"`
|
|
BeforeBytes uint64 `json:"before_bytes"`
|
|
AfterBytes uint64 `json:"after_bytes"`
|
|
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
|
|
}
|
|
|
|
var reResizeSpec = regexp.MustCompile(`^(?i)(\+)?\s*(\d+)\s*([GM])$`)
|
|
|
|
// ParseResizeTarget parses an absolute size ("256G") or relative delta ("+64G")
|
|
// and verifies it strictly grows the virtual disk without shrinking.
|
|
func ParseResizeTarget(currentVirtualBytes uint64, raw string) (uint64, string, error) {
|
|
m := reResizeSpec.FindStringSubmatch(strings.TrimSpace(raw))
|
|
if len(m) != 4 {
|
|
return 0, "", fmt.Errorf("invalid disk size %q (use e.g. 256G or +64G)", raw)
|
|
}
|
|
isDelta := m[1] == "+"
|
|
n, err := strconv.ParseUint(m[2], 10, 64)
|
|
if err != nil || n == 0 {
|
|
return 0, "", fmt.Errorf("disk size must be positive")
|
|
}
|
|
unit := strings.ToUpper(m[3])
|
|
var mult uint64 = 1 << 30
|
|
if unit == "M" {
|
|
mult = 1 << 20
|
|
}
|
|
const maxDiskBytes = uint64(16384) << 30 // 16 TiB sanity cap
|
|
valBytes := n * mult
|
|
if valBytes/mult != n {
|
|
return 0, "", fmt.Errorf("disk size overflows limit")
|
|
}
|
|
|
|
var newBytes uint64
|
|
var arg string
|
|
if isDelta {
|
|
newBytes = currentVirtualBytes + valBytes
|
|
arg = fmt.Sprintf("+%d%s", n, unit)
|
|
} else {
|
|
newBytes = valBytes
|
|
arg = fmt.Sprintf("%d%s", n, unit)
|
|
}
|
|
if newBytes <= currentVirtualBytes {
|
|
curGB := float64(currentVirtualBytes) / float64(1<<30)
|
|
return 0, "", fmt.Errorf("new size (%s) must be larger than current capacity (%.0fG); shrinking is not supported", raw, curGB)
|
|
}
|
|
if newBytes > maxDiskBytes {
|
|
return 0, "", fmt.Errorf("target disk size exceeds 16 TB limit")
|
|
}
|
|
return newBytes, arg, nil
|
|
}
|
|
|
|
// HasQCOW2BackingFile reports whether path is a qcow2 image with a non-zero
|
|
// backing_file_offset in its header (i.e. a CoW overlay).
|
|
func HasQCOW2BackingFile(path string) (bool, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer f.Close()
|
|
var hdr [16]byte
|
|
if _, err := f.ReadAt(hdr[:], 0); err != nil {
|
|
return false, err
|
|
}
|
|
if string(hdr[:4]) != "QFI\xfb" {
|
|
return false, nil
|
|
}
|
|
return binary.BigEndian.Uint64(hdr[8:16]) != 0, nil
|
|
}
|
|
|
|
// BuildResizeDiskArgs builds `qemu-img resize` arguments.
|
|
func BuildResizeDiskArgs(diskPath, sizeArg string) []string {
|
|
return []string{"resize", diskPath, sizeArg}
|
|
}
|
|
|
|
// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments
|
|
// for reclaiming unallocated/trimmed space into a fresh sparse qcow2 file.
|
|
func BuildCompactDiskArgs(srcPath, dstPath string) []string {
|
|
return []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2", srcPath, dstPath}
|
|
}
|
|
|
|
// NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW)
|
|
// that should be converted to qcow2 via qemu-img before handing off to reims-ctl.
|
|
func NeedsDiskConversion(srcPath string) bool {
|
|
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath)))
|
|
return ext == ".vmdk" || ext == ".raw"
|
|
}
|
|
|
|
// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments.
|
|
func BuildConvertToQCOW2Args(srcPath, dstPath string) []string {
|
|
return []string{"convert", "-O", "qcow2", srcPath, dstPath}
|
|
}
|
|
|
|
// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b <backing> -F qcow2 <overlay>`
|
|
// arguments for instant copy-on-write VM derivation.
|
|
func BuildCoWOverlayArgs(backingPath, overlayPath string) []string {
|
|
return []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2", overlayPath}
|
|
}
|
|
|
|
// ConvertDiskToQCOW2 converts a VMDK or RAW disk image to qcow2 using the
|
|
// portable runtime's qemu-img binary.
|
|
func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, srcPath, dstPath string, stdout, stderr io.Writer) error {
|
|
if _, err := os.Stat(qemuImgPath); err != nil {
|
|
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
|
|
return err
|
|
}
|
|
cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...)
|
|
configureCmd(cmd)
|
|
cmd.Env = env
|
|
if stdout != nil {
|
|
cmd.Stdout = stdout
|
|
}
|
|
if stderr != nil {
|
|
cmd.Stderr = stderr
|
|
}
|
|
if err := cmd.Run(); err != nil {
|
|
_ = os.Remove(dstPath)
|
|
return fmt.Errorf("qemu-img convert %s: %w", filepath.Base(srcPath), err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CreateCoWOverlay creates an instant qcow2 copy-on-write overlay backed by
|
|
// backingPath without modifying the backing disk image.
|
|
func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, backingPath, overlayPath string, stdout, stderr io.Writer) error {
|
|
if _, err := os.Stat(qemuImgPath); err != nil {
|
|
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
|
}
|
|
if _, err := os.Stat(backingPath); err != nil {
|
|
return fmt.Errorf("backing disk not found (%s): %w", backingPath, err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(overlayPath), 0o755); err != nil {
|
|
return err
|
|
}
|
|
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath)...)
|
|
configureCmd(cmd)
|
|
cmd.Env = env
|
|
if stdout != nil {
|
|
cmd.Stdout = stdout
|
|
}
|
|
if stderr != nil {
|
|
cmd.Stderr = stderr
|
|
}
|
|
if err := cmd.Run(); err != nil {
|
|
_ = os.Remove(overlayPath)
|
|
return fmt.Errorf("qemu-img create CoW overlay: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ResizeDisk expands a stopped VM's disk image via `qemu-img resize`.
|
|
func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, sizeSpec string, stdout, stderr io.Writer) (DiskResizeResult, error) {
|
|
if _, err := os.Stat(qemuImgPath); err != nil {
|
|
return DiskResizeResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
|
}
|
|
before, err := host.InspectDiskUsage(diskPath)
|
|
if err != nil {
|
|
return DiskResizeResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
|
|
}
|
|
newBytes, arg, err := ParseResizeTarget(before.VirtualBytes, sizeSpec)
|
|
if err != nil {
|
|
return DiskResizeResult{}, err
|
|
}
|
|
cmd := exec.CommandContext(ctx, qemuImgPath, BuildResizeDiskArgs(diskPath, arg)...)
|
|
configureCmd(cmd)
|
|
cmd.Env = env
|
|
if stdout != nil {
|
|
cmd.Stdout = stdout
|
|
}
|
|
if stderr != nil {
|
|
cmd.Stderr = stderr
|
|
}
|
|
if err := cmd.Run(); err != nil {
|
|
return DiskResizeResult{}, fmt.Errorf("qemu-img resize %s %s: %w", filepath.Base(diskPath), arg, err)
|
|
}
|
|
after, err := host.InspectDiskUsage(diskPath)
|
|
if err == nil && after.VirtualBytes > 0 {
|
|
newBytes = after.VirtualBytes
|
|
}
|
|
return DiskResizeResult{
|
|
Path: diskPath,
|
|
OldVirtualBytes: before.VirtualBytes,
|
|
NewVirtualBytes: newBytes,
|
|
GuestExpandCmd: GuestAPFSExpandCommand,
|
|
}, nil
|
|
}
|
|
|
|
// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly
|
|
// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically
|
|
// swaps it into place to reclaim deleted/TRIMmed host disk space.
|
|
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) {
|
|
if _, err := os.Stat(qemuImgPath); err != nil {
|
|
return DiskCompactResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
|
|
}
|
|
before, err := host.InspectDiskUsage(diskPath)
|
|
if err != nil {
|
|
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
|
|
}
|
|
if before.Format != "qcow2" {
|
|
return DiskCompactResult{}, fmt.Errorf("only qcow2 disks can be compacted (found %s)", before.Format)
|
|
}
|
|
if hasBacking, err := HasQCOW2BackingFile(diskPath); err != nil {
|
|
return DiskCompactResult{}, err
|
|
} else if hasBacking {
|
|
return DiskCompactResult{}, fmt.Errorf("cannot compact a CoW overlay disk directly (it shares a backing image); compact the base VM instead")
|
|
}
|
|
|
|
dir := filepath.Dir(diskPath)
|
|
const safetyMarginBytes = uint64(2) << 30 // 2 GiB safety headroom
|
|
if freeBytes, ok := host.FreeDiskBytesAt(dir); ok {
|
|
need := before.ActualBytes + safetyMarginBytes
|
|
if freeBytes < need {
|
|
return DiskCompactResult{}, fmt.Errorf("not enough free space to compact safely: need ~%.1f GB free, only %.1f GB available",
|
|
float64(need)/float64(1<<30), float64(freeBytes)/float64(1<<30))
|
|
}
|
|
}
|
|
|
|
tmpPath := diskPath + ".compact.tmp"
|
|
bakPath := diskPath + ".compact.bak"
|
|
_ = os.Remove(tmpPath)
|
|
defer os.Remove(tmpPath)
|
|
|
|
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath)...)
|
|
configureCmd(cmd)
|
|
cmd.Env = env
|
|
if stdout != nil {
|
|
cmd.Stdout = stdout
|
|
}
|
|
if stderr != nil {
|
|
cmd.Stderr = stderr
|
|
}
|
|
if err := cmd.Run(); err != nil {
|
|
return DiskCompactResult{}, fmt.Errorf("qemu-img convert (compact): %w", err)
|
|
}
|
|
|
|
// Verify integrity of the compacted image before touching the original.
|
|
chk := exec.CommandContext(ctx, qemuImgPath, "check", "-q", tmpPath)
|
|
configureCmd(chk)
|
|
chk.Env = env
|
|
if out, err := chk.CombinedOutput(); err != nil {
|
|
return DiskCompactResult{}, fmt.Errorf("compacted qcow2 integrity check failed: %w (%s)", err, strings.TrimSpace(string(out)))
|
|
}
|
|
|
|
_ = os.Remove(bakPath)
|
|
if err := os.Rename(diskPath, bakPath); err != nil {
|
|
return DiskCompactResult{}, fmt.Errorf("swap disk backup: %w", err)
|
|
}
|
|
if err := os.Rename(tmpPath, diskPath); err != nil {
|
|
_ = os.Rename(bakPath, diskPath)
|
|
return DiskCompactResult{}, fmt.Errorf("replace compacted disk: %w", err)
|
|
}
|
|
_ = os.Remove(bakPath)
|
|
|
|
after, err := host.InspectDiskUsage(diskPath)
|
|
afterBytes := before.ActualBytes
|
|
if err == nil {
|
|
afterBytes = after.ActualBytes
|
|
}
|
|
var reclaimed uint64
|
|
if before.ActualBytes > afterBytes {
|
|
reclaimed = before.ActualBytes - afterBytes
|
|
}
|
|
return DiskCompactResult{
|
|
Path: diskPath,
|
|
BeforeBytes: before.ActualBytes,
|
|
AfterBytes: afterBytes,
|
|
ReclaimedBytes: reclaimed,
|
|
}, nil
|
|
}
|