From 51b96e05012c7387102d23949ea1de7499d060c8 Mon Sep 17 00:00:00 2001 From: Admilkk <78579687+Admilkk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:33:17 +0800 Subject: [PATCH 1/3] fix: protect CoW backing disks and roll back runtime reinstall --- changes/cow-backing-disk-protection.json | 7 ++ changes/runtime-reinstall-rollback.json | 7 ++ frontend/src/i18n/domains/vm.gen.ts | 4 +- internal/app/lifecycle_flow.go | 2 +- internal/app/macos_detail.go | 23 +---- internal/host/stats.go | 20 ++-- internal/i18n/catalog_gen.go | 3 + internal/macos/macosdriver/clone.go | 17 +++- internal/macos/macosdriver/driver.go | 2 +- internal/macos/macosdriver/storage.go | 44 +++++---- internal/macos/reims/cow_guard.go | 113 +++++++++++++++++++++++ internal/macos/reims/reims.go | 54 +++++++++-- internal/runtime/runtime.go | 71 +++++++++++++- locales/en-US/native.json | 6 ++ locales/en-US/vm.json | 2 +- locales/zh-CN/native.json | 6 ++ locales/zh-CN/vm.json | 2 +- 17 files changed, 311 insertions(+), 72 deletions(-) create mode 100644 changes/cow-backing-disk-protection.json create mode 100644 changes/runtime-reinstall-rollback.json create mode 100644 internal/macos/reims/cow_guard.go diff --git a/changes/cow-backing-disk-protection.json b/changes/cow-backing-disk-protection.json new file mode 100644 index 0000000..e84e961 --- /dev/null +++ b/changes/cow-backing-disk-protection.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Admilkk"], + "zh": "保护 CoW 副本依赖的父磁盘,解除依赖前拦截源虚拟机启动、还原和磁盘改写。", + "en": "Protect disks used by CoW clones by blocking source VM startup, snapshot restore, and disk changes until the dependency is removed." +} diff --git a/changes/runtime-reinstall-rollback.json b/changes/runtime-reinstall-rollback.json new file mode 100644 index 0000000..a5f0987 --- /dev/null +++ b/changes/runtime-reinstall-rollback.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Admilkk"], + "zh": "重新导入同版本运行时失败时保留旧运行时,避免被占用的 Windows 文件导致已安装的运行时缺失。", + "en": "Preserve the existing runtime when reimporting the same version fails, including when Windows has files open." +} diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 80d0844..8b1d5bc 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -5,7 +5,7 @@ export const vmZh: Record = { "attachInstaller": "挂载离线镜像", "brokenHint": "这台虚拟机的配置无法读取", "cloneConfirm": "立即派生", - "cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响", + "cloneDesc": "副本共享源磁盘以节省空间,解除依赖前无法启动源虚拟机或改写源磁盘", "cloneNameLabel": "新虚拟机名称", "cloneTitle": "从「{name}」派生 CoW 副本", "cloneVM": "秒级派生副本 (CoW)", @@ -233,7 +233,7 @@ export const vmEn: Record = { "attachInstaller": "Attach offline image", "brokenHint": "This VM’s configuration can’t be read", "cloneConfirm": "Create clone", - "cloneDesc": "Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched", + "cloneDesc": "The clone shares the source disk to save space. Remove that dependency before starting the source VM or changing its disk", "cloneNameLabel": "New VM name", "cloneTitle": "Derive CoW clone from “{name}”", "cloneVM": "Derive CoW clone", diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 6af32e1..db29076 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -81,7 +81,7 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) { if err != nil { return driver.VMInfo{}, err } - return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil + return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil } func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) { diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 12034e0..8830f67 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -3,33 +3,12 @@ package app import ( "context" "encoding/json" - "path/filepath" - "strings" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/vmstart" ) -func resolveVMDiskPath(d reims.VMDetail) string { - raw := strings.TrimSpace(d.Disk) - if idx := strings.Index(raw, " ("); idx > 0 { - raw = strings.TrimSpace(raw[:idx]) - } - if raw != "" { - if filepath.IsAbs(raw) { - return raw - } - if d.Directory != "" { - return filepath.Join(d.Directory, raw) - } - } - if d.Directory != "" { - return filepath.Join(d.Directory, "disk.qcow2") - } - return "" -} - // macOSDetailFromVMInfo is the native UI adapter for the built-in macOS driver. func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) { raw, err := json.Marshal(vm.DriverData) @@ -48,7 +27,7 @@ func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo { raw, _ := json.Marshal(detail) var data map[string]any _ = json.Unmarshal(raw, &data) - return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: resolveVMDiskPath(detail), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} + return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} } func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, error) { diff --git a/internal/host/stats.go b/internal/host/stats.go index 34696e6..8f0256e 100644 --- a/internal/host/stats.go +++ b/internal/host/stats.go @@ -112,7 +112,7 @@ func InspectQCOW2BackingDepth(path string) (depth int, broken bool) { } visited[norm] = struct{}{} - backing, hasBacking, err := readQCOW2BackingPath(cur) + backing, hasBacking, err := ReadQCOW2BackingPath(cur) if err != nil { if depth > 0 { return depth, true @@ -123,19 +123,17 @@ func InspectQCOW2BackingDepth(path string) (depth int, broken bool) { return depth, false } depth++ - next := backing - if !filepath.IsAbs(next) { - next = filepath.Join(filepath.Dir(cur), next) - } - if _, err := os.Stat(next); err != nil { + if _, err := os.Stat(backing); err != nil { return depth, true } - cur = next + cur = backing } return depth, true } -func readQCOW2BackingPath(path string) (string, bool, error) { +// ReadQCOW2BackingPath reads the immediate backing file from a qcow2 header. +// Relative backing paths are resolved from the directory containing the image. +func ReadQCOW2BackingPath(path string) (string, bool, error) { f, err := os.Open(path) if err != nil { return "", false, err @@ -164,7 +162,11 @@ func readQCOW2BackingPath(path string) (string, bool, error) { if _, err := f.ReadAt(buf, int64(off)); err != nil { return "", true, err } - return strings.TrimSpace(string(buf)), true, nil + backing := strings.TrimSpace(string(buf)) + if !filepath.IsAbs(backing) { + backing = filepath.Join(filepath.Dir(path), backing) + } + return backing, true, nil } // InspectVMDiskChains scans VM directories under dataRoot and reports any diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 717aa3b..25085d9 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -118,6 +118,7 @@ var catalog = map[Locale]map[string]string{ "eject": "弹出安装盘", "emptyVMs": "还没有虚拟机", "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", + "err.clone.backing_in_use": "CoW 副本「{clone}」仍依赖此磁盘,解除依赖后才能继续", "err.clone.disk_missing": "找不到原虚拟机磁盘文件:{path}", "err.clone.in_recovery": "请先在「{name}」退出恢复模式后再派生副本", "err.clone.missing_name": "请输入派生虚拟机名称", @@ -677,6 +678,7 @@ var catalog = map[Locale]map[string]string{ "eject": "Eject installer", "emptyVMs": "No virtual machines", "err.affinity.empty_mask": "Select at least 1 logical processor", + "err.clone.backing_in_use": "The CoW clone “{clone}” still depends on this disk. Remove that dependency to continue", "err.clone.disk_missing": "Source disk file not found: {path}", "err.clone.in_recovery": "Exit recovery mode on “{name}” before deriving a CoW clone", "err.clone.missing_name": "Enter a name for the cloned VM", @@ -1155,6 +1157,7 @@ var paramOrder = map[string][]string{ "doctor.pcores.detail": {"count", "mask", "cpus"}, "doctor.ram.detail": {"total", "avail"}, "doctor.runtime.active": {"commit", "dir"}, + "err.clone.backing_in_use": {"clone"}, "err.clone.disk_missing": {"path"}, "err.clone.in_recovery": {"name"}, "err.clone.no_disk": {"name"}, diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index ec1aa3e..babcc4f 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -53,6 +53,15 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s return err } defer release() + releaseImages, err := c.LockCoWImages(ctx) + if err != nil { + return err + } + defer releaseImages() + src, err = c.Show(ctx, sourceName) + if err != nil { + return err + } if vmRunning(ctx, c, sourceName, src) { return fmt.Errorf("stop %s before cloning it", sourceName) } @@ -62,7 +71,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s if src.HasInstaller { return fmt.Errorf("exit recovery mode before cloning %s", sourceName) } - srcDisk := resolveVMDiskPath(src) + srcDisk := src.DiskPath() if srcDisk == "" { return fmt.Errorf("VM %s has no disk path", sourceName) } @@ -82,9 +91,11 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s } } } - overlayPath := filepath.Join(cfg.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName)) - if _, err := os.Stat(overlayPath); err == nil { + overlayPath := c.CoWImagePath(cloneName) + if _, err := os.Lstat(overlayPath); err == nil { return fmt.Errorf("clone overlay already exists: %s", overlayPath) + } else if !os.IsNotExist(err) { + return err } env := rt.BuildChildEnv(&cfg, active) _, _ = fmt.Fprintf(stdout, "Creating CoW overlay for %s backed by %s...\n", cloneName, filepath.Base(srcDisk)) diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index 5228122..f6b12fd 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -152,7 +152,7 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo CPUs: det.CPUs, Memory: det.Memory, DiskSummary: det.Disk, - DiskPath: resolveVMDiskPath(det), + DiskPath: det.DiskPath(), Directory: det.Directory, Network: det.Network, SSHPort: det.SSHPort, diff --git a/internal/macos/macosdriver/storage.go b/internal/macos/macosdriver/storage.go index 0f4b434..9f31c73 100644 --- a/internal/macos/macosdriver/storage.go +++ b/internal/macos/macosdriver/storage.go @@ -18,25 +18,6 @@ import ( var _ driver.SnapshotDriver = (*ReimsMacOSDriver)(nil) var _ driver.DiskDriver = (*ReimsMacOSDriver)(nil) -func resolveVMDiskPath(d reims.VMDetail) string { - raw := strings.TrimSpace(d.Disk) - if idx := strings.Index(raw, " ("); idx > 0 { - raw = strings.TrimSpace(raw[:idx]) - } - if raw != "" { - if filepath.IsAbs(raw) { - return raw - } - if d.Directory != "" { - return filepath.Join(d.Directory, raw) - } - } - if d.Directory != "" { - return filepath.Join(d.Directory, "disk.qcow2") - } - return "" -} - func vmRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool { if d.State == "running" { return true @@ -60,7 +41,7 @@ func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]dr if err != nil { return nil, err } - diskPath := resolveVMDiskPath(det) + diskPath := det.DiskPath() if diskPath == "" || !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") { return nil, nil } @@ -101,13 +82,20 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna if reims.HasSuspendState(det.Directory) { return i18n.NewCodedError(c.Locale, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) } - diskPath := resolveVMDiskPath(det) + diskPath := det.DiskPath() if diskPath == "" { return fmt.Errorf("VM %s has no disk path", name) } if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") { return fmt.Errorf("restore points require a qcow2 disk") } + if operation == "restore" { + releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath) + if err != nil { + return err + } + defer releaseDisk() + } cfg := d.getConfig() return reims.RunDiskSnapshot(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), flag, clean, diskPath) } @@ -128,10 +116,15 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string, if reims.HasSuspendState(det.Directory) { return driver.DiskResizeResult{}, i18n.NewCodedError(c.Locale, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) } - diskPath := resolveVMDiskPath(det) + diskPath := det.DiskPath() if diskPath == "" { return driver.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name) } + releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath) + if err != nil { + return driver.DiskResizeResult{}, err + } + defer releaseDisk() cfg := d.getConfig() res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, newSize, stdout, stderr) if err != nil { @@ -164,10 +157,15 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri if reims.HasSuspendState(det.Directory) { return driver.DiskCompactResult{}, i18n.NewCodedError(c.Locale, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) } - diskPath := resolveVMDiskPath(det) + diskPath := det.DiskPath() if diskPath == "" { return driver.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name) } + releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath) + if err != nil { + return driver.DiskCompactResult{}, err + } + defer releaseDisk() cfg := d.getConfig() res, err := reims.CompactDiskWithOptions(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr) if err != nil { diff --git a/internal/macos/reims/cow_guard.go b/internal/macos/reims/cow_guard.go new file mode 100644 index 0000000..932b915 --- /dev/null +++ b/internal/macos/reims/cow_guard.go @@ -0,0 +1,113 @@ +package reims + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/Nwflower/reims-go/internal/filelock" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" +) + +const cowImagePrefix = "cow-" +const cowImageSuffix = ".qcow2" + +func (c *Client) CoWImagePath(name string) string { + return filepath.Join(c.imagesDir, cowImagePrefix+name+cowImageSuffix) +} + +// LockCoWImages serializes publishing a linked clone and modifying its backing +// disk across the desktop and CLI, including VMs sharing an in-place disk. +func (c *Client) LockCoWImages(ctx context.Context) (func(), error) { + if c.imagesDir == "" { + return func() {}, nil + } + if err := os.MkdirAll(c.imagesDir, 0o755); err != nil { + return nil, err + } + return filelock.Acquire(ctx, filepath.Join(c.imagesDir, ".reims-go-cow.lock"), 0) +} + +// LockDiskForWrite holds the CoW lock until the caller finishes the disk +// operation. When diskPath is empty, it looks up the VM only if clones exist. +func (c *Client) LockDiskForWrite(ctx context.Context, vmName, diskPath string) (func(), error) { + release, err := c.LockCoWImages(ctx) + if err != nil { + return nil, err + } + if err := c.checkCoWBackingDisk(ctx, vmName, diskPath); err != nil { + release() + return nil, err + } + return release, nil +} + +func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath string) error { + if c.imagesDir == "" { + return nil + } + entries, err := os.ReadDir(c.imagesDir) + if err != nil { + return fmt.Errorf("list CoW disks: %w", err) + } + var basePath string + var baseInfo os.FileInfo + for _, entry := range entries { + name := strings.ToLower(entry.Name()) + if entry.IsDir() || !strings.HasPrefix(name, cowImagePrefix) || !strings.HasSuffix(name, cowImageSuffix) { + continue + } + overlay := filepath.Join(c.imagesDir, entry.Name()) + parent, hasBacking, err := host.ReadQCOW2BackingPath(overlay) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return fmt.Errorf("inspect CoW backing file %s: %w", overlay, err) + } + if !hasBacking { + continue + } + if basePath == "" { + if diskPath == "" { + detail, err := c.Show(ctx, vmName) + if err != nil { + return err + } + diskPath = detail.DiskPath() + } + if diskPath == "" { + return fmt.Errorf("cannot determine the disk for %s", vmName) + } + basePath, err = filepath.Abs(diskPath) + if err != nil { + return err + } + baseInfo, err = os.Stat(basePath) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + parentPath, err := filepath.Abs(parent) + if err != nil { + return err + } + same := basePath == parentPath || (runtime.GOOS == "windows" && strings.EqualFold(basePath, parentPath)) + if !same && baseInfo != nil { + if parentInfo, err := os.Stat(parentPath); err == nil { + same = os.SameFile(baseInfo, parentInfo) + } + } + if same { + cloneName := entry.Name()[len(cowImagePrefix) : len(entry.Name())-len(cowImageSuffix)] + return i18n.NewCodedError(c.Locale, "E_COW_BACKING_IN_USE", "err.clone.backing_in_use", + i18n.Vars{"clone": cloneName}, fmt.Errorf("backing disk %s is used by %s", basePath, overlay)) + } + } + return nil +} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 1f15133..1b698e2 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -8,6 +8,7 @@ import ( "io" "os" "os/exec" + "path/filepath" "regexp" "strconv" "strings" @@ -26,20 +27,42 @@ type Client struct { Env []string Locale i18n.Locale + imagesDir string probeGPUs func() []host.GPUInfo statFile func(string) (os.FileInfo, error) } func NewClient(cfg *config.Config, installed rt.Installed) *Client { - var loc i18n.Locale - if cfg != nil { - loc = cfg.Locale - } - return &Client{ + c := &Client{ Binary: installed.ReimsCtlPath(), Env: rt.BuildChildEnv(cfg, installed), - Locale: loc, } + if cfg != nil { + c.Locale = cfg.Locale + if cfg.DataRoot != "" { + c.imagesDir = cfg.ImagesDir() + } + } + return c +} + +// 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]) + } + raw = config.ExpandHomePath(raw) + if filepath.IsAbs(raw) { + return raw + } + if d.Directory == "" { + return "" + } + if raw == "" { + raw = "disk.qcow2" + } + return filepath.Join(d.Directory, raw) } type VMListItem = driver.VMListItem @@ -742,6 +765,13 @@ func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Wri if err != nil { return err } + if o.Start && o.Disk != "" && o.DiskMode == "in-place" { + release, err := c.LockDiskForWrite(ctx, o.Name, o.Disk) + if err != nil { + return err + } + defer release() + } return c.run(ctx, stdout, stderr, args...) } @@ -754,6 +784,11 @@ func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) e } func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Writer) error { + release, err := c.LockDiskForWrite(ctx, name, "") + if err != nil { + return err + } + defer release() return c.run(ctx, stdout, stderr, "start", name) } @@ -803,5 +838,12 @@ func BuildDeleteArgs(name string, keepFiles bool) []string { } func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { + if !keepFiles { + release, err := c.LockDiskForWrite(ctx, name, "") + if err != nil { + return err + } + defer release() + } return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...) } diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index ca75be4..4bd0855 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -3,6 +3,7 @@ package runtime import ( "archive/tar" "archive/zip" + "context" "encoding/json" "errors" "fmt" @@ -17,6 +18,7 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/filelock" "github.com/Nwflower/reims-go/internal/host" "github.com/klauspost/compress/zstd" ) @@ -230,6 +232,14 @@ func Remove(cfg *config.Config, commit string) (*Installed, error) { if want == "" { return nil, fmt.Errorf("%w: %s", ErrNotFound, commit) } + if _, err := os.Stat(cfg.RuntimesDir()); errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("%w: %s", ErrNotFound, want) + } + release, err := lockRuntimeDirectories(cfg.RuntimesDir()) + if err != nil { + return nil, err + } + defer release() list, err := List(cfg) if err != nil { return nil, err @@ -415,9 +425,13 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err } finalDir = filepath.Join(kindDir, m.Commit) } - _ = os.RemoveAll(finalDir) - if err := os.Rename(bundleDir, finalDir); err != nil { - return nil, fmt.Errorf("activate runtime dir: %w", err) + release, err := lockRuntimeDirectories(cfg.RuntimesDir()) + if err != nil { + return nil, err + } + defer release() + if err := replaceRuntimeDirectory(bundleDir, finalDir); err != nil { + return nil, err } return &Installed{ Kind: kind, @@ -429,6 +443,57 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err }, nil } +func lockRuntimeDirectories(runtimesDir string) (func(), error) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-runtime.lock"), 0) +} + +// replaceRuntimeDirectory publishes an already verified bundle. The caller +// holds the runtime directory lock. List ignores the backup's .tmp suffix. +func replaceRuntimeDirectory(bundleDir, finalDir string) error { + backupDir := finalDir + ".replace.tmp" + _, finalErr := os.Lstat(finalDir) + hadRuntime := finalErr == nil + if !hadRuntime && !errors.Is(finalErr, os.ErrNotExist) { + return fmt.Errorf("inspect installed runtime: %w", finalErr) + } + + if _, err := os.Lstat(backupDir); err == nil { + if hadRuntime { + if err := os.RemoveAll(backupDir); err != nil { + return fmt.Errorf("clean previous runtime backup: %w", err) + } + } else { + if err := os.Rename(backupDir, finalDir); err != nil { + return fmt.Errorf("recover previous runtime from %s: %w", backupDir, err) + } + hadRuntime = true + } + } else if !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("inspect runtime backup: %w", err) + } + + if hadRuntime { + if err := os.Rename(finalDir, backupDir); err != nil { + return fmt.Errorf("%w: move installed runtime to backup: %w", ErrRuntimeInUse, err) + } + } + if err := os.Rename(bundleDir, finalDir); err != nil { + activateErr := fmt.Errorf("activate runtime dir: %w", err) + if hadRuntime { + if restoreErr := os.Rename(backupDir, finalDir); restoreErr != nil { + return errors.Join(activateErr, fmt.Errorf("restore previous runtime from %s: %w", backupDir, restoreErr)) + } + } + return activateErr + } + if hadRuntime { + _ = os.RemoveAll(backupDir) + } + return nil +} + // isSafeRuntimeSegment guards filepath.Join + os.RemoveAll against manifest // path traversal in kind or commit. func isSafeRuntimeSegment(s string) bool { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 9082381..adddd3e 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -933,6 +933,12 @@ "path" ] }, + "err.clone.backing_in_use": { + "message": "The CoW clone “{clone}” still depends on this disk. Remove that dependency to continue", + "$params": [ + "clone" + ] + }, "err.snapshot.vm_running": { "message": "Stop “{name}” before creating, restoring or deleting a restore point", "$params": [ diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 8171831..e478c50 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -101,7 +101,7 @@ "diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter", "diagAhciUpgradeHint": "The system disk still uses SATA; NVMe is faster", "cloneTitle": "Derive CoW clone from “{name}”", - "cloneDesc": "Makes an instant copy-on-write clone that takes almost no space and leaves the original untouched", + "cloneDesc": "The clone shares the source disk to save space. Remove that dependency before starting the source VM or changing its disk", "cloneNameLabel": "New VM name", "cloneConfirm": "Create clone", "typeClipboard": "Send clipboard to VM", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 4f8d516..ece5644 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -933,6 +933,12 @@ "path" ] }, + "err.clone.backing_in_use": { + "message": "CoW 副本「{clone}」仍依赖此磁盘,解除依赖后才能继续", + "$params": [ + "clone" + ] + }, "err.snapshot.vm_running": { "message": "请先停止「{name}」再创建、回滚或删除恢复点", "$params": [ diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index fa8f566..eb8468a 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -101,7 +101,7 @@ "diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿", "diagAhciUpgradeHint": "系统盘还是 SATA,改成 NVMe 读写更快", "cloneTitle": "从「{name}」派生 CoW 副本", - "cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响", + "cloneDesc": "副本共享源磁盘以节省空间,解除依赖前无法启动源虚拟机或改写源磁盘", "cloneNameLabel": "新虚拟机名称", "cloneConfirm": "立即派生", "typeClipboard": "粘贴剪贴板到虚拟机", From e12a4c73c538a96e8d1df74792cdd4686e0b227d Mon Sep 17 00:00:00 2001 From: Admilkk <78579687+Admilkk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:48:37 +0800 Subject: [PATCH 2/3] fix: allow deleting VMs with broken configuration --- internal/app/lifecycle_flow.go | 2 +- internal/lifecycle/lifecycle.go | 29 +++++++++++- internal/macos/reims/cow_guard.go | 77 ++++++++++++++++++++++++------- internal/macos/reims/reims.go | 2 +- 4 files changed, 90 insertions(+), 20 deletions(-) diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index db29076..4a8d9f9 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -277,7 +277,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { } return a.deleteVMLegacy(name, keepFiles) } - _, vm, err := svc.Resolve(context.Background(), driverID, name) + _, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) if err != nil { return err } diff --git a/internal/lifecycle/lifecycle.go b/internal/lifecycle/lifecycle.go index 87b8a1e..b9a1069 100644 --- a/internal/lifecycle/lifecycle.go +++ b/internal/lifecycle/lifecycle.go @@ -31,6 +31,33 @@ func (s *Service) Resolve(ctx context.Context, driverID, name string) (driver.Dr return s.router.ResolveVM(ctx, name) } +// ResolveForDelete also finds registered macOS VMs whose configuration cannot be loaded. +func (s *Service) ResolveForDelete(ctx context.Context, driverID, name string) (driver.Driver, driver.VMInfo, error) { + d, vm, err := s.Resolve(ctx, driverID, name) + if err == nil || driverID == "" { + return d, vm, err + } + ref := driver.NewVMRef(driverID, name) + if ref.DriverID != driver.BuiltinReimsMacOSDriverID { + return d, vm, err + } + macOS, driverErr := s.router.DriverByID(ref.DriverID) + if driverErr != nil { + return d, vm, err + } + listed, listErr := macOS.List(ctx) + if listErr != nil { + return d, vm, err + } + for _, item := range listed { + if item.Name == ref.Name && item.State == "broken" { + item.DriverID = macOS.ID() + return macOS, item, nil + } + } + return d, vm, err +} + func defaultPayload(d driver.Driver, vm driver.VMInfo) plugin.BeforeStartPayload { p := plugin.BeforeStartPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID(), RuntimeKind: d.RuntimeKind(), VMCaps: d.Capabilities(), State: vm.State} @@ -122,7 +149,7 @@ func (s *Service) ReadLogs(ctx context.Context, ref driver.VMRef, serial bool) ( } func (s *Service) Delete(ctx context.Context, ref driver.VMRef, keepFiles bool, stdout, stderr io.Writer) error { - d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name) + d, vm, err := s.ResolveForDelete(ctx, ref.DriverID, ref.Name) if err != nil { return err } diff --git a/internal/macos/reims/cow_guard.go b/internal/macos/reims/cow_guard.go index 932b915..62c98ac 100644 --- a/internal/macos/reims/cow_guard.go +++ b/internal/macos/reims/cow_guard.go @@ -36,18 +36,22 @@ func (c *Client) LockCoWImages(ctx context.Context) (func(), error) { // LockDiskForWrite holds the CoW lock until the caller finishes the disk // operation. When diskPath is empty, it looks up the VM only if clones exist. func (c *Client) LockDiskForWrite(ctx context.Context, vmName, diskPath string) (func(), error) { + return c.lockCoWBacking(ctx, vmName, diskPath, false) +} + +func (c *Client) lockCoWBacking(ctx context.Context, vmName, diskPath string, deleting bool) (func(), error) { release, err := c.LockCoWImages(ctx) if err != nil { return nil, err } - if err := c.checkCoWBackingDisk(ctx, vmName, diskPath); err != nil { + if err := c.checkCoWBackingDisk(ctx, vmName, diskPath, deleting); err != nil { release() return nil, err } return release, nil } -func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath string) error { +func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath string, deleting bool) error { if c.imagesDir == "" { return nil } @@ -56,6 +60,8 @@ func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath strin return fmt.Errorf("list CoW disks: %w", err) } var basePath string + var vmDir string + var resolvedDir string var baseInfo os.FileInfo for _, entry := range entries { name := strings.ToLower(entry.Name()) @@ -73,24 +79,33 @@ func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath strin if !hasBacking { continue } - if basePath == "" { + if basePath == "" && vmDir == "" { if diskPath == "" { - detail, err := c.Show(ctx, vmName) - if err != nil { - return err + detail, showErr := c.Show(ctx, vmName) + if showErr != nil && !deleting { + return showErr } diskPath = detail.DiskPath() } - if diskPath == "" { - return fmt.Errorf("cannot determine the disk for %s", vmName) - } - basePath, err = filepath.Abs(diskPath) - if err != nil { - return err - } - baseInfo, err = os.Stat(basePath) - if err != nil && !errors.Is(err, os.ErrNotExist) { - return err + if diskPath == "" && deleting { + // reims-ctl can remove the registered directory even if vm.toml cannot be read. + vmDir, err = c.registeredVMDirectory(ctx, vmName) + if err != nil { + return err + } + resolvedDir, _ = filepath.EvalSymlinks(vmDir) + } else { + if diskPath == "" { + return fmt.Errorf("cannot determine the disk for %s", vmName) + } + basePath, err = filepath.Abs(diskPath) + if err != nil { + return err + } + baseInfo, err = os.Stat(basePath) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } } } parentPath, err := filepath.Abs(parent) @@ -98,16 +113,44 @@ func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath strin return err } same := basePath == parentPath || (runtime.GOOS == "windows" && strings.EqualFold(basePath, parentPath)) - if !same && baseInfo != nil { + if vmDir != "" { + same = pathInDirectory(vmDir, parentPath) + if !same && resolvedDir != "" { + if resolvedParent, err := filepath.EvalSymlinks(parentPath); err == nil { + same = pathInDirectory(resolvedDir, resolvedParent) + } + } + } else if !same && baseInfo != nil { if parentInfo, err := os.Stat(parentPath); err == nil { same = os.SameFile(baseInfo, parentInfo) } } if same { cloneName := entry.Name()[len(cowImagePrefix) : len(entry.Name())-len(cowImageSuffix)] + if vmDir != "" { + basePath = parentPath + } return i18n.NewCodedError(c.Locale, "E_COW_BACKING_IN_USE", "err.clone.backing_in_use", i18n.Vars{"clone": cloneName}, fmt.Errorf("backing disk %s is used by %s", basePath, overlay)) } } return nil } + +func (c *Client) registeredVMDirectory(ctx context.Context, name string) (string, error) { + vms, err := c.List(ctx) + if err != nil { + return "", err + } + for _, vm := range vms { + if vm.Name == name && vm.Dir != "" { + return filepath.Abs(vm.Dir) + } + } + return "", fmt.Errorf("cannot determine the registered directory for %s", name) +} + +func pathInDirectory(dir, path string) bool { + relative, err := filepath.Rel(dir, path) + return err == nil && filepath.IsLocal(relative) +} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index 1b698e2..f73eecc 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -839,7 +839,7 @@ func BuildDeleteArgs(name string, keepFiles bool) []string { func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { if !keepFiles { - release, err := c.LockDiskForWrite(ctx, name, "") + release, err := c.lockCoWBacking(ctx, name, "", true) if err != nil { return err } From 6aacd1bfc554927ec2a8b7e3c8c7222e45817a29 Mon Sep 17 00:00:00 2001 From: Admilkk <78579687+Admilkk@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:48:27 +0800 Subject: [PATCH 3/3] fix: complete CoW backing protection and clone deletion --- changes/cow-backing-disk-protection.json | 4 +- frontend/src/i18n/domains/vm.gen.ts | 4 +- internal/app/app.go | 4 + internal/app/lifecycle_flow.go | 8 +- internal/cli/cli.go | 3 + internal/driver/driver.go | 38 ++ internal/host/stats.go | 34 +- internal/i18n/catalog_gen.go | 13 +- internal/lifecycle/lifecycle.go | 32 +- internal/lifecycle/lifecycle_test.go | 39 +- internal/macos/macosdriver/clone.go | 33 +- internal/macos/macosdriver/storage.go | 10 +- internal/macos/reims/cow_guard.go | 543 ++++++++++++++---- internal/macos/reims/disk_import.go | 19 +- internal/macos/reims/disk_ops_test.go | 190 +++++- internal/macos/reims/registrations.go | 29 +- internal/macos/reims/registry_read_other.go | 9 + internal/macos/reims/registry_read_windows.go | 45 ++ internal/macos/reims/reims.go | 37 +- internal/macos/reims/suspend_lock_windows.go | 2 +- internal/runtime/remove_test.go | 43 ++ locales/en-US/native.json | 9 +- locales/en-US/vm.json | 2 +- locales/zh-CN/native.json | 9 +- locales/zh-CN/vm.json | 2 +- 25 files changed, 950 insertions(+), 211 deletions(-) create mode 100644 internal/macos/reims/registry_read_other.go create mode 100644 internal/macos/reims/registry_read_windows.go diff --git a/changes/cow-backing-disk-protection.json b/changes/cow-backing-disk-protection.json index e84e961..abcf57d 100644 --- a/changes/cow-backing-disk-protection.json +++ b/changes/cow-backing-disk-protection.json @@ -2,6 +2,6 @@ "group": "fixes", "order": 0, "authors": ["Admilkk"], - "zh": "保护 CoW 副本依赖的父磁盘,解除依赖前拦截源虚拟机启动、还原和磁盘改写。", - "en": "Protect disks used by CoW clones by blocking source VM startup, snapshot restore, and disk changes until the dependency is removed." + "zh": "保护在册 CoW 副本依赖的父磁盘,删除最后一个副本后可恢复启动和磁盘修改,历史残留文件不再阻断操作。", + "en": "Protect backing disks used by registered CoW clones, and allow startup and disk changes once the last dependent VM is deleted even if older overlay files remain." } diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 8b1d5bc..c1d00da 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -5,7 +5,7 @@ export const vmZh: Record = { "attachInstaller": "挂载离线镜像", "brokenHint": "这台虚拟机的配置无法读取", "cloneConfirm": "立即派生", - "cloneDesc": "副本共享源磁盘以节省空间,解除依赖前无法启动源虚拟机或改写源磁盘", + "cloneDesc": "副本共享源磁盘,删除副本后才能启动源虚拟机或改写源磁盘", "cloneNameLabel": "新虚拟机名称", "cloneTitle": "从「{name}」派生 CoW 副本", "cloneVM": "秒级派生副本 (CoW)", @@ -233,7 +233,7 @@ export const vmEn: Record = { "attachInstaller": "Attach offline image", "brokenHint": "This VM’s configuration can’t be read", "cloneConfirm": "Create clone", - "cloneDesc": "The clone shares the source disk to save space. Remove that dependency before starting the source VM or changing its disk", + "cloneDesc": "This clone shares the source disk, so delete the clone before starting the source VM or changing its disk", "cloneNameLabel": "New VM name", "cloneTitle": "Derive CoW clone from “{name}”", "cloneVM": "Derive CoW clone", diff --git a/internal/app/app.go b/internal/app/app.go index 320e621..c3edf8d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1092,11 +1092,15 @@ func (a *App) OpenProcessorScheduling() error { func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) { a.mu.Lock() cfg := a.cfg + loc := i18n.EffectiveLocale(cfg.Locale) a.mu.Unlock() a.emitLog("runtime", "Installing portable runtime: "+archivePath) inst, err := rt.InstallFromArchive(cfg, archivePath) if err != nil { a.emitLog("runtime", "Install failed: "+err.Error()) + if errors.Is(err, rt.ErrRuntimeInUse) { + return nil, i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err) + } return nil, err } a.mu.Lock() diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 4a8d9f9..3e95424 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -277,7 +277,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { } return a.deleteVMLegacy(name, keepFiles) } - _, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) + d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) if err != nil { return err } @@ -290,7 +290,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) }) if ref.DriverID == driver.BuiltinReimsMacOSDriverID { removed, delErr := a.deleteVMWithGuestTools(ref.Name, func() error { - return svc.Delete(context.Background(), ref, keepFiles, w, w) + return svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w) }, func() (bool, error) { vms, lerr := a.listVMsInternal(context.Background()) if lerr != nil { @@ -308,7 +308,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { } err = delErr } else { - if err := svc.Delete(context.Background(), ref, keepFiles, w, w); err != nil { + if err := svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w); err != nil { return err } } @@ -328,5 +328,5 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error { } a.wakePoll() a.emitLifecycleStateChanged() - return nil + return err } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b094577..99d67af 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -292,6 +292,9 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { } inst, err := rt.InstallFromArchive(cfg, args[1]) if err != nil { + if errors.Is(err, rt.ErrRuntimeInUse) { + return i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err) + } return err } cfg.ActiveRuntime = inst.Commit diff --git a/internal/driver/driver.go b/internal/driver/driver.go index c8b8385..31a6fc3 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -479,11 +479,30 @@ func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, // ResolveRef resolves a VM within an explicit owning driver. func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, error) { + return rt.resolveRef(ctx, ref, false) +} + +// ResolveRefForDelete can resolve by inventory when a driver cannot load a +// VM's settings. The driver still decides whether deletion is allowed. +func (rt *Router) ResolveRefForDelete(ctx context.Context, ref VMRef) (Driver, VMInfo, error) { + return rt.resolveRef(ctx, ref, true) +} + +func (rt *Router) resolveRef(ctx context.Context, ref VMRef, deleting bool) (Driver, VMInfo, error) { ref = NewVMRef(ref.DriverID, ref.Name) d, err := rt.DriverByID(ref.DriverID) if err == nil { vm, showErr := d.Show(ctx, ref.Name) if showErr != nil { + if deleting { + list, err := d.List(ctx) + if err == nil { + item, found, err := matchDeletionVM(list, ref) + if err != nil || found { + return d, item, err + } + } + } return nil, VMInfo{}, showErr } vm.DriverID = d.ID() @@ -498,6 +517,25 @@ func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, er return nil, VMInfo{}, errors.Join(err, inventoryErr) } +func matchDeletionVM(list []VMInfo, ref VMRef) (VMInfo, bool, error) { + var vm VMInfo + matches := 0 + for _, item := range list { + item.DriverID = ref.DriverID + if item.Name == ref.Name { + return item, true, nil + } + if strings.EqualFold(item.Name, ref.Name) { + vm = item + matches++ + } + } + if matches > 1 { + return VMInfo{}, false, fmt.Errorf("VM name %q matches multiple VMs in driver %q; use the registered spelling", ref.Name, ref.DriverID) + } + return vm, matches == 1, nil +} + // PluginInUseChecker reports a plugin as in use while a guest driver it // declares (or registers under its own ID) owns any VM. It blocks removal. func (rt *Router) PluginInUseChecker() plugin.InUseChecker { diff --git a/internal/host/stats.go b/internal/host/stats.go index 8f0256e..0ecd556 100644 --- a/internal/host/stats.go +++ b/internal/host/stats.go @@ -87,12 +87,17 @@ func InspectDiskUsage(path string) (DiskUsage, error) { VirtualBytes: uint64(info.Size()), Format: "raw", } - if vSize, extendedL2, snapshotCount, ok := readQCOW2HeaderMeta(path); ok { + f, err := os.Open(path) + if err != nil { + return usage, nil + } + defer f.Close() + if vSize, extendedL2, snapshotCount, ok := decodeQCOW2HeaderMeta(f); ok { usage.VirtualBytes = vSize usage.ExtendedL2 = extendedL2 usage.SnapshotCount = snapshotCount usage.Format = "qcow2" - usage.BackingDepth, usage.BackingBroken = InspectQCOW2BackingDepth(path) + usage.BackingDepth, usage.BackingBroken = inspectQCOW2BackingDepth(path, f) } return usage, nil } @@ -102,6 +107,10 @@ func InspectDiskUsage(path string) (DiskUsage, error) { // standalone image, 1 for a direct CoW overlay, >=2 for nested overlays) and // whether any parent image in the chain is missing or unreadable. func InspectQCOW2BackingDepth(path string) (depth int, broken bool) { + return inspectQCOW2BackingDepth(path, nil) +} + +func inspectQCOW2BackingDepth(path string, first io.ReaderAt) (depth int, broken bool) { const maxChainWalk = 32 visited := make(map[string]struct{}) cur := path @@ -112,7 +121,14 @@ func InspectQCOW2BackingDepth(path string) (depth int, broken bool) { } visited[norm] = struct{}{} - backing, hasBacking, err := ReadQCOW2BackingPath(cur) + var backing string + var hasBacking bool + var err error + if i == 0 && first != nil { + backing, hasBacking, err = readQCOW2BackingPath(first, cur) + } else { + backing, hasBacking, err = ReadQCOW2BackingPath(cur) + } if err != nil { if depth > 0 { return depth, true @@ -139,6 +155,10 @@ func ReadQCOW2BackingPath(path string) (string, bool, error) { return "", false, err } defer f.Close() + return readQCOW2BackingPath(f, path) +} + +func readQCOW2BackingPath(f io.ReaderAt, path string) (string, bool, error) { var hdr [24]byte if _, err := f.ReadAt(hdr[:], 0); err != nil { return "", false, err @@ -152,10 +172,10 @@ func ReadQCOW2BackingPath(path string) (string, bool, error) { } off := binary.BigEndian.Uint64(hdr[8:16]) size := binary.BigEndian.Uint32(hdr[16:20]) - if off == 0 || size == 0 { + if off == 0 { return "", false, nil } - if size > 4096 { + if size == 0 || size > 4096 { return "", true, os.ErrInvalid } buf := make([]byte, size) @@ -244,6 +264,10 @@ func readQCOW2HeaderMeta(path string) (virtualSize uint64, extendedL2 bool, snap return 0, false, 0, false } defer f.Close() + return decodeQCOW2HeaderMeta(f) +} + +func decodeQCOW2HeaderMeta(f io.ReaderAt) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) { var hdr [104]byte n, err := f.ReadAt(hdr[:], 0) if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 25085d9..99eecc0 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -118,12 +118,15 @@ var catalog = map[Locale]map[string]string{ "eject": "弹出安装盘", "emptyVMs": "还没有虚拟机", "err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器", - "err.clone.backing_in_use": "CoW 副本「{clone}」仍依赖此磁盘,解除依赖后才能继续", + "err.clone.backing_in_use": "「{clone}」仍依赖此磁盘,删除该副本后才能继续", + "err.clone.disk_busy": "等待此磁盘上的操作完成后再试", "err.clone.disk_missing": "找不到原虚拟机磁盘文件:{path}", + "err.clone.disk_running": "「{name}」正在使用此磁盘,停止该虚拟机后再派生副本", "err.clone.in_recovery": "请先在「{name}」退出恢复模式后再派生副本", "err.clone.missing_name": "请输入派生虚拟机名称", "err.clone.no_disk": "原虚拟机「{name}」未配置虚拟磁盘路径", "err.clone.overlay_exists": "目标增量磁盘文件已存在:{path}", + "err.clone.registry_busy": "等待其他虚拟机操作完成后再试", "err.clone.same_name": "新虚拟机名称不能与原虚拟机相同", "err.clone.source_running": "请先关闭「{name}」再派生副本,以保证母盘数据一致", "err.commit_memory": "内存不够启动:这台虚拟机需要 {need, number, .0} GB(客体内存 {mem, number, .0} GB 加运行开销),Windows 现在最多还能分配 {avail, number, .1} GB(已算上页面文件可自动扩展的部分)。关掉一些程序再试,或在设置里把内存改为 {rec, number, .0} GB", @@ -399,6 +402,7 @@ var catalog = map[Locale]map[string]string{ "restart": "重启", "runtime.activated": "已切换激活运行时:{commit}", "runtime.empty": "尚未安装任何便携运行时。", + "runtime.install_in_use": "停止使用此运行时的虚拟机后再试一次导入", "runtime.installed": "便携运行时已安装:{commit} -> {dir}", "runtime.not_found": "未找到运行时 \"{name}\"", "runtime.remote.downloading": "下载运行时 {commit}({channel},{size})", @@ -678,12 +682,15 @@ var catalog = map[Locale]map[string]string{ "eject": "Eject installer", "emptyVMs": "No virtual machines", "err.affinity.empty_mask": "Select at least 1 logical processor", - "err.clone.backing_in_use": "The CoW clone “{clone}” still depends on this disk. Remove that dependency to continue", + "err.clone.backing_in_use": "Delete “{clone}” before continuing because it still depends on this disk", + "err.clone.disk_busy": "Wait for the operation on this disk to finish and try again", "err.clone.disk_missing": "Source disk file not found: {path}", + "err.clone.disk_running": "Stop “{name}” before cloning the disk it is using", "err.clone.in_recovery": "Exit recovery mode on “{name}” before deriving a CoW clone", "err.clone.missing_name": "Enter a name for the cloned VM", "err.clone.no_disk": "Source VM “{name}” has no disk path configured", "err.clone.overlay_exists": "CoW overlay file already exists: {path}", + "err.clone.registry_busy": "Wait for the other VM operation to finish and try again", "err.clone.same_name": "Choose a different name from the source VM", "err.clone.source_running": "Stop “{name}” before deriving a CoW clone so the backing disk is clean", "err.commit_memory": "Not enough memory to start: this VM needs {need, number, .0} GB ({mem, number, .0} GB guest memory plus overhead) and Windows can commit at most {avail, number, .1} GB more, counting how far the page file can grow. Close some programs, or set its memory to {rec, number, .0} GB", @@ -959,6 +966,7 @@ var catalog = map[Locale]map[string]string{ "restart": "Restart", "runtime.activated": "Active runtime switched to: {commit}", "runtime.empty": "No portable runtimes installed.", + "runtime.install_in_use": "Stop the VMs using this runtime and try the import again", "runtime.installed": "Portable runtime installed: {commit} -> {dir}", "runtime.not_found": "runtime \"{name}\" not found", "runtime.remote.downloading": "Downloading runtime {commit} ({channel}, {size})", @@ -1159,6 +1167,7 @@ var paramOrder = map[string][]string{ "doctor.runtime.active": {"commit", "dir"}, "err.clone.backing_in_use": {"clone"}, "err.clone.disk_missing": {"path"}, + "err.clone.disk_running": {"name"}, "err.clone.in_recovery": {"name"}, "err.clone.no_disk": {"name"}, "err.clone.overlay_exists": {"path"}, diff --git a/internal/lifecycle/lifecycle.go b/internal/lifecycle/lifecycle.go index b9a1069..5bbcf31 100644 --- a/internal/lifecycle/lifecycle.go +++ b/internal/lifecycle/lifecycle.go @@ -31,31 +31,12 @@ func (s *Service) Resolve(ctx context.Context, driverID, name string) (driver.Dr return s.router.ResolveVM(ctx, name) } -// ResolveForDelete also finds registered macOS VMs whose configuration cannot be loaded. +// ResolveForDelete also finds registered VMs whose configuration cannot be loaded. func (s *Service) ResolveForDelete(ctx context.Context, driverID, name string) (driver.Driver, driver.VMInfo, error) { - d, vm, err := s.Resolve(ctx, driverID, name) - if err == nil || driverID == "" { - return d, vm, err + if driverID != "" { + return s.router.ResolveRefForDelete(ctx, driver.NewVMRef(driverID, name)) } - ref := driver.NewVMRef(driverID, name) - if ref.DriverID != driver.BuiltinReimsMacOSDriverID { - return d, vm, err - } - macOS, driverErr := s.router.DriverByID(ref.DriverID) - if driverErr != nil { - return d, vm, err - } - listed, listErr := macOS.List(ctx) - if listErr != nil { - return d, vm, err - } - for _, item := range listed { - if item.Name == ref.Name && item.State == "broken" { - item.DriverID = macOS.ID() - return macOS, item, nil - } - } - return d, vm, err + return s.router.ResolveVM(ctx, name) } func defaultPayload(d driver.Driver, vm driver.VMInfo) plugin.BeforeStartPayload { @@ -153,6 +134,11 @@ func (s *Service) Delete(ctx context.Context, ref driver.VMRef, keepFiles bool, if err != nil { return err } + return s.DeleteResolved(ctx, d, vm, keepFiles, stdout, stderr) +} + +// DeleteResolved uses the VM resolved for the caller's deletion flow. +func (s *Service) DeleteResolved(ctx context.Context, d driver.Driver, vm driver.VMInfo, keepFiles bool, stdout, stderr io.Writer) error { if err := d.Delete(ctx, vm.Name, keepFiles, stdout, stderr); err != nil { return err } diff --git a/internal/lifecycle/lifecycle_test.go b/internal/lifecycle/lifecycle_test.go index 9cda2a6..437b90d 100644 --- a/internal/lifecycle/lifecycle_test.go +++ b/internal/lifecycle/lifecycle_test.go @@ -14,12 +14,13 @@ import ( ) type testDriver struct { - id string - vms []driver.VMInfo - starts, stops, sets int - suspends, resumes, discardSuspends int - lastResumeEnv []string - storageCalls []string + id string + vms []driver.VMInfo + starts, stops, sets int + suspends, resumes, discardSuspends int + lastResumeEnv []string + storageCalls []string + deletedName string } func (d *testDriver) ID() string { return d.id } @@ -32,7 +33,7 @@ func (d *testDriver) SettingsSchema() *plugin.SettingsSchema { return nil func (d *testDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, nil } func (d *testDriver) Show(_ context.Context, name string) (driver.VMInfo, error) { for _, vm := range d.vms { - if vm.Name == name { + if vm.Name == name && vm.State != "broken" { return vm, nil } } @@ -59,7 +60,10 @@ func (d *testDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) e d.stops++ return nil } -func (d *testDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil } +func (d *testDriver) Delete(_ context.Context, name string, _ bool, _, _ io.Writer) error { + d.deletedName = name + return nil +} func (d *testDriver) Suspend(_ context.Context, req driver.SuspendRequest) (driver.SuspendResult, error) { d.suspends++ @@ -106,6 +110,25 @@ func registerTestDriver(t *testing.T, reg *plugin.Registry, d *testDriver) { } } +func TestDeleteResolvesBrokenVMThroughItsDriverInventory(t *testing.T) { + reg := plugin.NewRegistry(nil) + drv := &testDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "Broken-VM", State: "broken"}}} + registerTestDriver(t, reg, drv) + ctx := context.Background() + reg.Reconcile(ctx) + svc := New(reg, driver.NewRouter(reg, nil), nil) + ref := driver.NewVMRef(drv.id, "broken-vm") + if err := svc.Delete(ctx, ref, false, io.Discard, io.Discard); err != nil { + t.Fatal(err) + } + if drv.deletedName != "Broken-VM" { + t.Fatalf("deletion received %q instead of the registered name", drv.deletedName) + } + if _, _, err := svc.Resolve(ctx, drv.id, "Broken-VM"); err == nil { + t.Fatal("settings resolution should still report the broken VM") + } +} + func TestSecondDriverListStartStop(t *testing.T) { reg := plugin.NewRegistry(nil) drv := &testDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "ubuntu", DriverID: "test.driver.linux", State: "stopped"}}} diff --git a/internal/macos/macosdriver/clone.go b/internal/macos/macosdriver/clone.go index babcc4f..8b02b50 100644 --- a/internal/macos/macosdriver/clone.go +++ b/internal/macos/macosdriver/clone.go @@ -53,18 +53,6 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s return err } defer release() - releaseImages, err := c.LockCoWImages(ctx) - if err != nil { - return err - } - defer releaseImages() - src, err = c.Show(ctx, sourceName) - if err != nil { - return err - } - if vmRunning(ctx, c, sourceName, src) { - return fmt.Errorf("stop %s before cloning it", sourceName) - } if reims.HasSuspendState(src.Directory) { return i18n.NewCodedError(c.Locale, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil) } @@ -84,14 +72,18 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s return fmt.Errorf("invalid clone name %q: %s", cloneName, issue.Message) } } - if existing, err := c.List(ctx); err == nil { - for _, vm := range existing { - if strings.EqualFold(vm.Name, cloneName) { - return fmt.Errorf("VM name %q is already taken", cloneName) - } - } + overlayPath, err := c.NewCoWImagePath(cloneName) + if err != nil { + return err + } + releaseDisks, err := c.LockCoWDisks(ctx, srcDisk, overlayPath) + if err != nil { + return err + } + defer releaseDisks() + if err := c.CheckCoWCloneSource(ctx, sourceName, srcDisk, cloneName); err != nil { + return err } - overlayPath := c.CoWImagePath(cloneName) if _, err := os.Lstat(overlayPath); err == nil { return fmt.Errorf("clone overlay already exists: %s", overlayPath) } else if !os.IsNotExist(err) { @@ -104,8 +96,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s } audio, network, logs, capture := src.Audio, src.Network, src.Logs, src.Capture createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &capture, Audio: &audio, Network: &network, Logs: &logs, Start: false} - if err := c.Create(ctx, createOpts, stdout, stderr); err != nil { - _ = os.Remove(overlayPath) + if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil { return err } if postSet, ok := reims.PostCreateSetOpts(createOpts); ok { diff --git a/internal/macos/macosdriver/storage.go b/internal/macos/macosdriver/storage.go index 9f31c73..a142dbc 100644 --- a/internal/macos/macosdriver/storage.go +++ b/internal/macos/macosdriver/storage.go @@ -89,13 +89,11 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna if !strings.EqualFold(filepath.Ext(diskPath), ".qcow2") { return fmt.Errorf("restore points require a qcow2 disk") } - if operation == "restore" { - releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath) - if err != nil { - return err - } - defer releaseDisk() + releaseDisk, err := c.LockDiskForWrite(ctx, name, diskPath) + if err != nil { + return err } + defer releaseDisk() cfg := d.getConfig() return reims.RunDiskSnapshot(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), flag, clean, diskPath) } diff --git a/internal/macos/reims/cow_guard.go b/internal/macos/reims/cow_guard.go index 62c98ac..661d5ed 100644 --- a/internal/macos/reims/cow_guard.go +++ b/internal/macos/reims/cow_guard.go @@ -2,13 +2,20 @@ package reims import ( "context" + "crypto/rand" + "crypto/sha256" "errors" "fmt" + "io" "os" "path/filepath" "runtime" + "slices" "strings" + "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/host" "github.com/Nwflower/reims-go/internal/i18n" @@ -16,141 +23,485 @@ import ( const cowImagePrefix = "cow-" const cowImageSuffix = ".qcow2" +const cowDiskMarker = ".reims-go-cow-disk" func (c *Client) CoWImagePath(name string) string { return filepath.Join(c.imagesDir, cowImagePrefix+name+cowImageSuffix) } -// LockCoWImages serializes publishing a linked clone and modifying its backing -// disk across the desktop and CLI, including VMs sharing an in-place disk. -func (c *Client) LockCoWImages(ctx context.Context) (func(), error) { - if c.imagesDir == "" { - return func() {}, nil +func (c *Client) NewCoWImagePath(name string) (string, error) { + path := c.CoWImagePath(name) + if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) { + return path, nil + } else if err != nil { + return "", err } + // Older builds left this path behind. Preserve it and give the new + // clone a distinct disk, since the old file may still be useful. + return c.CoWImagePath(name + "-" + rand.Text()), nil +} + +func (c *Client) lockCoWRegistry(ctx context.Context) (func(), error) { if err := os.MkdirAll(c.imagesDir, 0o755); err != nil { return nil, err } - return filelock.Acquire(ctx, filepath.Join(c.imagesDir, ".reims-go-cow.lock"), 0) + wait, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + release, err := filelock.Acquire(wait, filepath.Join(c.imagesDir, ".reims-go-cow.lock"), 0) + if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { + return nil, i18n.NewCodedError(c.Locale, "E_COW_REGISTRY_BUSY", "err.clone.registry_busy", nil, err) + } + return release, err +} + +// LockCoWDisks holds cross-process locks for specific disks. The path key +// survives file replacement, while the file ID also unifies hard-linked disks. +func (c *Client) LockCoWDisks(ctx context.Context, paths ...string) (func(), error) { + if c.imagesDir == "" { + return func() {}, nil + } + lockDir := filepath.Join(c.imagesDir, ".reims-go-disk-locks") + if err := os.MkdirAll(lockDir, 0o755); err != nil { + return nil, err + } + var keys []string + for _, path := range paths { + if path == "" { + continue + } + 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 { + return nil, err + } + keys = append(keys, fmt.Sprintf("file-%x-%x", volume, id)) + } else if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + } + + slices.Sort(keys) + var held []func() + release := func() { + for _, unlock := range slices.Backward(held) { + unlock() + } + } + wait, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + for _, key := range slices.Compact(keys) { + unlock, err := filelock.Acquire(wait, filepath.Join(lockDir, key), 0) + if err != nil { + release() + if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { + return nil, i18n.NewCodedError(c.Locale, "E_COW_DISK_BUSY", "err.clone.disk_busy", nil, err) + } + return nil, err + } + held = append(held, unlock) + } + return release, nil } -// LockDiskForWrite holds the CoW lock until the caller finishes the disk -// operation. When diskPath is empty, it looks up the VM only if clones exist. func (c *Client) LockDiskForWrite(ctx context.Context, vmName, diskPath string) (func(), error) { - return c.lockCoWBacking(ctx, vmName, diskPath, false) -} - -func (c *Client) lockCoWBacking(ctx context.Context, vmName, diskPath string, deleting bool) (func(), error) { - release, err := c.LockCoWImages(ctx) + if c.imagesDir == "" { + return func() {}, nil + } + if diskPath == "" { + vms, err := readRegisteredVMs(c.registryDir) + if err != nil { + return nil, err + } + vm := findRegisteredVM(vms, vmName) + if vm.Directory == "" { + return nil, fmt.Errorf("no VM named %s", vmName) + } + diskPath, err = vmSystemDisk(vm.Directory) + if err != nil { + return nil, err + } + } + release, err := c.LockCoWDisks(ctx, diskPath) if err != nil { return nil, err } - if err := c.checkCoWBackingDisk(ctx, vmName, diskPath, deleting); err != nil { + registry, err := c.lockCoWRegistry(ctx) + if err != nil { + release() + return nil, err + } + needle := newDiskMatch(diskPath) + vms, err := readRegisteredVMs(c.registryDir) + if err == nil { + err = c.checkCoWBackingUse(vms, "", needle.matches) + } + registry() + if err != nil { release() return nil, err } return release, nil } -func (c *Client) checkCoWBackingDisk(ctx context.Context, vmName, diskPath string, deleting bool) error { - if c.imagesDir == "" { - return nil +func findRegisteredVM(vms []driver.VMInfo, name string) driver.VMInfo { + for _, vm := range vms { + if vm.Name == name { + return vm + } } - entries, err := os.ReadDir(c.imagesDir) + return driver.VMInfo{} +} + +// CheckCoWCloneSource refreshes the inventory while the caller holds the +// source disk lock, including running VMs that opened it under another name. +func (c *Client) CheckCoWCloneSource(ctx context.Context, sourceName, diskPath, cloneName string) error { + vms, err := c.List(ctx) if err != nil { - return fmt.Errorf("list CoW disks: %w", err) + return err } - var basePath string - var vmDir string - var resolvedDir string - var baseInfo os.FileInfo - for _, entry := range entries { - name := strings.ToLower(entry.Name()) - if entry.IsDir() || !strings.HasPrefix(name, cowImagePrefix) || !strings.HasSuffix(name, cowImageSuffix) { - continue + return c.checkCoWCloneSource(vms, sourceName, diskPath, cloneName) +} + +func (c *Client) checkCoWCloneSource(vms []VMListItem, sourceName, diskPath, cloneName string) error { + sourceFound := false + needle := newDiskMatch(diskPath) + for _, vm := range vms { + if strings.EqualFold(vm.Name, cloneName) { + return fmt.Errorf("VM name %q is already taken", cloneName) } - overlay := filepath.Join(c.imagesDir, entry.Name()) - parent, hasBacking, err := host.ReadQCOW2BackingPath(overlay) - if errors.Is(err, os.ErrNotExist) { - continue - } - if err != nil { - return fmt.Errorf("inspect CoW backing file %s: %w", overlay, err) - } - if !hasBacking { - continue - } - if basePath == "" && vmDir == "" { - if diskPath == "" { - detail, showErr := c.Show(ctx, vmName) - if showErr != nil && !deleting { - return showErr - } - diskPath = detail.DiskPath() + if vm.Name == sourceName { + if current, err := vmSystemDisk(vm.Dir); err != nil || !needle.matches(current) || vm.State == "broken" { + return fmt.Errorf("source VM %s changed while waiting for its disk", sourceName) } - if diskPath == "" && deleting { - // reims-ctl can remove the registered directory even if vm.toml cannot be read. - vmDir, err = c.registeredVMDirectory(ctx, vmName) - if err != nil { - return err - } - resolvedDir, _ = filepath.EvalSymlinks(vmDir) - } else { - if diskPath == "" { - return fmt.Errorf("cannot determine the disk for %s", vmName) - } - basePath, err = filepath.Abs(diskPath) - if err != nil { - return err - } - baseInfo, err = os.Stat(basePath) - if err != nil && !errors.Is(err, os.ErrNotExist) { - return err - } + sourceFound = true + if vm.State == "running" || vm.PID != nil { + return fmt.Errorf("stop %s before cloning it", sourceName) + } + } else if vm.State == "running" || vm.PID != nil { + if needle.matches(c.registeredDisk(driver.VMInfo{Name: vm.Name, Directory: vm.Dir})) { + return i18n.NewCodedError(c.Locale, "E_COW_DISK_RUNNING", "err.clone.disk_running", i18n.Vars{"name": vm.Name}, nil) } } - parentPath, err := filepath.Abs(parent) - if err != nil { - return err + } + if !sourceFound { + return fmt.Errorf("no VM named %s", sourceName) + } + return nil +} + +// RegisterCoWClone publishes an already-created overlay. The caller holds the +// source and overlay disk locks until registration completes. +func (c *Client) RegisterCoWClone(ctx context.Context, o CreateOpts, stdout, stderr io.Writer) error { + args, err := BuildCreateArgs(o) + if err != nil { + return err + } + release, err := c.lockCoWRegistry(ctx) + if err != nil { + return err + } + defer release() + createErr := c.run(ctx, stdout, stderr, args...) + vms, inventoryErr := readRegisteredVMs(c.registryDir) + if createErr != nil { + // A failed child process may already have registered the clone. + disk := newDiskMatch(o.Disk) + if inventoryErr == nil && !c.hasOtherDiskOwner(vms, "", disk) && + c.checkCoWBackingUse(vms, "", disk.matches) == nil { + _ = os.Remove(o.Disk) } - same := basePath == parentPath || (runtime.GOOS == "windows" && strings.EqualFold(basePath, parentPath)) - if vmDir != "" { - same = pathInDirectory(vmDir, parentPath) - if !same && resolvedDir != "" { - if resolvedParent, err := filepath.EvalSymlinks(parentPath); err == nil { - same = pathInDirectory(resolvedDir, resolvedParent) - } - } - } else if !same && baseInfo != nil { - if parentInfo, err := os.Stat(parentPath); err == nil { - same = os.SameFile(baseInfo, parentInfo) - } - } - if same { - cloneName := entry.Name()[len(cowImagePrefix) : len(entry.Name())-len(cowImageSuffix)] - if vmDir != "" { - basePath = parentPath - } - return i18n.NewCodedError(c.Locale, "E_COW_BACKING_IN_USE", "err.clone.backing_in_use", - i18n.Vars{"clone": cloneName}, fmt.Errorf("backing disk %s is used by %s", basePath, overlay)) + return createErr + } + if vm := findRegisteredVM(vms, o.Name); vm.Directory != "" { + if err := os.WriteFile(filepath.Join(vm.Directory, cowDiskMarker), []byte(filepath.Base(o.Disk)), 0o644); err != nil && stderr != nil { + _, _ = fmt.Fprintf(stderr, "Warning: could not record the clone disk: %v\n", err) } } return nil } -func (c *Client) registeredVMDirectory(ctx context.Context, name string) (string, error) { - vms, err := c.List(ctx) - if err != nil { - return "", err +func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string, stdout, stderr io.Writer) error { + disk := absoluteDiskPath(config.ExpandHomePath(o.Disk)) + paths := []string{disk} + if err := visitDiskBackings(disk, func(parent string) bool { + paths = append(paths, parent) + return false + }); err != nil { + return err } - for _, vm := range vms { - if vm.Name == name && vm.Dir != "" { - return filepath.Abs(vm.Dir) + release, err := c.LockCoWDisks(ctx, paths...) + if err != nil { + return err + } + defer release() + + switch o.DiskMode { + case "in-place", "inplace", "link": + default: + // reims-ctl may copy a large image. Its source and backing files are + // locked above, so the shared registry lock need not cover the copy. + return c.run(ctx, stdout, stderr, args...) + } + registry, err := c.lockCoWRegistry(ctx) + if err != nil { + return err + } + defer registry() + if o.Start { + vms, err := readRegisteredVMs(c.registryDir) + if err != nil { + return err + } + if err := c.checkCoWBackingUse(vms, "", newDiskMatch(disk).matches); err != nil { + return err } } - return "", fmt.Errorf("cannot determine the registered directory for %s", name) + return c.run(ctx, stdout, stderr, args...) +} + +func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool, removeVM func() error) error { + if keepFiles { + registry, err := c.lockCoWRegistry(ctx) + if err != nil { + return err + } + defer registry() + return removeVM() + } + + vms, err := readRegisteredVMs(c.registryDir) + if err != nil { + return err + } + vm := findRegisteredVM(vms, name) + disk, managedPath := c.deletionDisk(vm) + release, err := c.LockCoWDisks(ctx, disk) + if err != nil { + return err + } + defer release() + + registry, err := c.lockCoWRegistry(ctx) + if err != nil { + return err + } + defer registry() + vms, err = readRegisteredVMs(c.registryDir) + if err != nil { + return err + } + current := findRegisteredVM(vms, name) + if vm.Directory != current.Directory { + return fmt.Errorf("VM %s changed while waiting to delete it", name) + } + if vm.Directory == "" { + return removeVM() + } + if currentDisk, currentManaged := c.deletionDisk(current); currentDisk != disk || currentManaged != managedPath { + return fmt.Errorf("VM %s changed its disk while waiting to delete it", name) + } + + // The upstream tool only removes a directory containing vm.toml. A + // broken (but present) config still needs a directory containment check. + _, cfgErr := os.Stat(filepath.Join(vm.Directory, "vm.toml")) + if cfgErr != nil && !errors.Is(cfgErr, os.ErrNotExist) { + return cfgErr + } + overlay := newDiskMatch(managedPath) + vmDir := absoluteDiskPath(vm.Directory) + match := func(path string) bool { + return overlay.matches(path) || (cfgErr == nil && + (pathInDirectory(vm.Directory, path) || pathInDirectory(vmDir, absoluteDiskPath(path)))) + } + if err := c.checkCoWBackingUse(vms, name, match); err != nil { + return err + } + if err := removeVM(); err != nil { + return err + } + + if managedPath != "" && !c.hasOtherDiskOwner(vms, name, overlay) { + if err := os.Remove(managedPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove clone disk %s: %w", managedPath, err) + } + } + return nil +} + +func (c *Client) deletionDisk(vm driver.VMInfo) (disk, managedPath string) { + if vm.Directory == "" { + return "", "" + } + if disk, err := vmSystemDisk(vm.Directory); err == nil { + return disk, c.managedCloneDisk(vm.Name, disk) + } + path := c.recordedCloneDisk(vm) + return path, path +} + +func (c *Client) recordedCloneDisk(vm driver.VMInfo) string { + raw, err := os.ReadFile(filepath.Join(vm.Directory, cowDiskMarker)) + if err != nil { + return "" + } + base := string(raw) + if filepath.Base(base) != base { + return "" + } + return c.managedCloneDisk(vm.Name, filepath.Join(c.imagesDir, base)) +} + +func (c *Client) managedCloneDisk(name, disk string) string { + if name == "" || disk == "" { + return "" + } + base := cowImagePrefix + name + file := filepath.Base(disk) + validName := sameDiskPath(file, base+cowImageSuffix) + if !validName && len(file) == len(base)+1+26+len(cowImageSuffix) && + sameDiskPath(file[:len(base)+1], base+"-") && + sameDiskPath(file[len(file)-len(cowImageSuffix):], cowImageSuffix) { + random := strings.ToUpper(file[len(base)+1 : len(file)-len(cowImageSuffix)]) + validName = strings.Trim(random, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") == "" + } + if !validName || !sameDiskPath(absoluteDiskPath(filepath.Dir(disk)), absoluteDiskPath(c.imagesDir)) { + return "" + } + if info, err := os.Lstat(disk); err != nil || !info.Mode().IsRegular() { + return "" + } + if _, linked, err := host.ReadQCOW2BackingPath(disk); err != nil || !linked { + return "" + } + return disk +} + +func (c *Client) registeredDisk(vm driver.VMInfo) string { + if disk, err := vmSystemDisk(vm.Directory); err == nil { + return disk + } + if disk := c.recordedCloneDisk(vm); disk != "" { + return disk + } + // Older managed clones use this name even when their vm.toml breaks. + return c.CoWImagePath(vm.Name) +} + +func (c *Client) hasOtherDiskOwner(vms []driver.VMInfo, owner string, disk diskMatch) bool { + for _, vm := range vms { + if vm.Name != owner && disk.matches(c.registeredDisk(vm)) { + return true + } + } + return false +} + +func (c *Client) checkCoWBackingUse(vms []driver.VMInfo, excludeVM string, matches func(string) bool) error { + for _, vm := range vms { + if vm.Name == excludeVM { + continue + } + disk := c.registeredDisk(vm) + var used string + if err := visitDiskBackings(disk, func(parent string) bool { + if matches(parent) { + used = parent + return true + } + return false + }); err != nil { + return err + } + if used != "" { + return i18n.NewCodedError(c.Locale, "E_COW_BACKING_IN_USE", "err.clone.backing_in_use", + i18n.Vars{"clone": vm.Name}, fmt.Errorf("backing disk %s is used by %s", used, disk)) + } + } + return nil +} + +func visitDiskBackings(disk string, visit func(string) bool) error { + seen := make(map[string]bool) + for disk != "" { + key := diskPathKey(absoluteDiskPath(disk)) + if seen[key] { + return nil + } + seen[key] = true + parent, linked, err := host.ReadQCOW2BackingPath(disk) + if errors.Is(err, os.ErrNotExist) || errors.Is(err, io.EOF) || + errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, os.ErrInvalid) { + return nil + } + if err != nil { + return fmt.Errorf("inspect CoW backing file %s: %w", disk, err) + } + if !linked || visit(parent) { + return nil + } + disk = parent + } + return nil +} + +type diskMatch struct { + path string + info os.FileInfo +} + +func newDiskMatch(path string) diskMatch { + if path == "" { + return diskMatch{} + } + path = absoluteDiskPath(path) + info, _ := os.Stat(path) + return diskMatch{path: path, info: info} +} + +func (d diskMatch) matches(path string) bool { + if d.path == "" || path == "" { + return false + } + path = absoluteDiskPath(path) + if sameDiskPath(d.path, path) { + return true + } + if d.info != nil { + if info, err := os.Stat(path); err == nil { + return os.SameFile(d.info, info) + } + } + return false +} + +func absoluteDiskPath(path string) string { + if abs, err := filepath.Abs(path); err == nil { + path = abs + } + if real, err := filepath.EvalSymlinks(path); err == nil { + path = real + } + return path +} + +func diskPathKey(path string) string { + if runtime.GOOS == "windows" { + path = strings.ToLower(path) + if path, ok := strings.CutPrefix(path, `\\?\unc\`); ok { + return `\\` + path + } + return strings.TrimPrefix(path, `\\?\`) + } + return path +} + +func sameDiskPath(a, b string) bool { + return diskPathKey(a) == diskPathKey(b) } func pathInDirectory(dir, path string) bool { - relative, err := filepath.Rel(dir, path) + relative, err := filepath.Rel(diskPathKey(dir), diskPathKey(path)) return err == nil && filepath.IsLocal(relative) } diff --git a/internal/macos/reims/disk_import.go b/internal/macos/reims/disk_import.go index e1fc61b..44ba8bf 100644 --- a/internal/macos/reims/disk_import.go +++ b/internal/macos/reims/disk_import.go @@ -2,7 +2,6 @@ package reims import ( "context" - "encoding/binary" "encoding/json" "fmt" "io" @@ -98,22 +97,10 @@ func ParseResizeTarget(currentVirtualBytes uint64, raw string) (uint64, string, 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). +// HasQCOW2BackingFile reports whether path is a linked qcow2 image. 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 + _, hasBacking, err := host.ReadQCOW2BackingPath(path) + return hasBacking, err } // QCOW2CreateOptions is the single source of truth for qcow2 image creation diff --git a/internal/macos/reims/disk_ops_test.go b/internal/macos/reims/disk_ops_test.go index e6c99ce..295e52b 100644 --- a/internal/macos/reims/disk_ops_test.go +++ b/internal/macos/reims/disk_ops_test.go @@ -3,11 +3,17 @@ package reims import ( "context" "encoding/binary" + "errors" + "fmt" "os" "os/exec" "path/filepath" "strings" "testing" + "time" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/i18n" ) func TestResolveCompactQCOW2Options(t *testing.T) { @@ -90,7 +96,7 @@ func TestHasQCOW2BackingFile(t *testing.T) { standalone := filepath.Join(dir, "standalone.qcow2") overlay := filepath.Join(dir, "overlay.qcow2") - var h [16]byte + 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 { @@ -100,8 +106,10 @@ func TestHasQCOW2BackingFile(t *testing.T) { t.Fatalf("standalone HasQCOW2BackingFile = (%v, %v), want (false, nil)", has, err) } - binary.BigEndian.PutUint64(h[8:16], 104) - if err := os.WriteFile(overlay, h[:], 0o644); err != nil { + 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 { @@ -109,6 +117,182 @@ func TestHasQCOW2BackingFile(t *testing.T) { } } +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, 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, 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, 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, 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, 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 diff --git a/internal/macos/reims/registrations.go b/internal/macos/reims/registrations.go index d7b3ace..ddeb04e 100644 --- a/internal/macos/reims/registrations.go +++ b/internal/macos/reims/registrations.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" @@ -19,8 +20,12 @@ func ListRegisteredVMs(dataRoot string) ([]driver.VMInfo, error) { if !overridden { dir = filepath.Join((&config.Config{DataRoot: dataRoot}).XDGConfigDir(), "reims-ctl") } + return readRegisteredVMs(dir) +} + +func readRegisteredVMs(dir string) ([]driver.VMInfo, error) { path := filepath.Join(dir, "vms.toml") - raw, err := os.ReadFile(path) + raw, err := readVMMetadata(path) if errors.Is(err, os.ErrNotExist) { return nil, nil } @@ -48,3 +53,25 @@ func ListRegisteredVMs(dataRoot string) ([]driver.VMInfo, error) { } return vms, nil } + +// vmSystemDisk mirrors reims-ctl's Vm::disk, which resolves relative paths +// against the registered VM directory. +func vmSystemDisk(dir string) (string, error) { + raw, err := readVMMetadata(filepath.Join(dir, "vm.toml")) + if err != nil { + return "", err + } + var vm struct { + Disk string `toml:"disk"` + } + if err := toml.Unmarshal(raw, &vm); err != nil { + return "", err + } + if strings.TrimSpace(vm.Disk) == "" { + return "", fmt.Errorf("VM config in %s has no system disk", dir) + } + if filepath.IsAbs(vm.Disk) { + return filepath.Clean(vm.Disk), nil + } + return filepath.Join(dir, vm.Disk), nil +} diff --git a/internal/macos/reims/registry_read_other.go b/internal/macos/reims/registry_read_other.go new file mode 100644 index 0000000..a46ac8f --- /dev/null +++ b/internal/macos/reims/registry_read_other.go @@ -0,0 +1,9 @@ +//go:build !windows + +package reims + +import "os" + +func readVMMetadata(path string) ([]byte, error) { + return os.ReadFile(path) +} diff --git a/internal/macos/reims/registry_read_windows.go b/internal/macos/reims/registry_read_windows.go new file mode 100644 index 0000000..f245229 --- /dev/null +++ b/internal/macos/reims/registry_read_windows.go @@ -0,0 +1,45 @@ +//go:build windows + +package reims + +import ( + "io" + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/windows" +) + +// reims-ctl publishes metadata with an atomic rename. Allow the rename +// while reading the old handle, as the Rust standard library does. +func readVMMetadata(path string) ([]byte, error) { + name, err := windowsDiskPath(path) + if err != nil { + return nil, err + } + handle, err := windows.CreateFile(name, windows.GENERIC_READ, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, + windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + file := os.NewFile(uintptr(handle), path) + defer file.Close() + return io.ReadAll(file) +} + +func windowsDiskPath(path string) (*uint16, error) { + if len(path) > 240 && !strings.HasPrefix(path, `\\?\`) && !strings.HasPrefix(path, `\\.\`) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + if unc, ok := strings.CutPrefix(abs, `\\`); ok { + path = `\\?\UNC\` + unc + } else { + path = `\\?\` + abs + } + } + return windows.UTF16PtrFromString(path) +} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index f73eecc..21dac2c 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -27,9 +27,10 @@ type Client struct { Env []string Locale i18n.Locale - imagesDir string - probeGPUs func() []host.GPUInfo - statFile func(string) (os.FileInfo, error) + imagesDir string + registryDir string + probeGPUs func() []host.GPUInfo + statFile func(string) (os.FileInfo, error) } func NewClient(cfg *config.Config, installed rt.Installed) *Client { @@ -41,6 +42,13 @@ func NewClient(cfg *config.Config, installed rt.Installed) *Client { c.Locale = cfg.Locale if cfg.DataRoot != "" { c.imagesDir = cfg.ImagesDir() + c.registryDir = filepath.Join(cfg.XDGConfigDir(), "reims-ctl") + for _, entry := range c.Env { + key, value, _ := strings.Cut(entry, "=") + if strings.EqualFold(key, "REIMS_CTL_CONFIG_DIR") { + c.registryDir = value + } + } } } return c @@ -765,14 +773,10 @@ func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Wri if err != nil { return err } - if o.Start && o.Disk != "" && o.DiskMode == "in-place" { - release, err := c.LockDiskForWrite(ctx, o.Name, o.Disk) - if err != nil { - return err - } - defer release() + if c.imagesDir == "" || o.Disk == "" { + return c.run(ctx, stdout, stderr, args...) } - return c.run(ctx, stdout, stderr, args...) + return c.createWithDisk(ctx, o, args, stdout, stderr) } func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) error { @@ -838,12 +842,11 @@ func BuildDeleteArgs(name string, keepFiles bool) []string { } func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { - if !keepFiles { - release, err := c.lockCoWBacking(ctx, name, "", true) - if err != nil { - return err - } - defer release() + removeVM := func() error { + return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...) } - return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...) + if c.imagesDir == "" { + return removeVM() + } + return c.deleteWithCoW(ctx, name, keepFiles, removeVM) } diff --git a/internal/macos/reims/suspend_lock_windows.go b/internal/macos/reims/suspend_lock_windows.go index 251f78a..e3a40bc 100644 --- a/internal/macos/reims/suspend_lock_windows.go +++ b/internal/macos/reims/suspend_lock_windows.go @@ -20,7 +20,7 @@ func lockVMFile(f *os.File) error { } func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) { - name, err := windows.UTF16PtrFromString(path) + name, err := windowsDiskPath(path) if err != nil { return 0, 0, err } diff --git a/internal/runtime/remove_test.go b/internal/runtime/remove_test.go index 02f49cd..9ef3bf1 100644 --- a/internal/runtime/remove_test.go +++ b/internal/runtime/remove_test.go @@ -102,3 +102,46 @@ func TestRemoveRuntimeInUseWindows(t *testing.T) { t.Fatalf("locked runtime should remain intact: %v", err) } } + +func TestReplaceRuntimeInUseWindows(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("Windows file locking semantics only") + } + root := t.TempDir() + finalDir, bundleDir := filepath.Join(root, "installed"), filepath.Join(root, "bundle") + writeFakeRuntime(t, finalDir, Manifest{SchemaVersion: 2, Commit: "original"}) + writeFakeRuntime(t, bundleDir, Manifest{SchemaVersion: 2, Commit: "replacement"}) + locked, err := os.Open(filepath.Join(finalDir, "bin", "reims-ctl.exe")) + if err != nil { + t.Fatal(err) + } + defer locked.Close() + + err = replaceRuntimeDirectory(bundleDir, finalDir) + if !errors.Is(err, ErrRuntimeInUse) { + t.Fatalf("want ErrRuntimeInUse, got %v", err) + } + for dir, want := range map[string]string{finalDir: "original", bundleDir: "replacement"} { + manifest, err := readManifest(filepath.Join(dir, "manifest.json")) + if err != nil || manifest.Commit != want { + t.Fatalf("runtime %s changed: %+v, %v", dir, manifest, err) + } + } +} + +func TestReplaceRuntimeRecoversBackupAndRollsBack(t *testing.T) { + root := t.TempDir() + finalDir := filepath.Join(root, "installed") + backup := finalDir + ".replace.tmp" + writeFakeRuntime(t, backup, Manifest{SchemaVersion: 2, Commit: "original"}) + if err := replaceRuntimeDirectory(filepath.Join(root, "missing-bundle"), finalDir); err == nil { + t.Fatal("activation with a missing bundle succeeded") + } + manifest, err := readManifest(filepath.Join(finalDir, "manifest.json")) + if err != nil || manifest.Commit != "original" { + t.Fatalf("previous runtime was not restored: %+v, %v", manifest, err) + } + if _, err := os.Stat(backup); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("rollback left a backup in place: %v", err) + } +} diff --git a/locales/en-US/native.json b/locales/en-US/native.json index adddd3e..e68741b 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -144,6 +144,7 @@ ] }, "runtime.empty": "No portable runtimes installed.", + "runtime.install_in_use": "Stop the VMs using this runtime and try the import again", "runtime.not_found": { "message": "runtime \"{name}\" not found", "$params": [ @@ -934,11 +935,17 @@ ] }, "err.clone.backing_in_use": { - "message": "The CoW clone “{clone}” still depends on this disk. Remove that dependency to continue", + "message": "Delete “{clone}” before continuing because it still depends on this disk", "$params": [ "clone" ] }, + "err.clone.disk_busy": "Wait for the operation on this disk to finish and try again", + "err.clone.registry_busy": "Wait for the other VM operation to finish and try again", + "err.clone.disk_running": { + "message": "Stop “{name}” before cloning the disk it is using", + "$params": ["name"] + }, "err.snapshot.vm_running": { "message": "Stop “{name}” before creating, restoring or deleting a restore point", "$params": [ diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index e478c50..d00a14b 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -101,7 +101,7 @@ "diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter", "diagAhciUpgradeHint": "The system disk still uses SATA; NVMe is faster", "cloneTitle": "Derive CoW clone from “{name}”", - "cloneDesc": "The clone shares the source disk to save space. Remove that dependency before starting the source VM or changing its disk", + "cloneDesc": "This clone shares the source disk, so delete the clone before starting the source VM or changing its disk", "cloneNameLabel": "New VM name", "cloneConfirm": "Create clone", "typeClipboard": "Send clipboard to VM", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ece5644..008a988 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -144,6 +144,7 @@ ] }, "runtime.empty": "尚未安装任何便携运行时。", + "runtime.install_in_use": "停止使用此运行时的虚拟机后再试一次导入", "runtime.not_found": { "message": "未找到运行时 \"{name}\"", "$params": [ @@ -934,11 +935,17 @@ ] }, "err.clone.backing_in_use": { - "message": "CoW 副本「{clone}」仍依赖此磁盘,解除依赖后才能继续", + "message": "「{clone}」仍依赖此磁盘,删除该副本后才能继续", "$params": [ "clone" ] }, + "err.clone.disk_busy": "等待此磁盘上的操作完成后再试", + "err.clone.registry_busy": "等待其他虚拟机操作完成后再试", + "err.clone.disk_running": { + "message": "「{name}」正在使用此磁盘,停止该虚拟机后再派生副本", + "$params": ["name"] + }, "err.snapshot.vm_running": { "message": "请先停止「{name}」再创建、回滚或删除恢复点", "$params": [ diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index eb8468a..9068040 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -101,7 +101,7 @@ "diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿", "diagAhciUpgradeHint": "系统盘还是 SATA,改成 NVMe 读写更快", "cloneTitle": "从「{name}」派生 CoW 副本", - "cloneDesc": "副本共享源磁盘以节省空间,解除依赖前无法启动源虚拟机或改写源磁盘", + "cloneDesc": "副本共享源磁盘,删除副本后才能启动源虚拟机或改写源磁盘", "cloneNameLabel": "新虚拟机名称", "cloneConfirm": "立即派生", "typeClipboard": "粘贴剪贴板到虚拟机",