Files
Reims-Go/internal/driver/reims/disk_import.go
T

456 lines
16 KiB
Go

package reims
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/Nwflower/reims-go/internal/host"
)
// GuestAPFSExpandCommand repairs the GPT backup header moved by `qemu-img resize`
// and grows the APFS container backing `/` to fill the newly expanded disk,
// regardless of whether macOS assigned the system disk to disk0, disk1, or disk2.
const GuestAPFSExpandCommand = `P=$(diskutil info / | awk '/APFS Container:/{print $3}'); S=$(diskutil apfs list "$P" | awk '/APFS Physical Store Disk:/{print $5}'); D=${S%s*}; diskutil repairDisk "$D" && diskutil apfs resizeContainer "$S" 0`
type DiskResizeResult struct {
Path string `json:"path"`
OldVirtualBytes uint64 `json:"old_virtual_bytes"`
NewVirtualBytes uint64 `json:"new_virtual_bytes"`
GuestExpandCmd string `json:"guest_expand_cmd"`
}
type DiskCompactResult struct {
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
}
var reResizeSpec = regexp.MustCompile(`^(?i)(\+)?\s*(\d+)\s*([GM])$`)
// ParseResizeTarget parses an absolute size ("256G") or relative delta ("+64G")
// and verifies it strictly grows the virtual disk without shrinking.
func ParseResizeTarget(currentVirtualBytes uint64, raw string) (uint64, string, error) {
m := reResizeSpec.FindStringSubmatch(strings.TrimSpace(raw))
if len(m) != 4 {
return 0, "", fmt.Errorf("invalid disk size %q (use e.g. 256G or +64G)", raw)
}
isDelta := m[1] == "+"
n, err := strconv.ParseUint(m[2], 10, 64)
if err != nil || n == 0 {
return 0, "", fmt.Errorf("disk size must be positive")
}
unit := strings.ToUpper(m[3])
var mult uint64 = 1 << 30
if unit == "M" {
mult = 1 << 20
}
const maxDiskBytes = uint64(16384) << 30 // 16 TiB sanity cap
valBytes := n * mult
if valBytes/mult != n {
return 0, "", fmt.Errorf("disk size overflows limit")
}
var newBytes uint64
var arg string
if isDelta {
newBytes = currentVirtualBytes + valBytes
arg = fmt.Sprintf("+%d%s", n, unit)
} else {
newBytes = valBytes
arg = fmt.Sprintf("%d%s", n, unit)
}
if newBytes <= currentVirtualBytes {
curGB := float64(currentVirtualBytes) / float64(1<<30)
return 0, "", fmt.Errorf("new size (%s) must be larger than current capacity (%.0fG); shrinking is not supported", raw, curGB)
}
if newBytes > maxDiskBytes {
return 0, "", fmt.Errorf("target disk size exceeds 16 TB limit")
}
return newBytes, arg, nil
}
// HasQCOW2BackingFile reports whether path is a qcow2 image with a non-zero
// backing_file_offset in its header (i.e. a CoW overlay).
func HasQCOW2BackingFile(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
var hdr [16]byte
if _, err := f.ReadAt(hdr[:], 0); err != nil {
return false, err
}
if string(hdr[:4]) != "QFI\xfb" {
return false, nil
}
return binary.BigEndian.Uint64(hdr[8:16]) != 0, nil
}
// QCOW2CreateOptions is the single source of truth for qcow2 image creation
// options passed via `qemu-img ... -o <opts>` 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
// using the default qcow2 creation options.
func BuildCompactDiskArgs(srcPath, dstPath string) []string {
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)
// that should be converted to qcow2 via qemu-img before handing off to reims-ctl.
func NeedsDiskConversion(srcPath string) bool {
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(srcPath)))
return ext == ".vmdk" || ext == ".raw"
}
// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments
// using the canonical default qcow2 creation options.
func BuildConvertToQCOW2Args(srcPath, dstPath string) []string {
return BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions())
}
// 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 <backing> -F qcow2`
// arguments using the default qcow2 creation options.
func BuildCoWOverlayArgs(backingPath, overlayPath string) []string {
return BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, DefaultQCOW2CreateOptions())
}
// BuildCoWOverlayArgsWithOptions constructs `qemu-img create -f qcow2 -b <backing> -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
// portable runtime's qemu-img binary.
func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, srcPath, dstPath string, stdout, stderr io.Writer) error {
if _, err := os.Stat(qemuImgPath); err != nil {
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
return err
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
_ = os.Remove(dstPath)
return fmt.Errorf("qemu-img convert %s: %w", filepath.Base(srcPath), err)
}
return nil
}
// CreateCoWOverlay creates an instant qcow2 copy-on-write overlay backed by
// backingPath without modifying the backing disk image.
func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, backingPath, overlayPath string, stdout, stderr io.Writer) error {
if _, err := os.Stat(qemuImgPath); err != nil {
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
if _, err := os.Stat(backingPath); err != nil {
return fmt.Errorf("backing disk not found (%s): %w", backingPath, err)
}
if err := os.MkdirAll(filepath.Dir(overlayPath), 0o755); err != nil {
return err
}
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 {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
_ = os.Remove(overlayPath)
return fmt.Errorf("qemu-img create CoW overlay: %w", err)
}
return nil
}
// ResizeDisk expands a stopped VM's disk image via `qemu-img resize`.
func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath, sizeSpec string, stdout, stderr io.Writer) (DiskResizeResult, error) {
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskResizeResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
}
newBytes, arg, err := ParseResizeTarget(before.VirtualBytes, sizeSpec)
if err != nil {
return DiskResizeResult{}, err
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildResizeDiskArgs(diskPath, arg)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
return DiskResizeResult{}, fmt.Errorf("qemu-img resize %s %s: %w", filepath.Base(diskPath), arg, err)
}
after, err := host.InspectDiskUsage(diskPath)
if err == nil && after.VirtualBytes > 0 {
newBytes = after.VirtualBytes
}
return DiskResizeResult{
Path: diskPath,
OldVirtualBytes: before.VirtualBytes,
NewVirtualBytes: newBytes,
GuestExpandCmd: GuestAPFSExpandCommand,
}, nil
}
// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly
// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically
// swaps it into place to reclaim deleted/TRIMmed host disk space.
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) {
if _, err := os.Stat(qemuImgPath); err != nil {
return DiskCompactResult{}, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
}
if before.Format != "qcow2" {
return DiskCompactResult{}, fmt.Errorf("only qcow2 disks can be compacted (found %s)", before.Format)
}
if hasBacking, err := HasQCOW2BackingFile(diskPath); err != nil {
return DiskCompactResult{}, err
} else if hasBacking {
return DiskCompactResult{}, fmt.Errorf("cannot compact a CoW overlay disk directly (it shares a backing image); compact the base VM instead")
}
dir := filepath.Dir(diskPath)
const safetyMarginBytes = uint64(2) << 30 // 2 GiB safety headroom
if freeBytes, ok := host.FreeDiskBytesAt(dir); ok {
need := before.ActualBytes + safetyMarginBytes
if freeBytes < need {
return DiskCompactResult{}, fmt.Errorf("not enough free space to compact safely: need ~%.1f GB free, only %.1f GB available",
float64(need)/float64(1<<30), float64(freeBytes)/float64(1<<30))
}
}
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, BuildCompactDiskArgsWithOptions(diskPath, tmpPath, opts)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
}
if stderr != nil {
cmd.Stderr = stderr
}
if err := cmd.Run(); err != nil {
return DiskCompactResult{}, fmt.Errorf("qemu-img convert (compact): %w", err)
}
// Verify integrity of the compacted image before touching the original.
chk := exec.CommandContext(ctx, qemuImgPath, "check", "-q", tmpPath)
configureCmd(chk)
chk.Env = env
if out, err := chk.CombinedOutput(); err != nil {
return DiskCompactResult{}, fmt.Errorf("compacted qcow2 integrity check failed: %w (%s)", err, strings.TrimSpace(string(out)))
}
_ = os.Remove(bakPath)
if err := os.Rename(diskPath, bakPath); err != nil {
return DiskCompactResult{}, fmt.Errorf("swap disk backup: %w", err)
}
if err := os.Rename(tmpPath, diskPath); err != nil {
_ = os.Rename(bakPath, diskPath)
return DiskCompactResult{}, fmt.Errorf("replace compacted disk: %w", err)
}
_ = os.Remove(bakPath)
after, err := host.InspectDiskUsage(diskPath)
afterBytes := before.ActualBytes
if err == nil {
afterBytes = after.ActualBytes
}
var reclaimed uint64
if before.ActualBytes > afterBytes {
reclaimed = before.ActualBytes - afterBytes
}
return DiskCompactResult{
Path: diskPath,
BeforeBytes: before.ActualBytes,
AfterBytes: afterBytes,
ReclaimedBytes: reclaimed,
}, nil
}