Merge pull request #101 from Admilkk/fix/cow-runtime-rollback
fix: 保护 CoW 父盘并在运行时重装失败时回滚
This commit is contained in:
29 files changed
+1173
-125
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Admilkk"],
|
||||
"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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -5,7 +5,7 @@ export const vmZh: Record<string, string> = {
|
||||
"attachInstaller": "挂载离线镜像",
|
||||
"brokenHint": "这台虚拟机的配置无法读取",
|
||||
"cloneConfirm": "立即派生",
|
||||
"cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响",
|
||||
"cloneDesc": "副本共享源磁盘,删除副本后才能启动源虚拟机或改写源磁盘",
|
||||
"cloneNameLabel": "新虚拟机名称",
|
||||
"cloneTitle": "从「{name}」派生 CoW 副本",
|
||||
"cloneVM": "秒级派生副本 (CoW)",
|
||||
@@ -233,7 +233,7 @@ export const vmEn: Record<string, string> = {
|
||||
"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": "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",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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) {
|
||||
@@ -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)
|
||||
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
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+39
-13
@@ -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
|
||||
@@ -123,24 +139,26 @@ 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
|
||||
}
|
||||
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
|
||||
@@ -154,17 +172,21 @@ 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)
|
||||
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
|
||||
@@ -242,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) {
|
||||
|
||||
@@ -118,11 +118,15 @@ var catalog = map[Locale]map[string]string{
|
||||
"eject": "弹出安装盘",
|
||||
"emptyVMs": "还没有虚拟机",
|
||||
"err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器",
|
||||
"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",
|
||||
@@ -398,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})",
|
||||
@@ -677,11 +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": "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",
|
||||
@@ -957,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})",
|
||||
@@ -1155,7 +1165,9 @@ 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.disk_running": {"name"},
|
||||
"err.clone.in_recovery": {"name"},
|
||||
"err.clone.no_disk": {"name"},
|
||||
"err.clone.overlay_exists": {"path"},
|
||||
|
||||
@@ -31,6 +31,14 @@ func (s *Service) Resolve(ctx context.Context, driverID, name string) (driver.Dr
|
||||
return s.router.ResolveVM(ctx, name)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if driverID != "" {
|
||||
return s.router.ResolveRefForDelete(ctx, driver.NewVMRef(driverID, name))
|
||||
}
|
||||
return s.router.ResolveVM(ctx, name)
|
||||
}
|
||||
|
||||
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,10 +130,15 @@ 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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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"}}}
|
||||
|
||||
@@ -53,16 +53,13 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -75,16 +72,22 @@ 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
|
||||
}
|
||||
overlayPath := filepath.Join(cfg.ImagesDir(), fmt.Sprintf("cow-%s.qcow2", cloneName))
|
||||
if _, err := os.Stat(overlayPath); err == nil {
|
||||
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
|
||||
}
|
||||
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))
|
||||
@@ -93,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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,18 @@ 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")
|
||||
}
|
||||
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 +114,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 +155,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 {
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func (c *Client) LockDiskForWrite(ctx context.Context, vmName, diskPath string) (func(), error) {
|
||||
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
|
||||
}
|
||||
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 findRegisteredVM(vms []driver.VMInfo, name string) driver.VMInfo {
|
||||
for _, vm := range vms {
|
||||
if vm.Name == name {
|
||||
return vm
|
||||
}
|
||||
}
|
||||
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 err
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
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) 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
|
||||
}
|
||||
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 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(diskPathKey(dir), diskPathKey(path))
|
||||
return err == nil && filepath.IsLocal(relative)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !windows
|
||||
|
||||
package reims
|
||||
|
||||
import "os"
|
||||
|
||||
func readVMMetadata(path string) ([]byte, error) {
|
||||
return os.ReadFile(path)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -26,20 +27,50 @@ type Client struct {
|
||||
Env []string
|
||||
Locale i18n.Locale
|
||||
|
||||
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 {
|
||||
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()
|
||||
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
|
||||
}
|
||||
|
||||
// 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,7 +773,10 @@ func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Wri
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.run(ctx, stdout, stderr, args...)
|
||||
if c.imagesDir == "" || o.Disk == "" {
|
||||
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 {
|
||||
@@ -754,6 +788,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 +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 {
|
||||
return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...)
|
||||
removeVM := func() error {
|
||||
return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...)
|
||||
}
|
||||
if c.imagesDir == "" {
|
||||
return removeVM()
|
||||
}
|
||||
return c.deleteWithCoW(ctx, name, keepFiles, removeVM)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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": [
|
||||
@@ -933,6 +934,18 @@
|
||||
"path"
|
||||
]
|
||||
},
|
||||
"err.clone.backing_in_use": {
|
||||
"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": [
|
||||
|
||||
@@ -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": "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",
|
||||
|
||||
@@ -144,6 +144,7 @@
|
||||
]
|
||||
},
|
||||
"runtime.empty": "尚未安装任何便携运行时。",
|
||||
"runtime.install_in_use": "停止使用此运行时的虚拟机后再试一次导入",
|
||||
"runtime.not_found": {
|
||||
"message": "未找到运行时 \"{name}\"",
|
||||
"$params": [
|
||||
@@ -933,6 +934,18 @@
|
||||
"path"
|
||||
]
|
||||
},
|
||||
"err.clone.backing_in_use": {
|
||||
"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": [
|
||||
|
||||
@@ -101,7 +101,7 @@
|
||||
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
|
||||
"diagAhciUpgradeHint": "系统盘还是 SATA,改成 NVMe 读写更快",
|
||||
"cloneTitle": "从「{name}」派生 CoW 副本",
|
||||
"cloneDesc": "用写时复制瞬间创建副本,几乎不占空间,原虚拟机不受影响",
|
||||
"cloneDesc": "副本共享源磁盘,删除副本后才能启动源虚拟机或改写源磁盘",
|
||||
"cloneNameLabel": "新虚拟机名称",
|
||||
"cloneConfirm": "立即派生",
|
||||
"typeClipboard": "粘贴剪贴板到虚拟机",
|
||||
|
||||
Reference in new issue
Block a user