From e800d55f9f60d5cd5b7ef580a974e37bc85afbdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Mon, 30 Nov 2026 00:02:02 -0700 Subject: [PATCH] feat(disk): preserve qcow2 creation options across compact, clone, and import --- internal/driver/reims/compat_test.go | 9 +- internal/driver/reims/disk_import.go | 174 +++++++++++++++++++++++-- internal/driver/reims/disk_ops_test.go | 81 ++++++++++++ 3 files changed, 253 insertions(+), 11 deletions(-) diff --git a/internal/driver/reims/compat_test.go b/internal/driver/reims/compat_test.go index 70377b8..4822b30 100644 --- a/internal/driver/reims/compat_test.go +++ b/internal/driver/reims/compat_test.go @@ -208,12 +208,17 @@ func TestDiskImportAndCoWArgs(t *testing.T) { if NeedsDiskConversion(`D:\vms\disk.qcow2`) || NeedsDiskConversion(`D:\vms\disk.img`) { t.Fatalf("did not expect .qcow2/.img to need conversion") } + wantOpts := DefaultQCOW2CreateOptions().OptionString() conv := strings.Join(BuildConvertToQCOW2Args("in.vmdk", "out.qcow2"), " ") - if conv != "convert -O qcow2 in.vmdk out.qcow2" { + if conv != "convert -O qcow2 -o "+wantOpts+" in.vmdk out.qcow2" { t.Fatalf("BuildConvertToQCOW2Args = %q", conv) } cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ") - if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 cow-dev.qcow2" { + if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 -o "+wantOpts+" cow-dev.qcow2" { t.Fatalf("BuildCoWOverlayArgs = %q", cow) } + cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp"), " ") + if cmp != "convert -p -f qcow2 -O qcow2 -o "+wantOpts+" disk.qcow2 disk.compact.tmp" { + t.Fatalf("BuildCompactDiskArgs = %q", cmp) + } } diff --git a/internal/driver/reims/disk_import.go b/internal/driver/reims/disk_import.go index 21b823d..a6a10a9 100644 --- a/internal/driver/reims/disk_import.go +++ b/internal/driver/reims/disk_import.go @@ -3,6 +3,7 @@ package reims import ( "context" "encoding/binary" + "encoding/json" "fmt" "io" "os" @@ -96,15 +97,140 @@ func HasQCOW2BackingFile(path string) (bool, error) { return binary.BigEndian.Uint64(hdr[8:16]) != 0, nil } +// QCOW2CreateOptions is the single source of truth for qcow2 image creation +// options passed via `qemu-img ... -o ` across import conversion, +// compaction, and CoW overlay derivation. +type QCOW2CreateOptions struct { + Compat string + ClusterSize uint64 + LazyRefcounts *bool + ExtendedL2 *bool + RefcountBits int + CompressionType string +} + +func boolPtr(v bool) *bool { return &v } + +// DefaultQCOW2CreateOptions returns the canonical qcow2 creation defaults +// matching upstream reims-ctl / QEMU 11 defaults. +func DefaultQCOW2CreateOptions() QCOW2CreateOptions { + return QCOW2CreateOptions{ + Compat: "1.1", + ClusterSize: 65536, + LazyRefcounts: boolPtr(false), + ExtendedL2: boolPtr(false), + RefcountBits: 16, + } +} + +// OptionString formats non-zero fields into a deterministic `qemu-img -o` +// comma-separated option string. +func (o QCOW2CreateOptions) OptionString() string { + var parts []string + compat := strings.TrimSpace(o.Compat) + if compat != "" { + parts = append(parts, "compat="+compat) + } + if o.ClusterSize > 0 { + parts = append(parts, fmt.Sprintf("cluster_size=%d", o.ClusterSize)) + } + // qcow2 compat=0.10 (v2) does not support v3 format extensions. + if compat != "0.10" { + if o.LazyRefcounts != nil { + parts = append(parts, "lazy_refcounts="+onOff(*o.LazyRefcounts)) + } + if o.ExtendedL2 != nil { + parts = append(parts, "extended_l2="+onOff(*o.ExtendedL2)) + } + if o.RefcountBits > 0 { + parts = append(parts, fmt.Sprintf("refcount_bits=%d", o.RefcountBits)) + } + if ct := strings.TrimSpace(o.CompressionType); ct != "" { + parts = append(parts, "compression_type="+ct) + } + } + return strings.Join(parts, ",") +} + +func onOff(v bool) string { + if v { + return "on" + } + return "off" +} + +type qcow2InfoJSON struct { + Format string `json:"format"` + ClusterSize uint64 `json:"cluster-size"` + FormatSpecific *struct { + Type string `json:"type"` + Data struct { + Compat string `json:"compat"` + LazyRefcounts *bool `json:"lazy-refcounts"` + ExtendedL2 *bool `json:"extended-l2"` + RefcountBits int `json:"refcount-bits"` + CompressionType string `json:"compression-type"` + } `json:"data"` + } `json:"format-specific"` +} + +// ParseQCOW2CreateOptionsFromInfoJSON extracts qcow2 creation options from +// `qemu-img info --output=json` output so compaction and CoW overlays preserve +// the exact geometry and feature flags of the source image. +func ParseQCOW2CreateOptionsFromInfoJSON(raw []byte) (QCOW2CreateOptions, error) { + var info qcow2InfoJSON + if err := json.Unmarshal(raw, &info); err != nil { + return QCOW2CreateOptions{}, fmt.Errorf("decode qemu-img info: %w", err) + } + if info.Format != "qcow2" { + return QCOW2CreateOptions{}, fmt.Errorf("expected qcow2 image, got %q", info.Format) + } + opts := QCOW2CreateOptions{ + ClusterSize: info.ClusterSize, + } + if info.FormatSpecific != nil && info.FormatSpecific.Type == "qcow2" { + d := info.FormatSpecific.Data + opts.Compat = d.Compat + opts.LazyRefcounts = d.LazyRefcounts + opts.ExtendedL2 = d.ExtendedL2 + opts.RefcountBits = d.RefcountBits + opts.CompressionType = d.CompressionType + } + return opts, nil +} + +// InspectQCOW2CreateOptions runs `qemu-img info --force-share --output=json` +// on diskPath and returns its qcow2 creation options. +func InspectQCOW2CreateOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string) (QCOW2CreateOptions, error) { + cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--force-share", "--output=json", diskPath) + configureCmd(cmd) + cmd.Env = env + out, err := cmd.CombinedOutput() + if err != nil { + return QCOW2CreateOptions{}, fmt.Errorf("qemu-img info %s: %w (%s)", filepath.Base(diskPath), err, strings.TrimSpace(string(out))) + } + return ParseQCOW2CreateOptionsFromInfoJSON(out) +} + // BuildResizeDiskArgs builds `qemu-img resize` arguments. func BuildResizeDiskArgs(diskPath, sizeArg string) []string { return []string{"resize", diskPath, sizeArg} } // BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments -// for reclaiming unallocated/trimmed space into a fresh sparse qcow2 file. +// using the default qcow2 creation options. func BuildCompactDiskArgs(srcPath, dstPath string) []string { - return []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2", srcPath, dstPath} + return BuildCompactDiskArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) +} + +// BuildCompactDiskArgsWithOptions builds `qemu-img convert -p -f qcow2 -O qcow2` +// arguments preserving explicit qcow2 creation options. +func BuildCompactDiskArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { + args := []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2"} + if optStr := opts.OptionString(); optStr != "" { + args = append(args, "-o", optStr) + } + return append(args, srcPath, dstPath) } // NeedsDiskConversion reports whether srcPath is a disk format (VMDK or RAW) @@ -114,15 +240,36 @@ func NeedsDiskConversion(srcPath string) bool { return ext == ".vmdk" || ext == ".raw" } -// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments. +// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments +// using the canonical default qcow2 creation options. func BuildConvertToQCOW2Args(srcPath, dstPath string) []string { - return []string{"convert", "-O", "qcow2", srcPath, dstPath} + return BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions()) } -// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b -F qcow2 ` -// arguments for instant copy-on-write VM derivation. +// BuildConvertToQCOW2ArgsWithOptions constructs `qemu-img convert -O qcow2` +// arguments with explicit qcow2 creation options. +func BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string { + args := []string{"convert", "-O", "qcow2"} + if optStr := opts.OptionString(); optStr != "" { + args = append(args, "-o", optStr) + } + return append(args, srcPath, dstPath) +} + +// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b -F qcow2` +// arguments using the default qcow2 creation options. func BuildCoWOverlayArgs(backingPath, overlayPath string) []string { - return []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2", overlayPath} + return BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, DefaultQCOW2CreateOptions()) +} + +// BuildCoWOverlayArgsWithOptions constructs `qemu-img create -f qcow2 -b -F qcow2` +// arguments with explicit qcow2 creation options inherited from the backing image. +func BuildCoWOverlayArgsWithOptions(backingPath, overlayPath string, opts QCOW2CreateOptions) []string { + args := []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2"} + if optStr := opts.OptionString(); optStr != "" { + args = append(args, "-o", optStr) + } + return append(args, overlayPath) } // ConvertDiskToQCOW2 converts a VMDK or RAW disk image to qcow2 using the @@ -162,7 +309,11 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac if err := os.MkdirAll(filepath.Dir(overlayPath), 0o755); err != nil { return err } - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath)...) + opts, err := InspectQCOW2CreateOptions(ctx, qemuImgPath, env, backingPath) + if err != nil { + return fmt.Errorf("inspect backing qcow2 options: %w", err) + } + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { @@ -245,12 +396,17 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath } } + opts, err := InspectQCOW2CreateOptions(ctx, qemuImgPath, env, diskPath) + if err != nil { + return DiskCompactResult{}, fmt.Errorf("inspect source qcow2 options: %w", err) + } + tmpPath := diskPath + ".compact.tmp" bakPath := diskPath + ".compact.bak" _ = os.Remove(tmpPath) defer os.Remove(tmpPath) - cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath)...) + cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgsWithOptions(diskPath, tmpPath, opts)...) configureCmd(cmd) cmd.Env = env if stdout != nil { diff --git a/internal/driver/reims/disk_ops_test.go b/internal/driver/reims/disk_ops_test.go index 3dd960e..c05d5ea 100644 --- a/internal/driver/reims/disk_ops_test.go +++ b/internal/driver/reims/disk_ops_test.go @@ -97,4 +97,85 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) { if cmp.AfterBytes == 0 { t.Fatalf("CompactDisk AfterBytes = 0") } + + // Verify non-default qcow2 options (cluster_size, lazy_refcounts, extended_l2) + // are preserved across both CompactDisk and CreateCoWOverlay. + customDisk := filepath.Join(dir, "custom.qcow2") + if out, err := exec.Command(qemuImg, "create", "-f", "qcow2", + "-o", "compat=1.1,cluster_size=131072,lazy_refcounts=on,extended_l2=on,refcount_bits=16", + customDisk, "64M").CombinedOutput(); err != nil { + t.Fatalf("create custom qcow2: %v (%s)", err, string(out)) + } + beforeOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, customDisk) + if err != nil { + t.Fatalf("InspectQCOW2CreateOptions(before): %v", err) + } + if beforeOpts.ClusterSize != 131072 || beforeOpts.LazyRefcounts == nil || !*beforeOpts.LazyRefcounts || beforeOpts.ExtendedL2 == nil || !*beforeOpts.ExtendedL2 { + t.Fatalf("unexpected beforeOpts: %+v", beforeOpts) + } + + if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, nil, nil); err != nil { + t.Fatalf("CompactDisk(custom): %v", err) + } + afterCompactOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, customDisk) + if err != nil { + t.Fatalf("InspectQCOW2CreateOptions(after compact): %v", err) + } + if afterCompactOpts.OptionString() != beforeOpts.OptionString() { + t.Fatalf("CompactDisk lost qcow2 options:\n got %s\n want %s", afterCompactOpts.OptionString(), beforeOpts.OptionString()) + } + + overlay := filepath.Join(dir, "custom-overlay.qcow2") + if err := CreateCoWOverlay(context.Background(), qemuImg, nil, customDisk, overlay, nil, nil); err != nil { + t.Fatalf("CreateCoWOverlay(custom): %v", err) + } + overlayOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, overlay) + if err != nil { + t.Fatalf("InspectQCOW2CreateOptions(overlay): %v", err) + } + if overlayOpts.OptionString() != beforeOpts.OptionString() { + t.Fatalf("CreateCoWOverlay lost qcow2 options:\n got %s\n want %s", overlayOpts.OptionString(), beforeOpts.OptionString()) + } +} + +func TestParseQCOW2CreateOptionsFromInfoJSON(t *testing.T) { + raw := []byte(`{ + "format": "qcow2", + "cluster-size": 131072, + "format-specific": { + "type": "qcow2", + "data": { + "compat": "1.1", + "compression-type": "zstd", + "lazy-refcounts": true, + "refcount-bits": 16, + "extended-l2": true + } + } + }`) + opts, err := ParseQCOW2CreateOptionsFromInfoJSON(raw) + if err != nil { + t.Fatalf("ParseQCOW2CreateOptionsFromInfoJSON: %v", err) + } + want := "compat=1.1,cluster_size=131072,lazy_refcounts=on,extended_l2=on,refcount_bits=16,compression_type=zstd" + if got := opts.OptionString(); got != want { + t.Fatalf("OptionString() = %q, want %q", got, want) + } + + // compat=0.10 must omit v3-only options. + v2 := QCOW2CreateOptions{ + Compat: "0.10", + ClusterSize: 65536, + LazyRefcounts: boolPtr(true), + ExtendedL2: boolPtr(true), + RefcountBits: 16, + } + if got := v2.OptionString(); got != "compat=0.10,cluster_size=65536" { + t.Fatalf("compat=0.10 OptionString() = %q", got) + } + + // Non-qcow2 format rejected. + if _, err := ParseQCOW2CreateOptionsFromInfoJSON([]byte(`{"format":"raw"}`)); err == nil { + t.Fatal("expected error for raw format") + } }