feat(storage): add Windows raw disk/partition in-place mode and disk cache policy

This commit is contained in:
YXC0915 committed 2026-12-05 12:04:54 +08:00
1 parent a11d08cb9b
commit 3837e72644
26 files changed
+976 -34

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "为 Windows Q35 虚拟机新增原生块设备直通模式(支持物理磁盘或分区就地挂载、`--disk-cache` 主机缓存策略配置,以及配合便携运行时新版 QEMU 的 Win32 原生 IOCP/WHPX/NVMe 性能优化)。",
"en": "Add Windows raw disk/partition in-place mounting and per-VM `--disk-cache` policy support, paired with the Win32 native IOCP AIO, WHPX doorbell/fast-MMIO, and NVMe runtime optimizations."
}
+15 -2
View File
@@ -27,7 +27,7 @@ import {
} from '../lib/format'
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
import { useVMStats } from '../lib/vmStats'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
@@ -36,6 +36,7 @@ import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
import { VMNetworkSettings } from './VMNetworkSettings'
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
import { DiskCacheRow } from './vmSettings/diskCache'
import { KeymapSection, useKeymap } from './vmSettings/keymap'
import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins'
import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing'
@@ -72,6 +73,7 @@ const FIELD_CAT: Record<Field, Cat> = {
displays: 'display',
borderless: 'display',
disk_controller: 'storage',
disk_cache: 'storage',
network: 'storage',
ssh_port: 'storage',
capture: 'input',
@@ -101,6 +103,7 @@ function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
case 'log_level':
case 'extra_args':
case 'audio_backend':
case 'disk_cache':
case 'guest_lang': return String(a ?? '').trim() === String(b ?? '').trim()
default: return a === b
}
@@ -117,6 +120,7 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
graphics: detail.graphics,
displays: detail.displays || 1,
disk_controller: detail.disk_controller,
disk_cache: (detail.disk_cache as DiskCache) || 'default',
resolution: detail.resolution,
borderless: detail.borderless,
capture: detail.capture,
@@ -172,7 +176,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const smbios = useSMBIOS(detail, running)
const keymap = useKeymap(detail.name, running, cat === 'input')
const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr)
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, running, stats, onError: setErr, onDiskChanged })
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged })
const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general')
const display = useTargetDisplay({
locale, driverID, vm: detail.name, running, host, shown: cat === 'display', onToast,
@@ -681,6 +685,15 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
/>
}
/>
<DiskCacheRow
locale={locale}
value={(form.disk_cache as DiskCache) || 'default'}
dirty={dirty('disk_cache')}
onReset={reset('disk_cache')}
resetLabel={tr('resetField')}
error={issueOf('disk_cache')}
onChange={(disk_cache) => set({ disk_cache })}
/>
<DiskMaintenanceRows locale={locale} running={running} state={disk} onCopy={onCopy} />
{host.defender_realtime_active && <DefenderExclusionRow locale={locale} dataRoot={host.data_root} onCopy={onCopy} onError={setErr} />}
</SetGroup>
+19 -10
View File
@@ -11,14 +11,20 @@ interface DiskOptions {
locale: Locale
driverID: string
vm: string
diskPath?: string
running: boolean
stats?: VMStats | null
onError: (message: string) => void
onDiskChanged?: () => void
}
function isWindowsRawDevicePath(disk?: string): boolean {
const s = (disk ?? '').trim().replace(/\//g, '\\')
return /^\\\\[.?]\\(physicaldrive|harddiskvolume|harddisk|volume\{)/i.test(s)
}
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
export function useDiskMaintenance({ locale, driverID, vm, diskPath, running, stats, onError, onDiskChanged }: DiskOptions) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
@@ -53,7 +59,10 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
}
}
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
const isRawDevice = isWindowsRawDevicePath(diskPath)
const resizeDisabled = running || isRawDevice
const resizeReason = isRawDevice ? tr('diskResizeRawDisabled') : tr('stopBeforeDiskOp')
const isQcow2 = !isRawDevice && (!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')
@@ -93,7 +102,7 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
return {
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
}
}
@@ -104,16 +113,16 @@ interface RowsProps {
onCopy?: (text: string) => void
}
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running: _running, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
return (
<>
<SetRow
title={tr('diskResizeTitle')}
desc={tr('diskResizeDesc')}
disabled={running}
reason={tr('stopBeforeDiskOp')}
disabled={resizeDisabled}
reason={resizeReason}
block={
<div className="stack-2">
<div className="hstack">
@@ -124,7 +133,7 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
type="button"
className="preset"
aria-pressed={resizeInput === v}
disabled={running || !!diskOpBusy}
disabled={resizeDisabled || !!diskOpBusy}
onClick={() => setResizeInput(v)}
>
{v}
@@ -139,14 +148,14 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
value={resizeInput}
spellCheck={false}
autoComplete="off"
disabled={running || !!diskOpBusy}
disabled={resizeDisabled || !!diskOpBusy}
onChange={(e) => setResizeInput(e.target.value)}
placeholder="+64G / 256G"
/>
<Button
variant="secondary"
busy={diskOpBusy === 'resize'}
disabled={running || !!diskOpBusy || !resizeInput.trim()}
disabled={resizeDisabled || !!diskOpBusy || !resizeInput.trim()}
onClick={handleResizeDisk}
>
{tr('diskResizeAction')}
@@ -0,0 +1,50 @@
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { DiskCache, Locale } from '../../types'
import { Segmented, SetRow } from '../../ui/settings'
interface Props {
locale: Locale
value: DiskCache
dirty: boolean
onReset: () => void
resetLabel: string
error?: string
onChange: (cache: DiskCache) => void
}
export const DiskCacheRow: React.FC<Props> = ({ locale, value, dirty, onReset, resetLabel, error, onChange }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const desc = value === 'writeback'
? tr('diskCacheDescWriteback')
: value === 'none'
? tr('diskCacheDescNone')
: value === 'unsafe'
? tr('diskCacheDescUnsafe')
: tr('diskCacheDescDefault')
return (
<SetRow
field="disk_cache"
dirty={dirty}
onReset={onReset}
resetLabel={resetLabel}
error={error}
title={tr('diskCacheTitle')}
desc={desc}
control={
<Segmented
label={tr('diskCacheTitle')}
value={value}
onChange={onChange}
options={[
{ value: 'default', label: tr('diskCacheOptionDefault') },
{ value: 'writeback', label: tr('diskCacheOptionWriteback') },
{ value: 'none', label: tr('diskCacheOptionNone') },
{ value: 'unsafe', label: tr('diskCacheOptionUnsafe') },
]}
/>
}
/>
)
}
+20
View File
@@ -120,6 +120,15 @@ export const settingsZh: Record<string, string> = {
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
"defenderOpenSecurity": "打开 Windows 安全中心",
"diskCacheDescDefault": "跟随运行时默认策略(回写缓存并正常转发刷盘请求)",
"diskCacheDescNone": "绕过宿主机页缓存直通磁盘(Direct I/O),适合裸分区直挂",
"diskCacheDescUnsafe": "警告:忽略 Guest 刷盘指令以换取最高吞吐,宿主机断电或崩溃可能导致磁盘损坏",
"diskCacheDescWriteback": "经宿主机页缓存回写,并安全转发 Guest 刷盘请求",
"diskCacheOptionDefault": "默认",
"diskCacheOptionNone": "直通",
"diskCacheOptionUnsafe": "激进 (Unsafe)",
"diskCacheOptionWriteback": "回写",
"diskCacheTitle": "磁盘 I/O 缓存策略",
"diskCompactAction": "立即回收",
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
@@ -144,6 +153,7 @@ export const settingsZh: Record<string, string> = {
"diskResizeAction": "扩容",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeRawDisabled": "Windows 裸分区不支持在此调整容量",
"diskResizeTitle": "扩大磁盘",
"diskRewriteBusy": "正在进行另一项磁盘操作。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
@@ -656,6 +666,15 @@ export const settingsEn: Record<string, string> = {
"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",
"diskCacheDescDefault": "Follows the current runtime default (writeback caching, flushes forwarded to host)",
"diskCacheDescNone": "Direct I/O bypassing host page cache; recommended for raw partition passthrough",
"diskCacheDescUnsafe": "Warning: ignores guest flushes for peak throughput; host power loss or crash can corrupt the disk",
"diskCacheDescWriteback": "Uses host page cache and forwards guest flushes safely to disk",
"diskCacheOptionDefault": "Default",
"diskCacheOptionNone": "Direct",
"diskCacheOptionUnsafe": "Unsafe",
"diskCacheOptionWriteback": "Writeback",
"diskCacheTitle": "Disk I/O cache",
"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})",
@@ -680,6 +699,7 @@ export const settingsEn: Record<string, string> = {
"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:",
"diskResizeRawDisabled": "Windows raw partitions cannot be resized here",
"diskResizeTitle": "Expand disk",
"diskRewriteBusy": "Another disk operation is in progress.",
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
+10
View File
@@ -179,6 +179,15 @@ export type I18nKey =
| "discardSuspendConfirm"
| "discardSuspendDesc"
| "discardSuspendTitle"
| "diskCacheDescDefault"
| "diskCacheDescNone"
| "diskCacheDescUnsafe"
| "diskCacheDescWriteback"
| "diskCacheOptionDefault"
| "diskCacheOptionNone"
| "diskCacheOptionUnsafe"
| "diskCacheOptionWriteback"
| "diskCacheTitle"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
@@ -203,6 +212,7 @@ export type I18nKey =
| "diskResizeAction"
| "diskResizeDesc"
| "diskResizeDone"
| "diskResizeRawDisabled"
| "diskResizeTitle"
| "diskRewriteBusy"
| "diskRewriteOverlay"
+2
View File
@@ -106,6 +106,7 @@ export type DiskResizeResult = driver.DiskResizeResult
export type DiskCompactResult = driver.DiskCompactResult
export type DiskSnapshot = driver.DiskSnapshot
export type StorageBreakdown = Model<app.StorageBreakdown>
export type DiskCache = 'default' | 'writeback' | 'none' | 'unsafe'
export type SetOpts = reims.SetOpts
export type CreateOpts = Model<reims.CreateOpts> & {
@@ -114,6 +115,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
disk_mode?: 'copy' | 'in-place'
disk_controller?: 'nvme' | 'ahci' | 'virtio'
disk_cache?: DiskCache
graphics: 'reims-vgpu' | 'vmware-svga'
cpus: number
memory: string
+6
View File
@@ -3017,6 +3017,7 @@ export namespace reims {
disk?: string;
disk_mode?: string;
disk_controller?: string;
disk_cache?: string;
graphics?: string;
gpu?: string;
resolution?: string;
@@ -3050,6 +3051,7 @@ export namespace reims {
this.disk = source["disk"];
this.disk_mode = source["disk_mode"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.graphics = source["graphics"];
this.gpu = source["gpu"];
this.resolution = source["resolution"];
@@ -3073,6 +3075,7 @@ export namespace reims {
graphics?: string;
displays?: number;
disk_controller?: string;
disk_cache?: string;
resolution?: string;
borderless?: boolean;
capture?: boolean;
@@ -3101,6 +3104,7 @@ export namespace reims {
this.graphics = source["graphics"];
this.displays = source["displays"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.resolution = source["resolution"];
this.borderless = source["borderless"];
this.capture = source["capture"];
@@ -3175,6 +3179,7 @@ export namespace reims {
memory: string;
disk: string;
disk_controller: string;
disk_cache: string;
graphics: string;
display: string;
displays: number;
@@ -3227,6 +3232,7 @@ export namespace reims {
this.memory = source["memory"];
this.disk = source["disk"];
this.disk_controller = source["disk_controller"];
this.disk_cache = source["disk_cache"];
this.graphics = source["graphics"];
this.display = source["display"];
this.displays = source["displays"];
+10
View File
@@ -189,6 +189,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
if opts.Displays > 0 && opts.Displays != cur.Displays {
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
}
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
}
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
from := cur.DiskCache
if from == "" {
from = "default"
}
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
}
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
}
+44 -2
View File
@@ -100,6 +100,8 @@ func run(args []string) (i18n.Locale, error) {
return loc, cmdInstaller(cfg, loc, rest[1:])
case "plugin":
return loc, cmdPlugin(cfg, loc, rest[1:])
case "host":
return loc, cmdHost(cfg, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return loc, nil
@@ -501,6 +503,9 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
cpus := fs.Int("cpus", 8, "vCPU count")
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
disk := fs.String("disk", "", "Existing disk image or Windows raw partition path")
diskMode := fs.String("disk-mode", "", "Existing disk attach mode (copy, in-place)")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
@@ -534,6 +539,9 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
"disk_size": *diskSize,
},
}
if *diskCache != "" {
req.Options["disk_cache"] = *diskCache
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
@@ -547,7 +555,7 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s
}
return nil
}
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, Disk: *disk, DiskMode: *diskMode, DiskCache: *diskCache, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
}
func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
@@ -555,6 +563,7 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
cpus := fs.Int("cpus", 0, "vCPU count")
mem := fs.String("memory", "", "RAM size")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
@@ -573,6 +582,9 @@ func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
if *mem != "" {
changes["memory"] = *mem
}
if *diskCache != "" {
changes["disk_cache"] = *diskCache
}
if *gpu != "" {
changes["gpu"] = *gpu
}
@@ -601,9 +613,39 @@ func printJSON(v any) error {
// readOnlySafeCommand reports whether cmd runs without writing to the data
// folder, so it may run while the folder is open read-only.
func cmdHost(cfg *config.Config, args []string) error {
if len(args) == 0 || args[0] != "raw-disks" {
return fmt.Errorf("usage: reims-go host raw-disks [--json]")
}
fs := flag.NewFlagSet("host raw-disks", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
list, err := host.ListRawPartitions(cfg.DataRoot)
if err != nil {
return err
}
if *asJSON {
return printJSON(list)
}
if len(list) == 0 {
fmt.Println("No eligible unmounted raw partitions or offline disks found.")
return nil
}
for _, c := range list {
apfs := ""
if c.IsAPFS {
apfs = " [APFS]"
}
fmt.Printf("%-46s %7.1f GiB disk=%d part=%d%s\n", c.DevicePath, float64(c.SizeBytes)/float64(1<<30), c.DiskNumber, c.PartitionNumber, apfs)
}
return nil
}
func readOnlySafeCommand(cmd string) bool {
switch cmd {
case "version", "-v", "--version", "help", "-h", "--help", "doctor":
case "version", "-v", "--version", "help", "-h", "--help", "doctor", "host":
return true
}
return false
+4 -4
View File
@@ -65,9 +65,9 @@ func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
type macOSCreateOptions struct {
Name, Dir, MacOS, Memory, DiskSize, GPU, GuestLang string
CPUs int
Capture, Logs bool
Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string
CPUs int
Capture, Logs bool
}
func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in macOSCreateOptions, startAfterCreate, viaWindow bool) error {
@@ -79,7 +79,7 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in
return err
}
client := prep.Client
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, Disk: in.Disk, DiskMode: in.DiskMode, DiskCache: in.DiskCache, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
existingVMs, err := client.List(ctx)
if err != nil {
return fmt.Errorf("check existing VMs before create: %w", err)
+135
View File
@@ -0,0 +1,135 @@
package host
import (
"fmt"
"slices"
"strings"
)
// AppleAPFSPartitionTypeGUID is the canonical GPT partition type GUID for Apple APFS containers.
const AppleAPFSPartitionTypeGUID = "7C3457EF-0000-11AA-AA11-00306543ECAC"
var protectedGPTPartitionTypeGUIDs = map[string]bool{
"C12A7328-F81F-11D2-BA4B-00A0C93EC93B": true, // EFI System Partition
"E3C9E316-0B5C-4DB8-817D-F92DF00215AE": true, // Microsoft Reserved (MSR)
"DE94BBA4-06D1-4D40-A16A-BFD50179D6AC": true, // Windows Recovery Environment
}
// RawDiskCandidate describes a Windows raw volume or offline whole disk
// eligible as an unmounted guest block device.
type RawDiskCandidate struct {
DevicePath string `json:"device_path"`
DiskNumber uint32 `json:"disk_number"`
PartitionNumber uint32 `json:"partition_number,omitempty"`
SizeBytes uint64 `json:"size_bytes"`
PartitionTypeGUID string `json:"partition_type_guid,omitempty"`
IsAPFS bool `json:"is_apfs"`
Offline bool `json:"offline"`
ReadOnly bool `json:"read_only"`
Label string `json:"label,omitempty"`
}
// IsWindowsRawDevicePath reports whether path names a Windows raw disk,
// partition, or volume device path (excluding regular Win32 paths such as \\?\C:\...).
func IsWindowsRawDevicePath(path string) bool {
p := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(path), "/", `\`))
if strings.HasPrefix(p, `\\.\`) {
rest := p[len(`\\.\`):]
return strings.HasPrefix(rest, "physicaldrive") ||
strings.HasPrefix(rest, "harddiskvolume") ||
strings.HasPrefix(rest, "harddisk") ||
strings.HasPrefix(rest, "volume{")
}
if strings.HasPrefix(p, `\\?\`) {
rest := p[len(`\\?\`):]
return strings.HasPrefix(rest, "volume{")
}
return false
}
// RawVolumeObservation captures raw probe fields for a Windows volume or offline disk
// before applying host-safety filters.
type RawVolumeObservation struct {
DevicePath string
DiskNumber uint32
PartitionNumber uint32
SizeBytes uint64
PartitionTypeGUID string
HasMountPoints bool
Filesystem string
Offline bool
ReadOnly bool
Label string
}
func isMountedWindowsFilesystem(fsName string) bool {
switch strings.ToUpper(strings.TrimSpace(fsName)) {
case "NTFS", "FAT", "FAT32", "EXFAT", "REFS", "CDFS", "UDF":
return true
default:
return false
}
}
func filterRawPartitionCandidates(observations []RawVolumeObservation, excludedDisks map[uint32]bool) []RawDiskCandidate {
var out []RawDiskCandidate
for _, obs := range observations {
if obs.DevicePath == "" || obs.SizeBytes == 0 {
continue
}
if excludedDisks[obs.DiskNumber] {
continue
}
if obs.HasMountPoints || isMountedWindowsFilesystem(obs.Filesystem) {
continue
}
guid := strings.ToUpper(strings.TrimSpace(obs.PartitionTypeGUID))
if guid != "" && protectedGPTPartitionTypeGUIDs[guid] {
continue
}
isAPFS := guid == AppleAPFSPartitionTypeGUID
label := strings.TrimSpace(obs.Label)
if label == "" {
if obs.PartitionNumber == 0 {
label = fmt.Sprintf("Disk %d (Offline)", obs.DiskNumber)
} else if isAPFS {
label = fmt.Sprintf("Disk %d Partition %d (APFS)", obs.DiskNumber, obs.PartitionNumber)
} else {
label = fmt.Sprintf("Disk %d Partition %d", obs.DiskNumber, obs.PartitionNumber)
}
}
out = append(out, RawDiskCandidate{
DevicePath: obs.DevicePath,
DiskNumber: obs.DiskNumber,
PartitionNumber: obs.PartitionNumber,
SizeBytes: obs.SizeBytes,
PartitionTypeGUID: guid,
IsAPFS: isAPFS,
Offline: obs.Offline,
ReadOnly: obs.ReadOnly,
Label: label,
})
}
slices.SortFunc(out, func(a, b RawDiskCandidate) int {
if a.IsAPFS != b.IsAPFS {
if a.IsAPFS {
return -1
}
return 1
}
if a.DiskNumber != b.DiskNumber {
if a.DiskNumber < b.DiskNumber {
return -1
}
return 1
}
if a.PartitionNumber < b.PartitionNumber {
return -1
}
if a.PartitionNumber > b.PartitionNumber {
return 1
}
return strings.Compare(a.DevicePath, b.DevicePath)
})
return out
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package host
// ListRawPartitions returns eligible unmounted partitions or offline whole disks.
// Currently only Windows raw device passthrough is implemented.
func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) {
return nil, nil
}
+52
View File
@@ -0,0 +1,52 @@
package host
import "testing"
func TestIsWindowsRawDevicePath(t *testing.T) {
cases := []struct {
path string
want bool
}{
{`\\?\Volume{11111111-2222-3333-4444-555555555555}`, true},
{`//?/volume{11111111-2222-3333-4444-555555555555}`, true},
{`\\.\PhysicalDrive1`, true},
{`\\.\HarddiskVolume3`, true},
{`\\.\Harddisk1Partition2`, true},
{`\\.\Volume{11111111-2222-3333-4444-555555555555}`, true},
{`\\?\C:\VMs\macOS\disk.qcow2`, false},
{`\\?\UNC\server\share\disk.qcow2`, false},
{`D:\ReimsData\disk.qcow2`, false},
{``, false},
}
for _, tc := range cases {
if got := IsWindowsRawDevicePath(tc.path); got != tc.want {
t.Errorf("IsWindowsRawDevicePath(%q) = %v, want %v", tc.path, got, tc.want)
}
}
}
func TestFilterRawPartitionCandidatesSafety(t *testing.T) {
obs := []RawVolumeObservation{
{DevicePath: `\\?\Volume{os-c}`, DiskNumber: 0, PartitionNumber: 3, SizeBytes: 200 << 30, HasMountPoints: true, Filesystem: "NTFS"},
{DevicePath: `\\?\Volume{os-efi}`, DiskNumber: 0, PartitionNumber: 1, SizeBytes: 260 << 20, PartitionTypeGUID: "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"},
{DevicePath: `\\?\Volume{data-apfs}`, DiskNumber: 1, PartitionNumber: 2, SizeBytes: 256 << 30, PartitionTypeGUID: "7c3457ef-0000-11aa-aa11-00306543ecac"},
{DevicePath: `\\?\Volume{mounted-ntfs}`, DiskNumber: 2, PartitionNumber: 2, SizeBytes: 500 << 30, Filesystem: "NTFS"},
{DevicePath: `\\?\Volume{efi-disk2}`, DiskNumber: 2, PartitionNumber: 1, SizeBytes: 200 << 20, PartitionTypeGUID: "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"},
{DevicePath: `\\?\Volume{other-raw}`, DiskNumber: 2, PartitionNumber: 3, SizeBytes: 128 << 30, PartitionTypeGUID: "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"},
{DevicePath: `\\.\PhysicalDrive3`, DiskNumber: 3, SizeBytes: 512 << 30, Offline: true},
}
excluded := map[uint32]bool{0: true}
got := filterRawPartitionCandidates(obs, excluded)
if len(got) != 3 {
t.Fatalf("got %d candidates %+v, want 3", len(got), got)
}
if !got[0].IsAPFS || got[0].DevicePath != `\\?\Volume{data-apfs}` {
t.Fatalf("expected APFS partition sorted first, got %+v", got[0])
}
if got[1].DevicePath != `\\?\Volume{other-raw}` {
t.Fatalf("unexpected second candidate: %+v", got[1])
}
if !got[2].Offline || got[2].DevicePath != `\\.\PhysicalDrive3` {
t.Fatalf("unexpected third candidate: %+v", got[2])
}
}
+364
View File
@@ -0,0 +1,364 @@
//go:build windows
package host
import (
"encoding/binary"
"fmt"
"os"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
var (
procFindFirstVolumeW = kernel32.NewProc("FindFirstVolumeW")
procFindNextVolumeW = kernel32.NewProc("FindNextVolumeW")
procFindVolumeClose = kernel32.NewProc("FindVolumeClose")
procGetVolumeInformationW = kernel32.NewProc("GetVolumeInformationW")
procGetVolumePathNameW = kernel32.NewProc("GetVolumePathNameW")
)
const (
ioctlVolumeGetVolumeDiskExtents = 0x00560000
ioctlDiskGetDriveLayoutEx = 0x00070050
ioctlDiskGetLengthInfo = 0x0007405C
ioctlDiskGetDiskAttributes = 0x000700F0
diskAttributeOffline = 0x1
diskAttributeReadOnly = 0x2
)
// ListRawPartitions enumerates Windows raw partitions and offline disks that
// are safe to pass through to a VM (excluding OS disk, dataRoot disk, EFI/MSR/Recovery,
// mounted volumes, and Windows filesystems).
func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) {
excluded := excludedHostDiskNumbers(dataRoot)
volByExtent := indexVolumesByExtent()
var observations []RawVolumeObservation
for diskNum := uint32(0); diskNum < 32; diskNum++ {
if excluded[diskNum] {
continue
}
dev := fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum)
offline, readOnly, ok := queryDiskAttributes(diskNum)
if !ok {
continue
}
if offline {
sizeBytes, _ := queryDeviceLengthBytes(dev)
if sizeBytes > 0 {
observations = append(observations, RawVolumeObservation{
DevicePath: dev,
DiskNumber: diskNum,
SizeBytes: sizeBytes,
Offline: true,
ReadOnly: readOnly,
})
}
continue
}
parts := queryDiskPartitions(diskNum)
for _, p := range parts {
if p.number == 0 || p.length == 0 {
continue
}
obs := RawVolumeObservation{
DevicePath: fmt.Sprintf(`\\.\Harddisk%dPartition%d`, diskNum, p.number),
DiskNumber: diskNum,
PartitionNumber: p.number,
SizeBytes: p.length,
PartitionTypeGUID: p.typeGUID,
ReadOnly: readOnly,
}
if v, mapped := volByExtent[extentKey{disk: diskNum, offset: p.offset}]; mapped {
obs.DevicePath = v.volDev
obs.HasMountPoints = v.hasMountPoints
obs.Filesystem = v.filesystem
}
if exact, ok := queryDeviceLengthBytes(obs.DevicePath); ok && exact > 0 {
obs.SizeBytes = exact
}
observations = append(observations, obs)
}
}
return filterRawPartitionCandidates(observations, excluded), nil
}
type volumeDiskExtent struct {
diskNumber uint32
startingOffset int64
extentLength uint64
}
type extentKey struct {
disk uint32
offset int64
}
type indexedVolume struct {
volDev string
hasMountPoints bool
filesystem string
}
type diskPartitionEntry struct {
number uint32
offset int64
length uint64
typeGUID string
}
func indexVolumesByExtent() map[extentKey]indexedVolume {
out := map[extentKey]indexedVolume{}
volNames, err := enumVolumeNames()
if err != nil {
return out
}
for _, volWithSlash := range volNames {
volDev := strings.TrimSuffix(volWithSlash, `\`)
extents, ok := queryVolumeDiskExtents(volDev)
if !ok || len(extents) != 1 {
continue
}
ext := extents[0]
out[extentKey{disk: ext.diskNumber, offset: ext.startingOffset}] = indexedVolume{
volDev: volDev,
hasMountPoints: volumeHasMountPoints(volWithSlash),
filesystem: queryVolumeFilesystem(volWithSlash),
}
}
return out
}
func excludedHostDiskNumbers(dataRoot string) map[uint32]bool {
excluded := map[uint32]bool{}
addPath := func(p string) {
p = strings.TrimSpace(p)
if p == "" {
return
}
volDev := volumeDeviceForPath(p)
if volDev == "" {
return
}
if extents, ok := queryVolumeDiskExtents(volDev); ok {
for _, ext := range extents {
excluded[ext.diskNumber] = true
}
}
}
if sysRoot := os.Getenv("SystemRoot"); sysRoot != "" {
addPath(sysRoot)
} else if sysDrive := os.Getenv("SystemDrive"); sysDrive != "" {
addPath(sysDrive + `\`)
}
addPath(dataRoot)
return excluded
}
func volumeDeviceForPath(path string) string {
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return ""
}
mount := make([]uint16, 32768)
r, _, _ := procGetVolumePathNameW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&mount[0])), uintptr(len(mount)))
if r == 0 {
return ""
}
var vol [64]uint16
r2, _, _ := procGetVolumeNameForVolumeMountPointW.Call(uintptr(unsafe.Pointer(&mount[0])), uintptr(unsafe.Pointer(&vol[0])), uintptr(len(vol)))
if r2 == 0 {
return ""
}
return strings.TrimSuffix(syscall.UTF16ToString(vol[:]), `\`)
}
func enumVolumeNames() ([]string, error) {
buf := make([]uint16, 32768)
h, _, err := procFindFirstVolumeW.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if h == uintptr(windows.InvalidHandle) {
return nil, err
}
defer procFindVolumeClose.Call(h)
var out []string
for {
name := syscall.UTF16ToString(buf)
if name != "" {
out = append(out, name)
}
r, _, _ := procFindNextVolumeW.Call(h, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if r == 0 {
break
}
}
return out, nil
}
func volumeHasMountPoints(volWithSlash string) bool {
p, err := windows.UTF16PtrFromString(volWithSlash)
if err != nil {
return false
}
buf := make([]uint16, 1024)
var needed uint32
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
if needed > uint32(len(buf)) {
buf = make([]uint16, needed)
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
return false
}
} else {
return false
}
}
return len(buf) > 0 && buf[0] != 0
}
func queryVolumeFilesystem(volWithSlash string) string {
p, err := syscall.UTF16PtrFromString(volWithSlash)
if err != nil {
return ""
}
fsBuf := make([]uint16, 64)
r, _, _ := procGetVolumeInformationW.Call(
uintptr(unsafe.Pointer(p)),
0, 0,
0, 0, 0,
uintptr(unsafe.Pointer(&fsBuf[0])), uintptr(len(fsBuf)),
)
if r == 0 {
return ""
}
return syscall.UTF16ToString(fsBuf)
}
func openDeviceMeta(devicePath string, access uint32) (windows.Handle, error) {
p, err := windows.UTF16PtrFromString(devicePath)
if err != nil {
return 0, err
}
return windows.CreateFile(
p,
access,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,
nil,
windows.OPEN_EXISTING,
0,
0,
)
}
func queryVolumeDiskExtents(volDev string) ([]volumeDiskExtent, bool) {
h, err := openDeviceMeta(volDev, 0)
if err != nil {
return nil, false
}
defer windows.CloseHandle(h)
buf := make([]byte, 256)
var n uint32
if err := windows.DeviceIoControl(h, ioctlVolumeGetVolumeDiskExtents, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil {
return nil, false
}
if n < 32 {
return nil, false
}
count := binary.LittleEndian.Uint32(buf[0:4])
var out []volumeDiskExtent
for i := uint32(0); i < count; i++ {
off := 8 + int(i)*24
if off+24 > int(n) {
break
}
out = append(out, volumeDiskExtent{
diskNumber: binary.LittleEndian.Uint32(buf[off : off+4]),
startingOffset: int64(binary.LittleEndian.Uint64(buf[off+8 : off+16])),
extentLength: binary.LittleEndian.Uint64(buf[off+16 : off+24]),
})
}
return out, len(out) > 0
}
func queryDeviceLengthBytes(devPath string) (uint64, bool) {
h, err := openDeviceMeta(devPath, windows.GENERIC_READ)
if err != nil {
return 0, false
}
defer windows.CloseHandle(h)
var out [8]byte
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetLengthInfo, nil, 0, &out[0], 8, &n, nil); err != nil || n < 8 {
return 0, false
}
return binary.LittleEndian.Uint64(out[:]), true
}
func queryDiskAttributes(diskNum uint32) (offline, readOnly, ok bool) {
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), 0)
if err != nil {
return false, false, false
}
defer windows.CloseHandle(h)
var out [16]byte
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetDiskAttributes, nil, 0, &out[0], uint32(len(out)), &n, nil); err != nil || n < 16 {
return false, false, false
}
attrs := binary.LittleEndian.Uint64(out[8:16])
return (attrs & diskAttributeOffline) != 0, (attrs & diskAttributeReadOnly) != 0, true
}
func queryDiskPartitions(diskNum uint32) []diskPartitionEntry {
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), windows.GENERIC_READ)
if err != nil {
return nil
}
defer windows.CloseHandle(h)
// Accommodate up to 128 GPT partitions: 48 + 128*144 = 18480 bytes.
buf := make([]byte, 48+128*144)
var n uint32
if err := windows.DeviceIoControl(h, ioctlDiskGetDriveLayoutEx, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil || n < 48 {
return nil
}
style := binary.LittleEndian.Uint32(buf[0:4])
count := binary.LittleEndian.Uint32(buf[4:8])
var out []diskPartitionEntry
for i := uint32(0); i < count; i++ {
off := 48 + int(i)*144
if off+144 > int(n) {
break
}
entryStyle := binary.LittleEndian.Uint32(buf[off : off+4])
startOff := int64(binary.LittleEndian.Uint64(buf[off+8 : off+16]))
length := binary.LittleEndian.Uint64(buf[off+16 : off+24])
num := binary.LittleEndian.Uint32(buf[off+24 : off+28])
guid := ""
if style == 1 && entryStyle == 1 {
guid = formatWinGUID(buf[off+32 : off+48])
}
out = append(out, diskPartitionEntry{
number: num,
offset: startOff,
length: length,
typeGUID: guid,
})
}
return out
}
func formatWinGUID(b []byte) string {
if len(b) < 16 {
return ""
}
d1 := binary.LittleEndian.Uint32(b[0:4])
d2 := binary.LittleEndian.Uint16(b[4:6])
d3 := binary.LittleEndian.Uint16(b[6:8])
return fmt.Sprintf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
}
+4
View File
@@ -673,6 +673,7 @@ var catalog = map[Locale]map[string]string{
"validate.installer_not_found": "所选安装镜像文件不存在",
"validate.invalid_audio_backend": "不支持的音频后端 \"{backend}\"",
"validate.invalid_cpus": "虚拟处理器核数须在 1 到 {max} 之间",
"validate.invalid_disk_cache": "磁盘缓存策略仅支持 default、writeback、none 或 unsafe",
"validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio",
"validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)",
"validate.invalid_displays": "显示器数量须在 1 到 4 之间",
@@ -687,6 +688,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "虚拟机名称不能为空",
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.name_taken": "已存在名为 {name} 的虚拟机",
"validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)",
"validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置",
"viewLogs": "查看日志",
"vm.already_running": "{name} 已在运行中",
@@ -1376,6 +1378,7 @@ var catalog = map[Locale]map[string]string{
"validate.installer_not_found": "Selected installer image file does not exist",
"validate.invalid_audio_backend": "Unsupported audio backend \"{backend}\"",
"validate.invalid_cpus": "vCPUs must be between 1 and {max}",
"validate.invalid_disk_cache": "Disk cache mode must be default, writeback, none, or unsafe",
"validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio",
"validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)",
"validate.invalid_displays": "Displays must be between 1 and 4",
@@ -1390,6 +1393,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "VM name is required",
"validate.missing_release": "Choose the macOS release to install offline",
"validate.name_taken": "A VM named {name} already exists",
"validate.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place",
"validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings",
"viewLogs": "View logs",
"vm.already_running": "{name} is already running",
+3
View File
@@ -117,6 +117,9 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
if srcDisk == "" {
return fmt.Errorf("VM %s has no disk path", sourceName)
}
if reims.IsWindowsRawDevicePath(srcDisk) {
return fmt.Errorf("cannot derive a CoW clone from a raw disk partition")
}
if _, err := os.Stat(srcDisk); err != nil {
return fmt.Errorf("source disk %s: %w", srcDisk, err)
}
+8 -2
View File
@@ -28,7 +28,7 @@ func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]dr
return nil, err
}
diskPath := det.DiskPath()
if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
if diskPath == "" || reims.IsWindowsRawDevicePath(diskPath) || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return nil, nil
}
cfg := d.getConfig()
@@ -72,7 +72,7 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna
if diskPath == "" {
return fmt.Errorf("VM %s has no disk path", name)
}
if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
if reims.IsWindowsRawDevicePath(diskPath) || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") {
return fmt.Errorf("restore points require a qcow2 disk")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
@@ -104,6 +104,9 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string,
if diskPath == "" {
return driver.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
}
if reims.IsWindowsRawDevicePath(diskPath) {
return driver.DiskResizeResult{}, fmt.Errorf("raw disk partitions cannot be resized here")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
if err != nil {
return driver.DiskResizeResult{}, err
@@ -145,6 +148,9 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri
if diskPath == "" {
return driver.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
}
if reims.IsWindowsRawDevicePath(diskPath) {
return driver.DiskCompactResult{}, fmt.Errorf("raw disk partitions cannot be compacted")
}
releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath)
if err != nil {
return driver.DiskCompactResult{}, err
+28 -13
View File
@@ -70,16 +70,20 @@ func (c *Client) LockCoWDisks(ctx context.Context, paths ...string) (func(), err
if path == "" {
continue
}
path = absoluteDiskPath(path)
if !IsWindowsRawDevicePath(path) {
path = absoluteDiskPath(path)
}
keys = append(keys, fmt.Sprintf("path-%x", sha256.Sum256([]byte(diskPathKey(path)))))
if info, err := os.Stat(path); err == nil {
volume, id, err := mediaFileID(path, info)
if err != nil {
if !IsWindowsRawDevicePath(path) {
if info, err := os.Stat(path); err == nil {
volume, id, err := mediaFileID(path, info)
if err != nil {
return nil, err
}
keys = append(keys, fmt.Sprintf("file-%x-%x", volume, id))
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
keys = append(keys, fmt.Sprintf("file-%x-%x", volume, id))
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
@@ -224,13 +228,18 @@ func (c *Client) RegisterCoWClone(ctx context.Context, o CreateOpts, stdout, std
}
func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string, stdout, stderr io.Writer) error {
disk := absoluteDiskPath(config.ExpandHomePath(o.Disk))
disk := config.ExpandHomePath(o.Disk)
if !IsWindowsRawDevicePath(disk) {
disk = absoluteDiskPath(disk)
}
paths := []string{disk}
if err := visitDiskBackings(disk, func(parent string) bool {
paths = append(paths, parent)
return false
}); err != nil {
return err
if !IsWindowsRawDevicePath(disk) {
if err := visitDiskBackings(disk, func(parent string) bool {
paths = append(paths, parent)
return false
}); err != nil {
return err
}
}
release, err := c.LockCoWDisks(ctx, paths...)
if err != nil {
@@ -633,6 +642,9 @@ func newDiskMatch(path string) diskMatch {
if path == "" {
return diskMatch{}
}
if IsWindowsRawDevicePath(path) {
return diskMatch{path: path}
}
path = absoluteDiskPath(path)
info, _ := os.Stat(path)
return diskMatch{path: path, info: info}
@@ -655,6 +667,9 @@ func (d diskMatch) matches(path string) bool {
}
func absoluteDiskPath(path string) string {
if IsWindowsRawDevicePath(path) {
return strings.ReplaceAll(strings.TrimSpace(path), "/", `\`)
}
if abs, err := filepath.Abs(path); err == nil {
path = abs
}
+9
View File
@@ -236,6 +236,9 @@ func BuildCompactDiskArgs(srcPath, dstPath string, opts QCOW2CreateOptions) []st
// 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 {
if IsWindowsRawDevicePath(srcPath) {
return false
}
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath)))
return ext == ".vmdk" || ext == ".raw"
}
@@ -315,6 +318,9 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac
// 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 IsWindowsRawDevicePath(diskPath) {
return DiskResizeResult{}, fmt.Errorf("raw disk partitions cannot be resized here")
}
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
@@ -351,6 +357,9 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath,
}
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) {
if IsWindowsRawDevicePath(diskPath) {
return DiskCompactResult{}, fmt.Errorf("raw disk partitions cannot be compacted")
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
+108
View File
@@ -0,0 +1,108 @@
package reims
import (
"context"
"slices"
"testing"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestRawDevicePathAndDiskPath(t *testing.T) {
vol := `\\?\Volume{11111111-2222-3333-4444-555555555555}`
d := VMDetail{Directory: `/tmp/vm`, Disk: vol + ` (128G)`}
if got := d.DiskPath(); got != vol {
t.Fatalf("DiskPath() = %q, want %q", got, vol)
}
if !IsWindowsRawDevicePath(vol) {
t.Fatalf("expected IsWindowsRawDevicePath(%q) = true", vol)
}
if IsWindowsRawDevicePath(`\\?\C:\Users\test\disk.qcow2`) {
t.Fatalf("expected regular extended Win32 path not to match raw device")
}
if NeedsDiskConversion(vol) {
t.Fatalf("expected NeedsDiskConversion(%q) = false", vol)
}
}
func TestDiskCacheValidationAndArgs(t *testing.T) {
vol := `\\?\Volume{11111111-2222-3333-4444-555555555555}`
rep := host.Report{LogicalCPUs: 16}
issues := ValidateCreate(CreateOpts{
Name: "apfs-vm",
CPUs: 8,
Memory: "8G",
Disk: vol,
DiskCache: "unsafe",
}, rep, i18n.EnUS)
if len(issues) != 0 {
t.Fatalf("expected no validation issues for valid raw partition + unsafe cache, got %+v", issues)
}
copyIssues := ValidateCreate(CreateOpts{
Name: "apfs-vm",
CPUs: 8,
Memory: "8G",
Disk: vol,
DiskMode: "copy",
}, rep, i18n.EnUS)
if !slices.ContainsFunc(copyIssues, func(is ValidationIssue) bool { return is.Code == "raw_disk_in_place_only" }) {
t.Fatalf("expected raw_disk_in_place_only issue, got %+v", copyIssues)
}
badCache := ValidateSet(SetOpts{Name: "apfs-vm", DiskCache: "invalid"}, VMDetail{Name: "apfs-vm"}, rep, i18n.EnUS)
if !slices.ContainsFunc(badCache, func(is ValidationIssue) bool { return is.Code == "invalid_disk_cache" }) {
t.Fatalf("expected invalid_disk_cache issue, got %+v", badCache)
}
createArgs, err := BuildCreateArgs(CreateOpts{
Name: "apfs-vm",
Disk: vol,
DiskCache: "none",
})
if err != nil {
t.Fatalf("BuildCreateArgs: %v", err)
}
wantCreate := []string{"create", "apfs-vm", "--disk", vol, "--disk-mode", "in-place", "--disk-cache", "none"}
if !slices.Equal(createArgs, wantCreate) {
t.Fatalf("BuildCreateArgs = %v, want %v", createArgs, wantCreate)
}
setArgs, err := BuildSetArgs(SetOpts{Name: "apfs-vm", DiskCache: "unsafe"})
if err != nil {
t.Fatalf("BuildSetArgs: %v", err)
}
wantSet := []string{"set", "apfs-vm", "--disk-cache", "unsafe"}
if !slices.Equal(setArgs, wantSet) {
t.Fatalf("BuildSetArgs = %v, want %v", setArgs, wantSet)
}
}
func TestParseShowDiskCache(t *testing.T) {
show := `apfs-vm
state stopped
disk \\?\Volume{11111111-2222-3333-4444-555555555555} (nvme)
disk cache unsafe
`
d := ParseShow("apfs-vm", show)
if d.DiskController != "nvme" {
t.Fatalf("DiskController = %q, want nvme", d.DiskController)
}
if d.DiskCache != "unsafe" {
t.Fatalf("DiskCache = %q, want unsafe", d.DiskCache)
}
if dDef := ParseShow("plain", "plain\n state stopped\n"); dDef.DiskCache != "default" {
t.Fatalf("default DiskCache = %q, want default", dDef.DiskCache)
}
}
func TestLockCoWDisksAllowsRawDevicePath(t *testing.T) {
c := &Client{imagesDir: t.TempDir(), Locale: i18n.EnUS}
release, err := c.LockCoWDisks(context.Background(), `\\?\Volume{11111111-2222-3333-4444-555555555555}`)
if err != nil {
t.Fatalf("LockCoWDisks on raw device: %v", err)
}
release()
}
+45 -1
View File
@@ -61,12 +61,21 @@ func NewClient(cfg *config.Config, installed rt.Installed) *Client {
return c
}
// IsWindowsRawDevicePath reports whether path targets a Windows raw disk,
// partition, or volume device path.
func IsWindowsRawDevicePath(path string) bool {
return host.IsWindowsRawDevicePath(path)
}
// DiskPath resolves the system disk path returned by reims-ctl show.
func (d VMDetail) DiskPath() string {
raw := strings.TrimSpace(d.Disk)
if idx := strings.LastIndex(raw, " ("); idx > 0 && strings.HasSuffix(raw, ")") {
raw = strings.TrimSpace(raw[:idx])
}
if IsWindowsRawDevicePath(raw) {
return raw
}
raw = config.ExpandHomePath(raw)
if filepath.IsAbs(raw) {
return raw
@@ -91,6 +100,7 @@ type VMDetail struct {
Memory string `json:"memory"`
Disk string `json:"disk"`
DiskController string `json:"disk_controller"`
DiskCache string `json:"disk_cache"`
Graphics string `json:"graphics"`
Display string `json:"display"`
Displays int `json:"displays"`
@@ -156,6 +166,7 @@ type CreateOpts struct {
Disk string `json:"disk,omitempty"`
DiskMode string `json:"disk_mode,omitempty"`
DiskController string `json:"disk_controller,omitempty"`
DiskCache string `json:"disk_cache,omitempty"`
Graphics string `json:"graphics,omitempty"`
GPU string `json:"gpu,omitempty"`
Resolution string `json:"resolution,omitempty"`
@@ -179,6 +190,7 @@ type SetOpts struct {
Graphics string `json:"graphics,omitempty"`
Displays int `json:"displays,omitempty"`
DiskController string `json:"disk_controller,omitempty"`
DiskCache string `json:"disk_cache,omitempty"`
Resolution string `json:"resolution,omitempty"`
Borderless *bool `json:"borderless,omitempty"`
Capture *bool `json:"capture,omitempty"`
@@ -259,13 +271,20 @@ func ValidateCreate(o CreateOpts, rep host.Report, loc i18n.Locale) []Validation
}
}
if o.Disk != "" {
if _, err := os.Stat(o.Disk); err != nil {
if IsWindowsRawDevicePath(o.Disk) {
if mode := strings.ToLower(strings.TrimSpace(o.DiskMode)); mode != "" && mode != "in-place" && mode != "inplace" {
issues = append(issues, ValidationIssue{Field: "disk_mode", Code: "raw_disk_in_place_only", Message: i18n.T(loc, "validate.raw_disk_in_place_only")})
}
} else if _, err := os.Stat(o.Disk); err != nil {
issues = append(issues, ValidationIssue{Field: "disk", Code: "disk_not_found", Message: i18n.T(loc, "validate.disk_not_found")})
}
}
if dc := strings.ToLower(strings.TrimSpace(o.DiskController)); dc != "" && dc != "nvme" && dc != "ahci" && dc != "virtio" {
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "invalid_disk_controller", Message: i18n.T(loc, "validate.invalid_disk_controller")})
}
if !validDiskCache(o.DiskCache) {
issues = append(issues, ValidationIssue{Field: "disk_cache", Code: "invalid_disk_cache", Message: i18n.T(loc, "validate.invalid_disk_cache")})
}
if o.Installer != "" {
if _, err := os.Stat(o.Installer); err != nil {
issues = append(issues, ValidationIssue{Field: "installer", Code: "installer_not_found", Message: i18n.T(loc, "validate.installer_not_found")})
@@ -322,6 +341,9 @@ func ValidateSet(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale)
if o.DiskController != "" && current.HasInstaller {
issues = append(issues, ValidationIssue{Field: "disk_controller", Code: "eject_before_controller_change", Message: i18n.T(loc, "validate.eject_before_controller_change")})
}
if !validDiskCache(o.DiskCache) {
issues = append(issues, ValidationIssue{Field: "disk_cache", Code: "invalid_disk_cache", Message: i18n.T(loc, "validate.invalid_disk_cache")})
}
if o.GPU != "" && o.GPU != "auto" && strings.HasSuffix(strings.ToLower(o.GPU), ".json") {
if _, err := os.Stat(o.GPU); err != nil {
issues = append(issues, ValidationIssue{Field: "gpu", Code: "gpu_icd_not_found", Message: i18n.T(loc, "validate.gpu_icd_not_found")})
@@ -383,8 +405,13 @@ func BuildCreateArgs(o CreateOpts) ([]string, error) {
args = append(args, "--disk", o.Disk)
if o.DiskMode != "" {
args = append(args, "--disk-mode", o.DiskMode)
} else if IsWindowsRawDevicePath(o.Disk) {
args = append(args, "--disk-mode", "in-place")
}
}
if dcache := strings.ToLower(strings.TrimSpace(o.DiskCache)); dcache != "" && dcache != "default" {
args = append(args, "--disk-cache", dcache)
}
if o.Graphics != "" {
args = append(args, "--graphics", o.Graphics)
}
@@ -510,6 +537,9 @@ func BuildSetArgs(o SetOpts) ([]string, error) {
if o.DiskController != "" {
args = append(args, "--disk-controller", o.DiskController)
}
if dcache := strings.ToLower(strings.TrimSpace(o.DiskCache)); dcache != "" {
args = append(args, "--disk-cache", dcache)
}
if o.Resolution != "" {
args = append(args, "--resolution", o.Resolution)
}
@@ -592,6 +622,15 @@ func parseDisplayCount(v string) int {
return 1
}
func validDiskCache(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "", "default", "writeback", "none", "unsafe":
return true
default:
return false
}
}
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192).
func ParseShow(name, text string) VMDetail {
@@ -600,6 +639,7 @@ func ParseShow(name, text string) VMDetail {
Displays: 1,
Resolution: "1920x1080",
DiskController: "ahci",
DiskCache: "default",
Graphics: "reims-vgpu",
GPU: "auto",
Capture: true,
@@ -639,6 +679,10 @@ func ParseShow(name, text string) VMDetail {
default:
d.DiskController = "ahci"
}
case "disk cache":
if low := strings.ToLower(strings.TrimSpace(v)); low != "" {
d.DiskCache = low
}
case "graphics":
// "VMware SVGA, no GPU acceleration, in QEMU's window" (3731afd
// cli.rs describe); older builds printed "vmware-svga".
+2
View File
@@ -521,7 +521,9 @@
"validate.missing_release": "Choose the macOS release to install offline",
"validate.invalid_disk_size": "New disk size must be at least 32G (recommended 128G)",
"validate.disk_not_found": "Selected disk image file does not exist",
"validate.raw_disk_in_place_only": "Windows raw disk or partition paths must be attached in place",
"validate.invalid_disk_controller": "Disk controller must be nvme, ahci, or virtio",
"validate.invalid_disk_cache": "Disk cache mode must be default, writeback, none, or unsafe",
"validate.installer_not_found": "Selected installer image file does not exist",
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
"validate.invalid_resolution": "Resolution must match WIDTHxHEIGHT (e.g. 1920x1080)",
+10
View File
@@ -379,11 +379,21 @@
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
"diskControllerVirtioHint": "Lower overhead but experimental; switch back to NVMe if you hit problems",
"diskControllerNvmeReadyHint": "Fast and works with Recovery. Recommended",
"diskCacheTitle": "Disk I/O cache",
"diskCacheDescDefault": "Follows the current runtime default (writeback caching, flushes forwarded to host)",
"diskCacheDescWriteback": "Uses host page cache and forwards guest flushes safely to disk",
"diskCacheDescNone": "Direct I/O bypassing host page cache; recommended for raw partition passthrough",
"diskCacheDescUnsafe": "Warning: ignores guest flushes for peak throughput; host power loss or crash can corrupt the disk",
"diskCacheOptionDefault": "Default",
"diskCacheOptionWriteback": "Writeback",
"diskCacheOptionNone": "Direct",
"diskCacheOptionUnsafe": "Unsafe",
"diskUsageSummary": "{actual} used of {virtual}",
"diskResizeTitle": "Expand disk",
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
"diskResizeAction": "Expand",
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
"diskResizeRawDisabled": "Windows raw partitions cannot be resized here",
"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.",
+2
View File
@@ -521,7 +521,9 @@
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.invalid_disk_size": "新建磁盘上限不能小于 32G(推荐 128G)",
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
"validate.raw_disk_in_place_only": "Windows 裸分区或物理盘路径仅支持原地直挂(in-place)",
"validate.invalid_disk_controller": "磁盘控制器仅支持 nvme、ahci 或 virtio",
"validate.invalid_disk_cache": "磁盘缓存策略仅支持 default、writeback、none 或 unsafe",
"validate.installer_not_found": "所选安装镜像文件不存在",
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
"validate.invalid_resolution": "分辨率格式须为 宽x高(如 1920x1080)",
+10
View File
@@ -379,11 +379,21 @@
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
"diskControllerVirtioHint": "VirtIO 开销更低,仍属实验性;遇到问题请改回 NVMe",
"diskControllerNvmeReadyHint": "NVMe 速度快,也兼容恢复模式,推荐",
"diskCacheTitle": "磁盘 I/O 缓存策略",
"diskCacheDescDefault": "跟随运行时默认策略(回写缓存并正常转发刷盘请求)",
"diskCacheDescWriteback": "经宿主机页缓存回写,并安全转发 Guest 刷盘请求",
"diskCacheDescNone": "绕过宿主机页缓存直通磁盘(Direct I/O),适合裸分区直挂",
"diskCacheDescUnsafe": "警告:忽略 Guest 刷盘指令以换取最高吞吐,宿主机断电或崩溃可能导致磁盘损坏",
"diskCacheOptionDefault": "默认",
"diskCacheOptionWriteback": "回写",
"diskCacheOptionNone": "直通",
"diskCacheOptionUnsafe": "激进 (Unsafe)",
"diskUsageSummary": "已占用 {actual},上限 {virtual}",
"diskResizeTitle": "扩大磁盘",
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
"diskResizeAction": "扩容",
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
"diskResizeRawDisabled": "Windows 裸分区不支持在此调整容量",
"diskCompactTitle": "回收空间",
"diskRewriteSnapshots": "请先删除内部恢复点,以免重写磁盘时丢失。",
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",