Merge pull request #56 from reiasu2/feat/disk-perf-subclusters-defender

feat(disk,host,ui): add qcow2 extended_l2 optimization, snapshot rewrite guard, and Defender exclusion guidance
This commit is contained in:
Nwflower committed 2026-12-01 04:33:53 -07:00
commit b493b395e4
25 files changed
+676 -93

No files matched your search

+96 -23
View File
@@ -157,9 +157,10 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const [err, setErr] = useState('')
const [form, setForm] = useState<SetOpts>(base)
const [resizeInput, setResizeInput] = useState('+64G')
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | ''>('')
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('')
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
const [optimizeResult, setOptimizeResult] = useState<DiskCompactResult | null>(null)
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
const [driveBusy, setDriveBusy] = useState(false)
const driveBusyRef = useRef(false)
@@ -182,6 +183,9 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
useEffect(() => {
let live = true
setResizeResult(null)
setCompactResult(null)
setOptimizeResult(null)
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmSettingsKey)])
.then(([list, vals]) => {
if (!live) return
@@ -790,35 +794,76 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const handleResizeDisk = async () => {
if (running || diskOpBusy || !resizeInput.trim()) return
const vmName = detail.name
setErr('')
setDiskOpBusy('resize')
try {
const res = await api.ResizeVMDiskWithDriver(driverID, detail.name, resizeInput.trim())
setResizeResult(res)
const res = await api.ResizeVMDiskWithDriver(driverID, vmName, resizeInput.trim())
if (activeVMNameRef.current === vmName) {
setResizeResult(res)
}
onDiskChanged?.()
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setDiskOpBusy('')
}
}
const handleCompactDisk = async () => {
if (running || diskOpBusy) return
setErr('')
setDiskOpBusy('compact')
try {
const res = await api.CompactVMDiskWithDriver(driverID, detail.name)
setCompactResult(res)
onDiskChanged?.()
} catch (e) {
setErr(parseAppError(e).summary)
if (activeVMNameRef.current === vmName) {
setErr(parseAppError(e).summary)
}
} finally {
setDiskOpBusy('')
}
}
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp')
: (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots')
: (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay')
: !isQcow2 ? tr('diskCompactQcow2Only')
: undefined
const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined)
const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined)
const handleCompactDisk = async (optimize: boolean) => {
if (diskRewriteBaseReason || diskOpBusy) return
const vmName = detail.name
setErr('')
setDiskOpBusy(optimize ? 'optimize' : 'compact')
try {
if (optimize) {
const res = await api.OptimizeVMDiskWithDriver(driverID, vmName)
if (activeVMNameRef.current === vmName) {
setOptimizeResult(res)
setCompactResult(null)
}
} else {
const res = await api.CompactVMDiskWithDriver(driverID, vmName)
if (activeVMNameRef.current === vmName) {
setCompactResult(res)
}
}
onDiskChanged?.()
} catch (e) {
if (activeVMNameRef.current === vmName) {
setErr(parseAppError(e).summary)
}
} finally {
setDiskOpBusy('')
}
}
const handleDefender = async (copy: boolean) => {
setErr('')
try {
if (copy) {
const command = await api.GetDefenderExclusionCommand()
if (command) onCopy?.(command)
} else {
await api.OpenWindowsSecurityExclusions()
}
} catch (e) {
setErr(parseAppError(e).summary)
}
}
const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled
const diskControllerDesc = detail.has_installer
? tr('diskControllerInstallHint')
: form.disk_controller === 'virtio'
@@ -937,19 +982,47 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
})
: tr('diskCompactNoGain')
: tr('diskCompactDesc')}
disabled={running || !isQcow2}
reason={running ? tr('stopBeforeDiskOp') : tr('diskCompactQcow2Only')}
disabled={!!compactRowReason}
reason={compactRowReason}
control={
<Button
variant="secondary"
busy={diskOpBusy === 'compact'}
disabled={running || !isQcow2 || !!diskOpBusy}
onClick={handleCompactDisk}
disabled={!!compactRowReason || !!diskOpBusy}
onClick={() => handleCompactDisk(false)}
>
{tr('diskCompactAction')}
</Button>
}
/>
<SetRow
title={tr('diskOptimizeTitle')}
desc={optimizeResult ? tr('diskOptimizeDone', {
before: formatBytes(optimizeResult.before_bytes, locale),
after: formatBytes(optimizeResult.after_bytes, locale),
reclaimed: formatBytes(optimizeResult.reclaimed_bytes, locale),
status: tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeInactive'),
}) : tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeDesc')}
disabled={!extendedL2 && !!optimizeRowReason}
reason={extendedL2 ? undefined : optimizeRowReason}
control={extendedL2 ? undefined : (
<Button variant="secondary" busy={diskOpBusy === 'optimize'} disabled={!!optimizeRowReason || !!diskOpBusy} onClick={() => handleCompactDisk(true)}>
{tr('diskOptimizeAction')}
</Button>
)}
/>
{host.defender_realtime_active && (
<SetRow
title={tr('defenderExclusionTitle')}
desc={tr('defenderExclusionDesc', { path: host.data_root })}
control={
<div className="hstack">
<Button variant="secondary" onClick={() => handleDefender(false)}>{tr('defenderOpenSecurity')}</Button>
{onCopy && <Button variant="secondary" onClick={() => handleDefender(true)}>{tr('defenderCopyCommand')}</Button>}
</div>
}
/>
)}
</SetGroup>
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
<SetRow
+26
View File
@@ -100,6 +100,10 @@ export const settingsZh: Record<string, string> = {
"coresUnit": "核",
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
"cpuRecHint": "推荐 {rec} 核 · 本机共 {n} 线程",
"defenderCopyCommand": "复制排除命令",
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
"defenderOpenSecurity": "打开 Windows 安全中心",
"diskCompactAction": "立即回收",
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
@@ -115,10 +119,19 @@ export const settingsZh: Record<string, string> = {
"diskMode": "使用方式",
"diskModeCopy": "复制一份,不改动原盘",
"diskModeInPlace": "直接使用原盘",
"diskOptimizeAction": "优化磁盘结构",
"diskOptimizeDesc": "默认 64 KiB 簇可划分为 2 KiB 子簇,减少小块写入的开销,同时整理磁盘并回收空间。",
"diskOptimizeDone": "{before} → {after},已回收 {reclaimed}。{status}。",
"diskOptimizeEnabled": "已启用 extended_l2",
"diskOptimizeInactive": "extended_l2 未启用",
"diskOptimizeTitle": "QCOW2 子簇优化",
"diskResizeAction": "扩容",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeTitle": "扩大磁盘",
"diskRewriteBusy": "正在进行另一项磁盘操作。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
"diskSize": "磁盘上限",
"diskSizeHint": "按实际占用增长",
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
@@ -448,6 +461,10 @@ export const settingsEn: Record<string, string> = {
"coresUnit": "cores",
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
"cpuRecHint": "{rec} cores recommended · this PC has {n} threads",
"defenderCopyCommand": "Copy exclusion command",
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
"defenderOpenSecurity": "Open Windows Security",
"diskCompactAction": "Reclaim now",
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
@@ -463,10 +480,19 @@ export const settingsEn: Record<string, string> = {
"diskMode": "Use disk as",
"diskModeCopy": "A copy — original untouched",
"diskModeInPlace": "In place",
"diskOptimizeAction": "Optimize disk layout",
"diskOptimizeDesc": "Splits default 64 KiB clusters into 2 KiB subclusters to reduce small-write overhead while compacting the disk.",
"diskOptimizeDone": "{before} → {after}, reclaimed {reclaimed}. {status}.",
"diskOptimizeEnabled": "extended_l2 is enabled",
"diskOptimizeInactive": "extended_l2 is inactive",
"diskOptimizeTitle": "QCOW2 subcluster optimization",
"diskResizeAction": "Expand",
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskResizeTitle": "Expand disk",
"diskRewriteBusy": "Another disk operation is in progress.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
"diskRewriteSnapshots": "Delete internal restore points first to preserve them when rewriting the disk.",
"diskSize": "Disk size",
"diskSizeHint": "Grows as it fills",
"diskUsageSummary": "{actual} used of {virtual}",
+13
View File
@@ -134,6 +134,10 @@ export type I18nKey =
| "dataRootReadOnlyTitle"
| "dataRootRepair"
| "dataRootRetry"
| "defenderCopyCommand"
| "defenderExclusionDesc"
| "defenderExclusionTitle"
| "defenderOpenSecurity"
| "delete"
| "deleteConfirm"
| "deleteDesc"
@@ -167,10 +171,19 @@ export type I18nKey =
| "diskMode"
| "diskModeCopy"
| "diskModeInPlace"
| "diskOptimizeAction"
| "diskOptimizeDesc"
| "diskOptimizeDone"
| "diskOptimizeEnabled"
| "diskOptimizeInactive"
| "diskOptimizeTitle"
| "diskResizeAction"
| "diskResizeDesc"
| "diskResizeDone"
| "diskResizeTitle"
| "diskRewriteBusy"
| "diskRewriteOverlay"
| "diskRewriteSnapshots"
| "diskSize"
| "diskSizeHint"
| "diskUsageSummary"
+8
View File
@@ -37,6 +37,14 @@ export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function OpenWindowsSecurityExclusions():Promise<void>;
export function GetDefenderExclusionCommand():Promise<string>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string):Promise<void>;
+16
View File
@@ -54,6 +54,22 @@ export function CompactVMDiskWithDriver(arg1, arg2) {
return window['go']['app']['App']['CompactVMDiskWithDriver'](arg1, arg2);
}
export function OptimizeVMDisk(arg1) {
return window['go']['app']['App']['OptimizeVMDisk'](arg1);
}
export function OptimizeVMDiskWithDriver(arg1, arg2) {
return window['go']['app']['App']['OptimizeVMDiskWithDriver'](arg1, arg2);
}
export function OpenWindowsSecurityExclusions() {
return window['go']['app']['App']['OpenWindowsSecurityExclusions']();
}
export function GetDefenderExclusionCommand() {
return window['go']['app']['App']['GetDefenderExclusionCommand']();
}
export function CompleteSetup(arg1) {
return window['go']['app']['App']['CompleteSetup'](arg1);
}
+8
View File
@@ -414,6 +414,8 @@ export namespace app {
disk_virtual_bytes: number;
disk_format?: string;
disk_backing_depth?: number;
disk_extended_l2?: boolean;
disk_snapshot_count?: number;
disk_backing_broken?: boolean;
disk_backing_depth_warn?: boolean;
uptime_seconds: number;
@@ -439,6 +441,8 @@ export namespace app {
this.disk_virtual_bytes = source["disk_virtual_bytes"];
this.disk_format = source["disk_format"];
this.disk_backing_depth = source["disk_backing_depth"];
this.disk_extended_l2 = source["disk_extended_l2"];
this.disk_snapshot_count = source["disk_snapshot_count"];
this.disk_backing_broken = source["disk_backing_broken"];
this.disk_backing_depth_warn = source["disk_backing_depth_warn"];
this.uptime_seconds = source["uptime_seconds"];
@@ -551,6 +555,7 @@ export namespace driver {
}
}
export class DiskCompactResult {
extended_l2_enabled?: boolean;
path: string;
before_bytes: number;
after_bytes: number;
@@ -562,6 +567,7 @@ export namespace driver {
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.extended_l2_enabled = source["extended_l2_enabled"];
this.path = source["path"];
this.before_bytes = source["before_bytes"];
this.after_bytes = source["after_bytes"];
@@ -924,6 +930,7 @@ export namespace host {
commit_limit_gb: number;
data_root: string;
data_root_drive_type?: string;
defender_realtime_active?: boolean;
deep_backing_chains?: BackingChainIssue[];
free_disk_gb: number;
whpx: string;
@@ -971,6 +978,7 @@ export namespace host {
this.commit_limit_gb = source["commit_limit_gb"];
this.data_root = source["data_root"];
this.data_root_drive_type = source["data_root_drive_type"];
this.defender_realtime_active = source["defender_realtime_active"];
this.deep_backing_chains = this.convertValues(source["deep_backing_chains"], BackingChainIssue);
this.free_disk_gb = source["free_disk_gb"];
this.whpx = source["whpx"];
+12
View File
@@ -28,6 +28,18 @@ import (
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) OpenWindowsSecurityExclusions() error {
a.emitLog("host", "Opening Windows Security settings...")
return host.OpenWindowsSecurityExclusions()
}
func (a *App) GetDefenderExclusionCommand() string {
a.mu.Lock()
dataRoot := a.cfg.DataRoot
a.mu.Unlock()
return host.DefenderExclusionCommand(dataRoot)
}
type PendingChange struct {
Field string `json:"field"`
From string `json:"from"`
+31 -5
View File
@@ -43,6 +43,18 @@ func (a *App) CompactVMDisk(name string) (driver.DiskCompactResult, error) {
return a.CompactVMDiskWithDriver("", name)
}
func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
return a.runCompactVMDisk(driverID, name, false)
}
// OptimizeVMDisk rewrites a stopped VM's qcow2 disk with extended L2 subclusters.
func (a *App) OptimizeVMDisk(name string) (driver.DiskCompactResult, error) {
return a.OptimizeVMDiskWithDriver("", name)
}
func (a *App) OptimizeVMDiskWithDriver(driverID, name string) (driver.DiskCompactResult, error) {
return a.runCompactVMDisk(driverID, name, true)
}
func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.DiskCompactResult, error) {
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
@@ -52,16 +64,30 @@ func (a *App) CompactVMDiskWithDriver(driverID, name string) (driver.DiskCompact
ref := driver.VMRef{DriverID: driverID, Name: name}
taskCtx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-compact", ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacting disk for %s to reclaim unused space...", name))
res, err := svc.CompactDisk(taskCtx, ref, w, w)
taskKind := "vm-disk-compact"
message := fmt.Sprintf("Compacting disk for %s to reclaim unused space...", name)
if optimize {
taskKind = "vm-disk-optimize"
message = fmt.Sprintf("Optimizing qcow2 disk for %s with extended L2 subclusters...", name)
}
_, w, finishTask := a.ctlTaskWriterWithCancel(taskKind, ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, message)
var (
res driver.DiskCompactResult
err error
)
if optimize {
res, err = svc.OptimizeDisk(taskCtx, ref, w, w)
} else {
res, err = svc.CompactDisk(taskCtx, ref, w, w)
}
if err != nil {
finishTask(err)
a.emitVMLogForDriver(driverID, name, "Disk compact error: "+err.Error())
a.emitVMLogForDriver(driverID, name, "Disk rewrite error: "+err.Error())
return driver.DiskCompactResult{}, err
}
finishTask(nil)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Compacted disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Rewrote disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB, extended L2: %t)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30), res.ExtendedL2Enabled))
a.wakePoll()
a.emitLifecycleStateChanged()
return res, nil
+71
View File
@@ -0,0 +1,71 @@
package app
import (
"context"
"encoding/binary"
"os"
"path/filepath"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
)
type stubStatsDriver struct {
diskPath string
}
func (d stubStatsDriver) ID() string { return driver.BuiltinReimsMacOSDriverID }
func (d stubStatsDriver) Capabilities() []string { return nil }
func (d stubStatsDriver) List(context.Context) ([]driver.VMInfo, error) { return []driver.VMInfo{{Name: "test", DriverID: d.ID(), State: "stopped", DiskPath: d.diskPath}}, nil }
func (d stubStatsDriver) Inspect(context.Context, string) (driver.VMInfo, error) {
return driver.VMInfo{Name: "test", DriverID: d.ID(), State: "stopped", DiskPath: d.diskPath}, nil
}
func (d stubStatsDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
return driver.StartResult{}, nil
}
func (d stubStatsDriver) Stop(context.Context, string, bool, interface{ Write([]byte) (int, error) }, interface{ Write([]byte) (int, error) }) error {
return nil
}
func TestGetDefenderExclusionCommand(t *testing.T) {
a := &App{cfg: &config.Config{DataRoot: `D:\Rei's VMs`}}
const want = `Add-MpPreference -ExclusionPath 'D:\Rei''s VMs' -ExclusionProcess 'qemu-system-x86_64.exe'`
if got := a.GetDefenderExclusionCommand(); got != want {
t.Fatalf("GetDefenderExclusionCommand = %q, want %q", got, want)
}
}
func TestVMStatsDiskHeaderMeta(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
runtimeDir := filepath.Join(cfg.RuntimesDir(), "test")
if err := os.MkdirAll(runtimeDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte(`{"commit":"test"}`), 0o644); err != nil {
t.Fatal(err)
}
disk := filepath.Join(cfg.DataRoot, "disk.qcow2")
hdr := make([]byte, 104)
copy(hdr, "QFI\xfb")
binary.BigEndian.PutUint32(hdr[4:8], 3)
binary.BigEndian.PutUint32(hdr[60:64], 2)
binary.BigEndian.PutUint64(hdr[72:80], 0x10)
if err := os.WriteFile(disk, hdr, 0o644); err != nil {
t.Fatal(err)
}
router := driver.NewRouter()
router.Register(stubStatsDriver{diskPath: disk})
a := &App{
cfg: cfg,
lastVMsAt: time.Now(),
lifecycleSvc: vmlifecycle.New(router, nil),
}
stats, err := a.GetVMStats("test")
if err != nil || !stats.DiskExtendedL2 || stats.DiskSnapshotCount != 2 {
t.Fatalf("GetVMStats = %+v, %v", stats, err)
}
}
+4
View File
@@ -20,6 +20,8 @@ type VMStats struct {
DiskActualBytes uint64 `json:"disk_actual_bytes"`
DiskVirtualBytes uint64 `json:"disk_virtual_bytes"`
DiskFormat string `json:"disk_format,omitempty"`
DiskExtendedL2 bool `json:"disk_extended_l2,omitempty"`
DiskSnapshotCount uint32 `json:"disk_snapshot_count,omitempty"`
DiskBackingDepth int `json:"disk_backing_depth,omitempty"`
DiskBackingBroken bool `json:"disk_backing_broken,omitempty"`
DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"`
@@ -56,6 +58,8 @@ func (a *App) GetVMStatsWithDriver(driverID, name string) (VMStats, error) {
stats.DiskActualBytes = du.ActualBytes
stats.DiskVirtualBytes = du.VirtualBytes
stats.DiskFormat = du.Format
stats.DiskExtendedL2 = du.ExtendedL2
stats.DiskSnapshotCount = du.SnapshotCount
stats.DiskBackingDepth = du.BackingDepth
stats.DiskBackingBroken = du.BackingBroken
stats.DiskBackingDepthWarn = du.BackingDepth >= host.BackingChainWarnDepth || du.BackingBroken
+11 -4
View File
@@ -25,10 +25,11 @@ type DiskResizeResult struct {
// DiskCompactResult describes host space reclaimed by rewriting a disk.
type DiskCompactResult struct {
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
ExtendedL2Enabled bool `json:"extended_l2_enabled,omitempty"`
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
}
// ValidateSnapshotName checks a restore-point tag without assuming a disk engine.
@@ -64,3 +65,9 @@ type DiskDriver interface {
ResizeDisk(context.Context, string, string, io.Writer, io.Writer) (DiskResizeResult, error)
CompactDisk(context.Context, string, io.Writer, io.Writer) (DiskCompactResult, error)
}
// DiskOptimizer is an optional extension for drivers that can rewrite a disk
// with performance-oriented image options (such as qcow2 extended_l2 subclusters).
type DiskOptimizer interface {
OptimizeDisk(context.Context, string, io.Writer, io.Writer) (DiskCompactResult, error)
}
+23
View File
@@ -0,0 +1,23 @@
package host
import "strings"
func DefenderExclusionCommand(dataRoot string) string {
var b strings.Builder
b.Grow(len(dataRoot))
for _, r := range dataRoot {
// Strip ASCII control chars and Unicode line/paragraph separators so
// copied PowerShell commands can never break out onto a second line.
if r < 0x20 || r == 0x7f || r == '\u0085' || r == '\u2028' || r == '\u2029' {
continue
}
b.WriteRune(r)
}
path := strings.TrimSpace(b.String())
if path == "" {
return ""
}
// PowerShell also recognizes typographic single quotes as delimiters.
path = strings.NewReplacer("'", "''", "‘", "‘‘", "’", "’’", "‚", "‚‚", "‛", "‛‛").Replace(path)
return "Add-MpPreference -ExclusionPath '" + path + "' -ExclusionProcess 'qemu-system-x86_64.exe'"
}
+11
View File
@@ -0,0 +1,11 @@
//go:build !windows
package host
import "errors"
func probeDefenderRealtime() bool { return false }
func OpenWindowsSecurityExclusions() error {
return errors.New("Windows Security is only available on Windows")
}
+20
View File
@@ -0,0 +1,20 @@
package host
import "testing"
func TestDefenderExclusionCommand(t *testing.T) {
for input, escaped := range map[string]string{
` D:\VM Data `: `D:\VM Data`,
`D:\Rei's ‘VM’`: `D:\Rei''s ‘‘VM’’`,
"D:\\VM\r\n\x00\x1b\t\u2028Data": `D:\VMData`,
" \r\n\x00\t": "",
} {
want := ""
if escaped != "" {
want = "Add-MpPreference -ExclusionPath '" + escaped + "' -ExclusionProcess 'qemu-system-x86_64.exe'"
}
if got := DefenderExclusionCommand(input); got != want {
t.Errorf("DefenderExclusionCommand(%q) = %q, want %q", input, got, want)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package host
import (
"errors"
"fmt"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
func probeDefenderRealtime() bool {
start, err := defenderDWORD(`SYSTEM\CurrentControlSet\Services\WinDefend`, "Start")
if err != nil || start == windows.SERVICE_DISABLED {
return false
}
for _, root := range []string{`SOFTWARE\Microsoft\Windows Defender`, `SOFTWARE\Policies\Microsoft\Windows Defender`} {
disabled, _ := defenderDWORD(root, "DisableAntiSpyware")
passive, _ := defenderDWORD(root, "PassiveMode")
realtimeDisabled, _ := defenderDWORD(root+`\Real-Time Protection`, "DisableRealtimeMonitoring")
if disabled == 1 || passive == 1 || realtimeDisabled == 1 {
return false
}
}
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
if err != nil {
return true
}
defer windows.CloseServiceHandle(manager)
service, err := windows.OpenService(manager, windows.StringToUTF16Ptr("WinDefend"), windows.SERVICE_QUERY_STATUS)
if err != nil {
if errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
return false
}
return true
}
defer windows.CloseServiceHandle(service)
var status windows.SERVICE_STATUS
return windows.QueryServiceStatus(service, &status) != nil || status.CurrentState == windows.SERVICE_RUNNING
}
func defenderDWORD(path, name string) (uint64, error) {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
if err != nil {
return 0, err
}
defer key.Close()
value, _, err := key.GetIntegerValue(name)
return value, err
}
func OpenWindowsSecurityExclusions() error {
err := windows.ShellExecute(0, windows.StringToUTF16Ptr("open"), windows.StringToUTF16Ptr("windowsdefender://threatsettings/"), nil, nil, windows.SW_SHOWNORMAL)
if err != nil {
return fmt.Errorf("open Windows Security: %w", err)
}
return nil
}
+44
View File
@@ -194,6 +194,50 @@ func TestInspectDiskUsageQCOW2(t *testing.T) {
}
}
func TestInspectDiskUsageHeaderMeta(t *testing.T) {
for _, tc := range []struct {
name string
version uint32
length int
snapshots uint32
incompatible uint64
wantFormat string
extended bool
wantSnaps uint32
}{
{"v2", 2, 72, 0, 0, "qcow2", false, 0},
{"v2 truncated", 2, 64, 1, 0, "raw", false, 0},
{"v3 snapshots", 3, 104, 2, 0, "qcow2", false, 2},
{"v3 truncated", 3, 80, 2, 0x10, "raw", false, 0},
{"v3 extended L2", 3, 104, 0, 0x10, "qcow2", true, 0},
{"raw", 0, 104, 0, 0, "raw", false, 0},
} {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "disk.img")
hdr := make([]byte, 104)
size := uint64(tc.length)
if tc.version != 0 {
copy(hdr, "QFI\xfb")
binary.BigEndian.PutUint32(hdr[4:8], tc.version)
binary.BigEndian.PutUint64(hdr[24:32], 128<<30)
binary.BigEndian.PutUint32(hdr[60:64], tc.snapshots)
binary.BigEndian.PutUint64(hdr[72:80], tc.incompatible)
if tc.wantFormat == "qcow2" {
size = 128 << 30
}
}
hdr = hdr[:tc.length]
if err := os.WriteFile(path, hdr, 0o644); err != nil {
t.Fatal(err)
}
got, err := InspectDiskUsage(path)
if err != nil || got.Format != tc.wantFormat || got.VirtualBytes != size || got.ExtendedL2 != tc.extended || got.SnapshotCount != tc.wantSnaps {
t.Fatalf("InspectDiskUsage = %+v, %v (want format=%s size=%d ext=%v snaps=%d)", got, err, tc.wantFormat, size, tc.extended, tc.wantSnaps)
}
})
}
}
func writeTestQCOW2(t *testing.T, path, backing string) {
t.Helper()
hdr := make([]byte, 512)
+37 -36
View File
@@ -58,50 +58,51 @@ type LogicalCPUInfo struct {
}
type Report struct {
OS string `json:"os"`
Arch string `json:"arch"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
MemoryLoadPct int `json:"memory_load_pct"`
MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"`
DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"`
OS string `json:"os"`
Arch string `json:"arch"`
LogicalCPUs int `json:"logical_cpus"`
PhysicalCores int `json:"physical_cores"`
HasHybridCores bool `json:"has_hybrid_cores"`
PCoreCount int `json:"p_core_count"`
ECoreCount int `json:"e_core_count"`
LPECoreCount int `json:"lpe_core_count,omitempty"`
PCoreMask uint64 `json:"p_core_mask"`
PCoreMaskHex string `json:"p_core_mask_hex"`
PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"`
ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"`
NonLPEMask uint64 `json:"non_lpe_mask,omitempty"`
NonLPEMaskHex string `json:"non_lpe_mask_hex,omitempty"`
NonLPELogicalCPUs []int `json:"non_lpe_logical_cpus,omitempty"`
CPUTopology []LogicalCPUInfo `json:"cpu_topology,omitempty"`
TotalRAMGB float64 `json:"total_ram_gb"`
AvailRAMGB float64 `json:"avail_ram_gb"`
MemoryLoadPct int `json:"memory_load_pct"`
MemorySpec *HostMemorySpec `json:"memory_spec,omitempty"`
// Commit memory: QEMU commits all guest RAM at start (CreateFileMapping), so
// a VM needs its memory free in the commit charge, not just in physical RAM.
// Measured 2026-11-28: 14.7 GiB commit free with 17.3 GiB physical free, and a
// 16G guest failed ("Cannot set up guest memory"). portable-runtime-spec.md §5.1.
CommitAvailGB float64 `json:"commit_avail_gb"`
CommitLimitGB float64 `json:"commit_limit_gb"`
CommitAvailGB float64 `json:"commit_avail_gb"`
CommitLimitGB float64 `json:"commit_limit_gb"`
DataRoot string `json:"data_root"`
DataRootDriveType string `json:"data_root_drive_type,omitempty"`
DeepBackingChains []BackingChainIssue `json:"deep_backing_chains,omitempty"`
FreeDiskGB float64 `json:"free_disk_gb"`
WHPX WHPXState `json:"whpx"`
WHPXCaps WHPXCapabilities `json:"whpx_caps"`
NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"`
GPUs []GPUInfo `json:"gpus"`
VulkanProbeError string `json:"vulkan_probe_error,omitempty"`
RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"`
Displays []DisplayInfo `json:"displays,omitempty"`
PrimaryDisplay *DisplayInfo `json:"primary_display,omitempty"`
RecommendedResolution string `json:"recommended_resolution,omitempty"`
DisplayPresets []DisplayPreset `json:"display_presets,omitempty"`
HiDPIAdvice string `json:"hidpi_advice,omitempty"` // how to reach HiDPI when no preset does (display.go)
FullscreenHiDPI bool `json:"fullscreen_hidpi"` // a borderless window on the primary screen is HiDPI
ProcessorScheduling string `json:"processor_scheduling,omitempty"` // "programs" or "background" (scheduling.go)
Audio AudioInfo `json:"audio"`
WHPX WHPXState `json:"whpx"`
WHPXCaps WHPXCapabilities `json:"whpx_caps"`
NeedsColdRebootWorkaround bool `json:"needs_cold_reboot_workaround"`
GPUs []GPUInfo `json:"gpus"`
VulkanProbeError string `json:"vulkan_probe_error,omitempty"`
RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"`
Displays []DisplayInfo `json:"displays,omitempty"`
PrimaryDisplay *DisplayInfo `json:"primary_display,omitempty"`
RecommendedResolution string `json:"recommended_resolution,omitempty"`
DisplayPresets []DisplayPreset `json:"display_presets,omitempty"`
HiDPIAdvice string `json:"hidpi_advice,omitempty"` // how to reach HiDPI when no preset does (display.go)
FullscreenHiDPI bool `json:"fullscreen_hidpi"` // a borderless window on the primary screen is HiDPI
ProcessorScheduling string `json:"processor_scheduling,omitempty"` // "programs" or "background" (scheduling.go)
Audio AudioInfo `json:"audio"`
}
// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters
+1
View File
@@ -126,6 +126,7 @@ func Inspect(dataRoot string) Report {
memSpecCopy = &cp
}
rep := Report{
DefenderRealtimeActive: probeDefenderRealtime(),
OS: "windows",
Arch: runtime.GOARCH,
LogicalCPUs: runtime.NumCPU(),
+31 -10
View File
@@ -2,6 +2,8 @@ package host
import (
"encoding/binary"
"errors"
"io"
"os"
"path/filepath"
"sort"
@@ -40,6 +42,8 @@ type DiskUsage struct {
Format string `json:"format,omitempty"`
BackingDepth int `json:"backing_depth,omitempty"`
BackingBroken bool `json:"backing_broken,omitempty"`
ExtendedL2 bool `json:"extended_l2,omitempty"`
SnapshotCount uint32 `json:"snapshot_count,omitempty"`
}
// ComputeCPUPercent computes host CPU utilization percentage between two samples.
@@ -83,8 +87,10 @@ func InspectDiskUsage(path string) (DiskUsage, error) {
VirtualBytes: uint64(info.Size()),
Format: "raw",
}
if vSize, ok := readQCOW2VirtualSize(path); ok {
if vSize, extendedL2, snapshotCount, ok := readQCOW2HeaderMeta(path); ok {
usage.VirtualBytes = vSize
usage.ExtendedL2 = extendedL2
usage.SnapshotCount = snapshotCount
usage.Format = "qcow2"
usage.BackingDepth, usage.BackingBroken = InspectQCOW2BackingDepth(path)
}
@@ -226,21 +232,36 @@ func resolveDiskPathFromVMToml(vmDir string) string {
// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2
// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24).
func readQCOW2VirtualSize(path string) (uint64, bool) {
size, _, _, ok := readQCOW2HeaderMeta(path)
return size, ok
}
func readQCOW2HeaderMeta(path string) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) {
f, err := os.Open(path)
if err != nil {
return 0, false
return 0, false, 0, false
}
defer f.Close()
var hdr [32]byte
if _, err := f.ReadAt(hdr[:], 0); err != nil {
return 0, false
var hdr [104]byte
n, err := f.ReadAt(hdr[:], 0)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return 0, false, 0, false
}
if hdr[0] != 'Q' || hdr[1] != 'F' || hdr[2] != 'I' || hdr[3] != 0xfb {
return 0, false
if n < 72 || string(hdr[:4]) != "QFI\xfb" {
return 0, false, 0, false
}
ver := binary.BigEndian.Uint32(hdr[4:8])
if ver < 2 || ver > 3 {
return 0, false
switch ver {
case 2:
// qcow2 v2 header is 72 bytes.
case 3:
if n < 104 {
return 0, false, 0, false
}
extendedL2 = binary.BigEndian.Uint64(hdr[72:80])&0x10 != 0
default:
return 0, false, 0, false
}
return binary.BigEndian.Uint64(hdr[24:32]), true
snapshotCount = binary.BigEndian.Uint32(hdr[60:64])
return binary.BigEndian.Uint64(hdr[24:32]), extendedL2, snapshotCount, true
}
+12
View File
@@ -67,3 +67,15 @@ func (s *Service) CompactDisk(ctx context.Context, ref driver.VMRef, stdout, std
}
return disks.CompactDisk(ctx, vm.Name, stdout, stderr)
}
func (s *Service) OptimizeDisk(ctx context.Context, ref driver.VMRef, stdout, stderr io.Writer) (driver.DiskCompactResult, error) {
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
if err != nil {
return driver.DiskCompactResult{}, err
}
opt, ok := d.(driver.DiskOptimizer)
if !ok {
return driver.DiskCompactResult{}, fmt.Errorf("driver %q does not support disk optimization", d.ID())
}
return opt.OptimizeDisk(ctx, vm.Name, stdout, stderr)
}
+17 -3
View File
@@ -141,6 +141,14 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string,
}
func (d *ReimsMacOSDriver) CompactDisk(ctx context.Context, name string, stdout, stderr io.Writer) (driver.DiskCompactResult, error) {
return d.compactDiskWithOptions(ctx, name, reims.CompactDiskOptions{}, stdout, stderr)
}
func (d *ReimsMacOSDriver) OptimizeDisk(ctx context.Context, name string, stdout, stderr io.Writer) (driver.DiskCompactResult, error) {
return d.compactDiskWithOptions(ctx, name, reims.CompactDiskOptions{EnableExtendedL2: true}, stdout, stderr)
}
func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name string, opts reims.CompactDiskOptions, stdout, stderr io.Writer) (driver.DiskCompactResult, error) {
c, active, err := d.startClient()
if err != nil {
return driver.DiskCompactResult{}, err
@@ -151,7 +159,7 @@ func (d *ReimsMacOSDriver) CompactDisk(ctx context.Context, name string, stdout,
}
defer release()
if vmRunning(ctx, c, name, det) {
return driver.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
return driver.DiskCompactResult{}, fmt.Errorf("stop %s before rewriting its disk", name)
}
if reims.HasSuspendState(det.Directory) {
return driver.DiskCompactResult{}, i18n.NewCodedError(c.Locale, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
@@ -161,9 +169,15 @@ func (d *ReimsMacOSDriver) CompactDisk(ctx context.Context, name string, stdout,
return driver.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
}
cfg := d.getConfig()
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, stdout, stderr)
res, err := reims.CompactDiskWithOptions(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr)
if err != nil {
return driver.DiskCompactResult{}, err
}
return driver.DiskCompactResult{Path: res.Path, BeforeBytes: res.BeforeBytes, AfterBytes: res.AfterBytes, ReclaimedBytes: res.ReclaimedBytes}, nil
return driver.DiskCompactResult{
ExtendedL2Enabled: res.ExtendedL2Enabled,
Path: res.Path,
BeforeBytes: res.BeforeBytes,
AfterBytes: res.AfterBytes,
ReclaimedBytes: res.ReclaimedBytes,
}, nil
}
+44 -12
View File
@@ -29,10 +29,29 @@ type DiskResizeResult struct {
}
type DiskCompactResult struct {
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
ExtendedL2Enabled bool `json:"extended_l2_enabled,omitempty"`
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
}
type CompactDiskOptions struct {
EnableExtendedL2 bool
}
func ResolveCompactQCOW2Options(src QCOW2CreateOptions, opts CompactDiskOptions) QCOW2CreateOptions {
if !opts.EnableExtendedL2 {
return src
}
if src.Compat == "" || src.Compat == "0.10" {
src.Compat = "1.1"
}
src.ExtendedL2 = boolPtr(true)
if src.ClusterSize == 0 {
src.ClusterSize = 65536
}
return src
}
var reResizeSpec = regexp.MustCompile(`^(?i)(\+)?\s*(\d+)\s*([GM])$`)
@@ -370,9 +389,10 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath,
// 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)
}
return CompactDiskWithOptions(ctx, qemuImgPath, env, diskPath, CompactDiskOptions{}, stdout, stderr)
}
func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) {
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
@@ -385,6 +405,12 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath
} else if hasBacking {
return DiskCompactResult{}, fmt.Errorf("cannot compact a CoW overlay disk directly (it shares a backing image); compact the base VM instead")
}
if before.SnapshotCount > 0 {
return DiskCompactResult{}, fmt.Errorf("cannot compact or optimize a qcow2 disk while it has %d restore point(s); delete internal snapshots first so they are not lost", before.SnapshotCount)
}
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskCompactResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
dir := filepath.Dir(diskPath)
const safetyMarginBytes = uint64(2) << 30 // 2 GiB safety headroom
@@ -400,6 +426,7 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect source qcow2 options: %w", err)
}
opts = ResolveCompactQCOW2Options(opts, compactOpts)
tmpPath := diskPath + ".compact.tmp"
bakPath := diskPath + ".compact.bak"
@@ -432,24 +459,29 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath
return DiskCompactResult{}, fmt.Errorf("swap disk backup: %w", err)
}
if err := os.Rename(tmpPath, diskPath); err != nil {
_ = os.Rename(bakPath, diskPath)
if restoreErr := os.Rename(bakPath, diskPath); restoreErr != nil {
return DiskCompactResult{}, fmt.Errorf("replace compacted disk: %w (rollback from %s also failed: %v)", err, bakPath, restoreErr)
}
return DiskCompactResult{}, fmt.Errorf("replace compacted disk: %w", err)
}
_ = os.Remove(bakPath)
after, err := host.InspectDiskUsage(diskPath)
afterBytes := before.ActualBytes
extendedL2 := opts.ExtendedL2 != nil && *opts.ExtendedL2
if err == nil {
afterBytes = after.ActualBytes
extendedL2 = after.ExtendedL2
}
var reclaimed uint64
if before.ActualBytes > afterBytes {
reclaimed = before.ActualBytes - afterBytes
}
return DiskCompactResult{
Path: diskPath,
BeforeBytes: before.ActualBytes,
AfterBytes: afterBytes,
ReclaimedBytes: reclaimed,
ExtendedL2Enabled: extendedL2,
Path: diskPath,
BeforeBytes: before.ActualBytes,
AfterBytes: afterBytes,
ReclaimedBytes: reclaimed,
}, nil
}
+57
View File
@@ -6,9 +6,66 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestResolveCompactQCOW2Options(t *testing.T) {
src := QCOW2CreateOptions{Compat: "0.10", ClusterSize: 131072, ExtendedL2: boolPtr(false)}
if got := ResolveCompactQCOW2Options(src, CompactDiskOptions{}); got.OptionString() != src.OptionString() {
t.Fatalf("compact changed source options: %s", got.OptionString())
}
optimize := CompactDiskOptions{EnableExtendedL2: true}
got := ResolveCompactQCOW2Options(src, optimize)
if got.Compat != "1.1" || got.ClusterSize != src.ClusterSize || got.ExtendedL2 == nil || !*got.ExtendedL2 || *src.ExtendedL2 {
t.Fatalf("unexpected optimized options: %s", got.OptionString())
}
got = ResolveCompactQCOW2Options(QCOW2CreateOptions{}, optimize)
if got.Compat != "1.1" || got.ClusterSize != 65536 || got.ExtendedL2 == nil || !*got.ExtendedL2 {
t.Fatalf("unexpected optimized defaults: %s", got.OptionString())
}
rich := QCOW2CreateOptions{
Compat: "1.1",
ClusterSize: 131072,
LazyRefcounts: boolPtr(true),
ExtendedL2: boolPtr(true),
RefcountBits: 16,
CompressionType: "zstd",
}
got = ResolveCompactQCOW2Options(rich, optimize)
if got.OptionString() != rich.OptionString() {
t.Fatalf("optimize altered existing v3 options: got %s, want %s", got.OptionString(), rich.OptionString())
}
}
func TestDiskRewriteRefusesSnapshotsAndBackingFiles(t *testing.T) {
dir := t.TempDir()
disk := filepath.Join(dir, "disk.qcow2")
missingQemuImg := filepath.Join(dir, "missing-qemu-img")
hdr := make([]byte, 104)
copy(hdr, "QFI\xfb")
binary.BigEndian.PutUint32(hdr[4:8], 3)
binary.BigEndian.PutUint32(hdr[60:64], 2)
for _, want := range []string{"2 restore point(s); delete internal snapshots first", "CoW overlay"} {
if want == "CoW overlay" {
binary.BigEndian.PutUint32(hdr[60:64], 0)
binary.BigEndian.PutUint64(hdr[8:16], 104)
hdr = append(hdr, "base.qcow2"...)
binary.BigEndian.PutUint32(hdr[16:20], uint32(len(hdr)-104))
}
if err := os.WriteFile(disk, hdr, 0o644); err != nil {
t.Fatal(err)
}
_, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, nil, nil)
_, optimizeErr := CompactDiskWithOptions(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil)
for _, err := range []error{compactErr, optimizeErr} {
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("rewrite error = %v, want %q", err, want)
}
}
}
}
func TestParseResizeTarget(t *testing.T) {
const gib = uint64(1) << 30
cur := 128 * gib
+13
View File
@@ -308,6 +308,19 @@
"diskResizeAction": "Expand",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskCompactTitle": "Reclaim space",
"diskRewriteSnapshots": "Delete internal restore points first to preserve them when rewriting the disk.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
"diskRewriteBusy": "Another disk operation is in progress.",
"diskOptimizeTitle": "QCOW2 subcluster optimization",
"diskOptimizeDesc": "Splits default 64 KiB clusters into 2 KiB subclusters to reduce small-write overhead while compacting the disk.",
"diskOptimizeAction": "Optimize disk layout",
"diskOptimizeEnabled": "extended_l2 is enabled",
"diskOptimizeInactive": "extended_l2 is inactive",
"diskOptimizeDone": "{before} → {after}, reclaimed {reclaimed}. {status}.",
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
"defenderOpenSecurity": "Open Windows Security",
"defenderCopyCommand": "Copy exclusion command",
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
"diskCompactAction": "Reclaim now",
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
+13
View File
@@ -308,6 +308,19 @@
"diskResizeAction": "扩容",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskCompactTitle": "回收空间",
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
"diskRewriteBusy": "正在进行另一项磁盘操作。",
"diskOptimizeTitle": "QCOW2 子簇优化",
"diskOptimizeDesc": "默认 64 KiB 簇可划分为 2 KiB 子簇,减少小块写入的开销,同时整理磁盘并回收空间。",
"diskOptimizeAction": "优化磁盘结构",
"diskOptimizeEnabled": "已启用 extended_l2",
"diskOptimizeInactive": "extended_l2 未启用",
"diskOptimizeDone": "{before} → {after},已回收 {reclaimed}。{status}。",
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
"defenderOpenSecurity": "打开 Windows 安全中心",
"defenderCopyCommand": "复制排除命令",
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
"diskCompactAction": "立即回收",
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",