A running reims-ctl create looks the same as a killed one: it is unregistered and has no vm.toml until it ends. Cloning or creating through the driver no longer deletes such a directory. Also drop a wrapper only tests called. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
730 lines
27 KiB
Go
730 lines
27 KiB
Go
package reims
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/filelock"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
)
|
|
|
|
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, CompactDiskOptions{}, nil, nil)
|
|
_, optimizeErr := CompactDisk(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
|
|
|
|
got, arg, err := ParseResizeTarget(cur, "256G")
|
|
if err != nil || got != 256*gib || arg != "256G" {
|
|
t.Fatalf("ParseResizeTarget(256G) = (%d, %q, %v)", got, arg, err)
|
|
}
|
|
got, arg, err = ParseResizeTarget(cur, "+64g")
|
|
if err != nil || got != 192*gib || arg != "+64G" {
|
|
t.Fatalf("ParseResizeTarget(+64g) = (%d, %q, %v)", got, arg, err)
|
|
}
|
|
for _, bad := range []string{"128G", "64G", "-32G", "0G", "+0G", "abc", "99999G"} {
|
|
if _, _, err := ParseResizeTarget(cur, bad); err == nil {
|
|
t.Fatalf("ParseResizeTarget(%q) expected error", bad)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHasQCOW2BackingFile(t *testing.T) {
|
|
dir := t.TempDir()
|
|
standalone := filepath.Join(dir, "standalone.qcow2")
|
|
overlay := filepath.Join(dir, "overlay.qcow2")
|
|
|
|
var h [24]byte
|
|
copy(h[:4], "QFI\xfb")
|
|
binary.BigEndian.PutUint32(h[4:8], 3)
|
|
if err := os.WriteFile(standalone, h[:], 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if has, err := HasQCOW2BackingFile(standalone); err != nil || has {
|
|
t.Fatalf("standalone HasQCOW2BackingFile = (%v, %v), want (false, nil)", has, err)
|
|
}
|
|
|
|
parent := filepath.Base(standalone)
|
|
binary.BigEndian.PutUint64(h[8:16], uint64(len(h)))
|
|
binary.BigEndian.PutUint32(h[16:20], uint32(len(parent)))
|
|
if err := os.WriteFile(overlay, append(h[:], parent...), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if has, err := HasQCOW2BackingFile(overlay); err != nil || !has {
|
|
t.Fatalf("overlay HasQCOW2BackingFile = (%v, %v), want (true, nil)", has, err)
|
|
}
|
|
}
|
|
|
|
func TestCoWRegisteredChainsAndDeletion(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
ctx := context.Background()
|
|
base := filepath.Join(root, "base", "disk.qcow2")
|
|
middle := c.CoWImagePath("middle")
|
|
orphan := c.CoWImagePath("orphan")
|
|
linked := filepath.Join(root, "custom", "linked-disk.img")
|
|
empty := filepath.Join(root, "damaged", "disk.qcow2")
|
|
writeTestCoWFile(t, base, nil)
|
|
writeTestCoWFile(t, empty, nil)
|
|
writeTestCoWFile(t, middle, testBackingHeader(base))
|
|
writeTestCoWFile(t, orphan, testBackingHeader(base))
|
|
writeTestCoWFile(t, linked, testBackingHeader(middle))
|
|
baseVM := testDiskVM(t, "base", filepath.Dir(base), base)
|
|
middleVM := testDiskVM(t, "middle", filepath.Join(root, "middle"), middle)
|
|
linkedVM := testDiskVM(t, "linked", filepath.Dir(linked), linked)
|
|
damagedVM := testDiskVM(t, "damaged", filepath.Dir(empty), empty)
|
|
|
|
writeTestRegistrations(t, c, baseVM, middleVM, linkedVM, damagedVM)
|
|
err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
|
|
t.Fatal("cannot delete a managed image used by another VM")
|
|
return nil
|
|
})
|
|
assertCoWInUse(t, err, linkedVM.Name)
|
|
|
|
writeTestRegistrations(t, c, baseVM, linkedVM, damagedVM)
|
|
release, err := c.LockDiskForWrite(ctx, baseVM.Name, base)
|
|
if release != nil {
|
|
release()
|
|
}
|
|
assertCoWInUse(t, err, linkedVM.Name)
|
|
|
|
writeTestRegistrations(t, c, baseVM, middleVM, damagedVM)
|
|
if err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
|
|
writeTestRegistrations(t, c, baseVM, damagedVM)
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := os.Stat(middle); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("deleted VM's overlay remains: %v", err)
|
|
}
|
|
if _, err := os.Stat(orphan); err != nil {
|
|
t.Fatalf("unregistered disk should be preserved: %v", err)
|
|
}
|
|
release, err = c.LockDiskForWrite(ctx, baseVM.Name, "")
|
|
if err != nil {
|
|
t.Fatalf("historical orphan or truncated disk blocked the parent: %v", err)
|
|
}
|
|
release()
|
|
}
|
|
|
|
func TestCoWBrokenVMDeletionAndKeepFiles(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
ctx := context.Background()
|
|
broken := driver.VMInfo{Name: "broken", Directory: filepath.Join(root, "broken")}
|
|
writeTestCoWFile(t, filepath.Join(broken.Directory, "vm.toml"), []byte("invalid = ["))
|
|
disk := filepath.Join(broken.Directory, "nested", "base.qcow2")
|
|
overlay := c.CoWImagePath("child")
|
|
child := testDiskVM(t, "child", filepath.Join(root, "child"), overlay)
|
|
writeTestCoWFile(t, overlay, testBackingHeader(disk))
|
|
writeTestRegistrations(t, c, broken, child)
|
|
assertCoWInUse(t, c.deleteWithCoW(ctx, broken.Name, false, nil, func() error {
|
|
t.Fatal("cannot delete the backing disk inside a broken VM directory")
|
|
return nil
|
|
}), child.Name)
|
|
|
|
if err := c.deleteWithCoW(ctx, child.Name, true, nil, func() error {
|
|
writeTestRegistrations(t, c, broken)
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := os.Stat(overlay); err != nil {
|
|
t.Fatalf("keep-files removed the clone disk: %v", err)
|
|
}
|
|
if err := c.deleteWithCoW(ctx, broken.Name, false, nil, func() error { return nil }); err != nil {
|
|
t.Fatalf("broken VM with no registered dependents should be deletable: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCoWDiskLocksSeparateDisksAndShareHardLinks(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images")}
|
|
first, second := filepath.Join(root, "first.qcow2"), filepath.Join(root, "second.qcow2")
|
|
writeTestCoWFile(t, first, nil)
|
|
writeTestCoWFile(t, second, nil)
|
|
release, err := c.LockCoWDisks(context.Background(), first)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer release()
|
|
unrelated, err := c.LockCoWDisks(context.Background(), second)
|
|
if err != nil {
|
|
t.Fatalf("the second disk waited on the first: %v", err)
|
|
}
|
|
unrelated()
|
|
alias := filepath.Join(root, "first-alias.qcow2")
|
|
if err := os.Link(first, alias); err != nil {
|
|
t.Skipf("hardlinks unavailable: %v", err)
|
|
}
|
|
wait, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
|
|
defer cancel()
|
|
aliasLock, err := c.LockCoWDisks(wait, alias)
|
|
if aliasLock != nil {
|
|
aliasLock()
|
|
}
|
|
if !errors.Is(err, context.DeadlineExceeded) {
|
|
t.Fatalf("hardlinked alias should share the lock: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCoWCloneRefusesDiskInUseByAnotherVM(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images")}
|
|
disk := filepath.Join(root, "shared.qcow2")
|
|
writeTestCoWFile(t, disk, nil)
|
|
source := testDiskVM(t, "source", filepath.Join(root, "source"), disk)
|
|
active := testDiskVM(t, "active", filepath.Join(root, "active"), disk)
|
|
vms := []VMListItem{
|
|
{Name: source.Name, Dir: source.Directory, State: "stopped"},
|
|
{Name: active.Name, Dir: active.Directory, State: "running"},
|
|
}
|
|
err := c.checkCoWCloneSource(vms, source.Name, disk, "clone")
|
|
var coded *i18n.CodedError
|
|
if !errors.As(err, &coded) || coded.Code != "E_COW_DISK_RUNNING" || coded.Params["name"] != active.Name {
|
|
t.Fatalf("expected the active VM to prevent cloning its disk, got %v", err)
|
|
}
|
|
}
|
|
|
|
func testBackingHeader(parent string) []byte {
|
|
const offset = 104
|
|
header := make([]byte, offset+len(parent))
|
|
copy(header, "QFI\xfb")
|
|
binary.BigEndian.PutUint32(header[4:8], 3)
|
|
binary.BigEndian.PutUint64(header[8:16], offset)
|
|
binary.BigEndian.PutUint32(header[16:20], uint32(len(parent)))
|
|
copy(header[offset:], parent)
|
|
return header
|
|
}
|
|
|
|
func testDiskVM(t *testing.T, name, dir, disk string) driver.VMInfo {
|
|
t.Helper()
|
|
writeTestCoWFile(t, filepath.Join(dir, "vm.toml"), []byte(fmt.Sprintf("disk = %q\n", disk)))
|
|
return driver.VMInfo{Name: name, Directory: dir}
|
|
}
|
|
|
|
func writeTestRegistrations(t *testing.T, c *Client, vms ...driver.VMInfo) {
|
|
t.Helper()
|
|
var registry strings.Builder
|
|
for _, vm := range vms {
|
|
fmt.Fprintf(®istry, "[[vm]]\nname = %q\ndir = %q\n", vm.Name, vm.Directory)
|
|
}
|
|
writeTestCoWFile(t, filepath.Join(c.registryDir, "vms.toml"), []byte(registry.String()))
|
|
}
|
|
|
|
func writeTestCoWFile(t *testing.T, path string, contents []byte) {
|
|
t.Helper()
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(path, contents, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func assertCoWInUse(t *testing.T, err error, clone string) {
|
|
t.Helper()
|
|
var coded *i18n.CodedError
|
|
if !errors.As(err, &coded) || coded.Code != "E_COW_BACKING_IN_USE" || coded.Params["clone"] != clone {
|
|
t.Fatalf("want E_COW_BACKING_IN_USE for %s, got %v", clone, err)
|
|
}
|
|
}
|
|
|
|
func TestParseShowAudioBackend(t *testing.T) {
|
|
cases := []struct {
|
|
line string
|
|
wantAudio bool
|
|
wantBackend string
|
|
}{
|
|
{" audio on", true, "auto"},
|
|
{" audio off", false, "auto"},
|
|
{" audio dsound", true, "dsound"},
|
|
{" audio none", true, "none"},
|
|
{" audio wav", true, "wav"},
|
|
}
|
|
for _, tc := range cases {
|
|
d := ParseShow("vm", "vm\n"+tc.line+"\n")
|
|
if d.Audio != tc.wantAudio || d.AudioBackend != tc.wantBackend {
|
|
t.Fatalf("ParseShow(%q) = (Audio=%v, Backend=%q), want (%v, %q)",
|
|
tc.line, d.Audio, d.AudioBackend, tc.wantAudio, tc.wantBackend)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestResizeAndCompactRealQemuImg(t *testing.T) {
|
|
qemuImg := os.Getenv("REIMS_GO_TEST_QEMU_IMG")
|
|
if qemuImg == "" {
|
|
t.Skip("set REIMS_GO_TEST_QEMU_IMG to test ResizeDisk and CompactDisk with real qemu-img")
|
|
}
|
|
dir := t.TempDir()
|
|
disk := filepath.Join(dir, "test.qcow2")
|
|
if out, err := exec.Command(qemuImg, "create", "-f", "qcow2", disk, "64M").CombinedOutput(); err != nil {
|
|
t.Fatalf("create qcow2: %v (%s)", err, string(out))
|
|
}
|
|
res, err := ResizeDisk(context.Background(), qemuImg, nil, disk, "+64M", nil, nil)
|
|
if err != nil {
|
|
t.Fatalf("ResizeDisk(+64M): %v", err)
|
|
}
|
|
if res.NewVirtualBytes != 128<<20 {
|
|
t.Fatalf("NewVirtualBytes = %d, want %d", res.NewVirtualBytes, 128<<20)
|
|
}
|
|
cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, CompactDiskOptions{}, nil, nil)
|
|
if err != nil {
|
|
t.Fatalf("CompactDisk: %v", err)
|
|
}
|
|
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, CompactDiskOptions{}, 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")
|
|
}
|
|
}
|
|
|
|
func TestDeleteRetriesDirectoryCleanupAfterUnregister(t *testing.T) {
|
|
origDelays := deleteDirRetryDelays
|
|
deleteDirRetryDelays = []time.Duration{
|
|
10 * time.Millisecond,
|
|
20 * time.Millisecond,
|
|
30 * time.Millisecond,
|
|
50 * time.Millisecond,
|
|
80 * time.Millisecond,
|
|
}
|
|
t.Cleanup(func() { deleteDirRetryDelays = origDelays })
|
|
|
|
t.Run("recovers_transient_lock_and_cleans_overlay", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
base := filepath.Join(root, "base", "disk.qcow2")
|
|
overlay := c.CoWImagePath("macos-tahoe2")
|
|
writeTestCoWFile(t, base, nil)
|
|
writeTestCoWFile(t, overlay, testBackingHeader(base))
|
|
vmDir := filepath.Join(root, "vms", "macos-tahoe2")
|
|
vm := testDiskVM(t, "macos-tahoe2", vmDir, overlay)
|
|
logPath := filepath.Join(vmDir, "logs", "qemu.log")
|
|
writeTestCoWFile(t, logPath, []byte("qemu log"))
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
// Hold an open handle on Windows so the initial remove_dir_all fails,
|
|
// then release it while deleteWithCoW is retrying.
|
|
held, err := os.Open(logPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
released := make(chan struct{})
|
|
go func() {
|
|
time.Sleep(25 * time.Millisecond)
|
|
_ = held.Close()
|
|
close(released)
|
|
}()
|
|
t.Cleanup(func() { <-released })
|
|
|
|
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
// Mirror upstream reims-ctl: unregister in vms.toml first, then fail removing dir.
|
|
writeTestRegistrations(t, c)
|
|
return errors.New("remove dir: sharing violation")
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("expected transient lock recovery, got %v", err)
|
|
}
|
|
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
|
|
}
|
|
if _, err := os.Stat(overlay); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("expected CoW overlay %s to be removed, stat err=%v", overlay, err)
|
|
}
|
|
})
|
|
|
|
t.Run("preserves_dir_when_still_registered", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
vmDir := filepath.Join(root, "vms", "running-vm")
|
|
disk := filepath.Join(vmDir, "disk.qcow2")
|
|
writeTestCoWFile(t, disk, nil)
|
|
vm := testDiskVM(t, "running-vm", vmDir, disk)
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
wantErr := errors.New("running-vm is running: stop it first")
|
|
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
return wantErr
|
|
})
|
|
if !errors.Is(err, wantErr) {
|
|
t.Fatalf("err = %v, want %v", err, wantErr)
|
|
}
|
|
if _, statErr := os.Stat(filepath.Join(vmDir, "vm.toml")); statErr != nil {
|
|
t.Fatalf("still-registered VM directory should remain untouched: %v", statErr)
|
|
}
|
|
})
|
|
|
|
t.Run("preserves_dir_when_used_by_other_vm", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{registryDir: filepath.Join(root, "registry")}
|
|
parentDir := filepath.Join(root, "vms", "parent")
|
|
childDir := filepath.Join(parentDir, "nested-child")
|
|
parent := testDiskVM(t, "parent", parentDir, filepath.Join(parentDir, "disk.qcow2"))
|
|
child := testDiskVM(t, "child", childDir, filepath.Join(childDir, "disk.qcow2"))
|
|
writeTestRegistrations(t, c, parent, child)
|
|
|
|
err := c.deleteWithCoW(context.Background(), parent.Name, false, nil, func() error {
|
|
t.Fatal("upstream delete must not run when another VM uses the directory")
|
|
return nil
|
|
})
|
|
if err == nil || !strings.Contains(err.Error(), "used by another registered VM") {
|
|
t.Fatalf("delete = %v, want shared directory error", err)
|
|
}
|
|
if _, statErr := os.Stat(filepath.Join(childDir, "vm.toml")); statErr != nil {
|
|
t.Fatalf("shared directory holding another VM must not be removed: %v", statErr)
|
|
}
|
|
})
|
|
|
|
t.Run("cleans_readonly_files_without_images_dir", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{registryDir: filepath.Join(root, "registry")}
|
|
vmDir := filepath.Join(root, "vms", "ro-vm")
|
|
roFile := filepath.Join(vmDir, "readonly.txt")
|
|
writeTestCoWFile(t, roFile, []byte("locked-readonly"))
|
|
vm := testDiskVM(t, "ro-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
|
|
writeTestRegistrations(t, c, vm)
|
|
if err := os.Chmod(roFile, 0o444); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
writeTestRegistrations(t, c)
|
|
return errors.New("remove dir: permission denied")
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("expected readonly cleanup to succeed, got %v", err)
|
|
}
|
|
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
|
|
}
|
|
})
|
|
|
|
t.Run("reports_persistent_lock_on_windows", func(t *testing.T) {
|
|
if runtime.GOOS != "windows" {
|
|
t.Skip("Windows sharing violation semantics only")
|
|
}
|
|
root := t.TempDir()
|
|
c := &Client{registryDir: filepath.Join(root, "registry")}
|
|
vmDir := filepath.Join(root, "vms", "stuck-vm")
|
|
logPath := filepath.Join(vmDir, "logs", "qemu.log")
|
|
writeTestCoWFile(t, logPath, []byte("still open"))
|
|
vm := testDiskVM(t, "stuck-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
held, err := os.Open(logPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer held.Close()
|
|
|
|
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
writeTestRegistrations(t, c)
|
|
return errors.New("exit status 1")
|
|
})
|
|
if err == nil || !strings.Contains(err.Error(), vmDir) {
|
|
t.Fatalf("expected error naming locked dir %s, got %v", vmDir, err)
|
|
}
|
|
})
|
|
|
|
t.Run("preserves_error_when_dir_already_removed", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
base := filepath.Join(root, "base", "disk.qcow2")
|
|
overlay := c.CoWImagePath("gone-vm")
|
|
writeTestCoWFile(t, base, nil)
|
|
writeTestCoWFile(t, overlay, testBackingHeader(base))
|
|
vmDir := filepath.Join(root, "vms", "gone-vm")
|
|
vm := testDiskVM(t, "gone-vm", vmDir, overlay)
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
wantErr := errors.New("reims-ctl exited unexpectedly after removal")
|
|
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
writeTestRegistrations(t, c)
|
|
if rmErr := os.RemoveAll(vmDir); rmErr != nil {
|
|
t.Fatal(rmErr)
|
|
}
|
|
return wantErr
|
|
})
|
|
if !errors.Is(err, wantErr) {
|
|
t.Fatalf("err = %v, want %v (must not mask error when dir was already gone)", err, wantErr)
|
|
}
|
|
if _, statErr := os.Stat(overlay); !errors.Is(statErr, os.ErrNotExist) {
|
|
t.Fatalf("expected orphaned CoW overlay %s to be cleaned, stat err=%v", overlay, statErr)
|
|
}
|
|
})
|
|
|
|
t.Run("locks_registry_and_detects_change_without_images_dir", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
regDir := filepath.Join(root, "registry")
|
|
c := &Client{registryDir: regDir}
|
|
vmDir := filepath.Join(root, "vms", "race-vm")
|
|
otherDir := filepath.Join(root, "vms", "race-vm-moved")
|
|
vm := testDiskVM(t, "race-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
|
|
moved := testDiskVM(t, "race-vm", otherDir, filepath.Join(otherDir, "disk.qcow2"))
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
unlock, err := filelock.Acquire(context.Background(), filepath.Join(regDir, ".reims-go-delete.lock"), 0)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
done <- c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
return errors.New("removeVM must not run after concurrent directory change")
|
|
})
|
|
}()
|
|
time.Sleep(40 * time.Millisecond)
|
|
writeTestRegistrations(t, c, moved)
|
|
unlock()
|
|
|
|
select {
|
|
case err := <-done:
|
|
if err == nil || !strings.Contains(err.Error(), "changed while waiting to delete it") {
|
|
t.Fatalf("err = %v, want concurrent change error", err)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("deleteWithCoW timed out waiting for registry lock")
|
|
}
|
|
})
|
|
|
|
t.Run("preserves_overlay_when_still_registered_after_nil_remove", func(t *testing.T) {
|
|
root := t.TempDir()
|
|
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
|
|
base := filepath.Join(root, "base", "disk.qcow2")
|
|
overlay := c.CoWImagePath("still-there")
|
|
writeTestCoWFile(t, base, nil)
|
|
writeTestCoWFile(t, overlay, testBackingHeader(base))
|
|
vmDir := filepath.Join(root, "vms", "still-there")
|
|
vm := testDiskVM(t, "still-there", vmDir, overlay)
|
|
writeTestRegistrations(t, c, vm)
|
|
|
|
if err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if _, statErr := os.Stat(vmDir); statErr != nil {
|
|
t.Fatalf("still-registered VM directory must not be deleted: %v", statErr)
|
|
}
|
|
if _, statErr := os.Stat(overlay); statErr != nil {
|
|
t.Fatalf("overlay for still-registered VM must not be deleted: %v", statErr)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestDeleteRealReimsCtlTransientLockAndKeepFiles(t *testing.T) {
|
|
ctlPath := os.Getenv("REIMS_GO_TEST_CTL")
|
|
if ctlPath == "" {
|
|
t.Skip("set REIMS_GO_TEST_CTL to test Client.Delete against a real reims-ctl binary")
|
|
}
|
|
rtDir := filepath.Dir(filepath.Dir(ctlPath))
|
|
dataRoot := t.TempDir()
|
|
cfg := &config.Config{DataRoot: dataRoot, Locale: i18n.EnUS}
|
|
if err := cfg.EnsureDirs(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
client := NewClient(cfg, rt.Installed{Dir: rtDir})
|
|
|
|
makeVM := func(name string) string {
|
|
t.Helper()
|
|
vmDir := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
|
|
writeTestCoWFile(t, filepath.Join(vmDir, "vm.toml"), []byte(fmt.Sprintf(
|
|
"name = %q\nprofile = \"q35-x86_64\"\ncpus = 4\nmemory_mib = 4096\ndisk = \"disk.qcow2\"\ndisk_format = \"qcow2\"\n",
|
|
name,
|
|
)))
|
|
writeTestCoWFile(t, filepath.Join(vmDir, "disk.qcow2"), []byte("dummy"))
|
|
writeTestCoWFile(t, filepath.Join(vmDir, ".reims-go-arg-ledger.json"), []byte("{}"))
|
|
writeTestCoWFile(t, filepath.Join(vmDir, "logs", "qemu.log"), []byte("boot\n"))
|
|
writeTestRegistrations(t, client, driver.VMInfo{Name: name, Directory: vmDir})
|
|
return vmDir
|
|
}
|
|
|
|
// 1. Real reims-ctl delete hitting a transient Windows sharing violation on the first file.
|
|
vmDir := makeVM("macos-tahoe2")
|
|
lockedPath := filepath.Join(vmDir, ".reims-go-arg-ledger.json")
|
|
held, err := os.Open(lockedPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
released := make(chan struct{})
|
|
go func() {
|
|
time.Sleep(120 * time.Millisecond)
|
|
_ = held.Close()
|
|
close(released)
|
|
}()
|
|
t.Cleanup(func() { <-released })
|
|
|
|
var out, errBuf bytes.Buffer
|
|
if err := client.Delete(context.Background(), "macos-tahoe2", false, &out, &errBuf); err != nil {
|
|
t.Fatalf("real reims-ctl delete failed to recover transient lock: %v (stdout=%q stderr=%q)", err, out.String(), errBuf.String())
|
|
}
|
|
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("expected %s to be deleted after retry, stat err=%v", vmDir, err)
|
|
}
|
|
if issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
|
|
t.Fatalf("recreating macos-tahoe2 should pass target dir validation after clean delete, got %+v", issue)
|
|
}
|
|
|
|
// 2. Real reims-ctl delete with keepFiles=true leaves the dir, and ValidateCreateTargetDir catches it upfront.
|
|
keptDir := makeVM("macos-tahoe-keep")
|
|
out.Reset()
|
|
errBuf.Reset()
|
|
if err := client.Delete(context.Background(), "macos-tahoe-keep", true, &out, &errBuf); err != nil {
|
|
t.Fatalf("real reims-ctl delete --keep-files failed: %v (stderr=%q)", err, errBuf.String())
|
|
}
|
|
if _, err := os.Stat(filepath.Join(keptDir, "vm.toml")); err != nil {
|
|
t.Fatalf("keep-files should preserve vm.toml: %v", err)
|
|
}
|
|
issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe-keep"}, nil, i18n.ZhCN)
|
|
if issue == nil || issue.Field != "dir" || issue.Code != "dir_not_empty" {
|
|
t.Fatalf("expected dir_not_empty after keep-files delete, got %+v", issue)
|
|
}
|
|
}
|