fix(vm): protect registered VM data during directory cleanup
model: magpie-responses/codex/gpt-6.2-sol agent: Codex
This commit is contained in:
8 files changed
+94
-20
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["icaruszezen"],
|
||||
"zh": "修复删除虚拟机后可能因文件句柄占用残留旧目录并在重建同名虚拟机时报错的问题。删除前先等待日志监控退出并关闭桥接通道,注销后目录仍被短暂占用时自动重试清理;同时在新建向导、命令行与克隆前提前校验目标目录是否非空,避免保留文件或残留目录拖到建机阶段才失败。",
|
||||
"en": "Fix deleted VMs leaving behind their directory on Windows due to transient file locks and breaking subsequent creation of a VM with the same name. Wait for the log monitor to exit and close bridge sockets before deletion, retry directory removal if the VM was already unregistered, and validate non-empty target directories upfront in the create wizard, CLI, and clone flows."
|
||||
"authors": ["icaruszezen", "Nwflower"],
|
||||
"zh": "修复删除虚拟机后可能因文件句柄占用残留旧目录并在重建同名虚拟机时报错的问题。删除前先等待日志监控退出并关闭桥接通道,注销后目录仍被短暂占用时自动重试清理;同时在新建向导、命令行与克隆前提前校验目标目录是否非空,避免保留文件或残留目录拖到建机阶段才失败。删除和清理残留目录前检查其中是否有其他已注册虚拟机的数据。",
|
||||
"en": "Fix deleted VMs leaving behind their directory on Windows due to transient file locks and breaking subsequent creation of a VM with the same name. Wait for the log monitor to exit and close bridge sockets before deletion, retry directory removal if the VM was already unregistered, and validate non-empty target directories upfront in the create wizard, CLI, and clone flows. Check whether another registered VM uses the directory before removing it."
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/tray"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
)
|
||||
|
||||
type appSecondDriver struct {
|
||||
@@ -222,6 +223,9 @@ func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
|
||||
if _, err := vmstart.SaveVMDisplay(vmDir, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const vmName = "monitor-wait-test"
|
||||
a.startVMMonitor(vmName, driver.VMInfo{
|
||||
Name: vmName,
|
||||
@@ -241,6 +245,41 @@ func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoppingVMMonitorStaysRegisteredUntilExit(t *testing.T) {
|
||||
const name = "monitor-concurrent-stop-test"
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan struct{})
|
||||
vmMonitors.mu.Lock()
|
||||
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
|
||||
vmMonitors.mu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
vmMonitors.mu.Lock()
|
||||
delete(vmMonitors.entries, name)
|
||||
vmMonitors.mu.Unlock()
|
||||
})
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
stopVMMonitor(name)
|
||||
close(stopped)
|
||||
}()
|
||||
defer func() {
|
||||
close(done)
|
||||
<-stopped
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("stop did not cancel the monitor")
|
||||
}
|
||||
vmMonitors.mu.Lock()
|
||||
entry, ok := vmMonitors.entries[name]
|
||||
vmMonitors.mu.Unlock()
|
||||
if !ok || entry.done != done {
|
||||
t.Fatal("concurrent callers lost the monitor completion channel before exit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCreateRejectsLeftoverNonEmptyVMDir(t *testing.T) {
|
||||
dataRoot := t.TempDir()
|
||||
a := &App{cfg: &config.Config{DataRoot: dataRoot}}
|
||||
|
||||
@@ -36,7 +36,6 @@ func stopVMMonitor(name string) {
|
||||
cur, ok := vmMonitors.entries[name]
|
||||
if ok {
|
||||
cur.cancel()
|
||||
delete(vmMonitors.entries, name)
|
||||
}
|
||||
vmMonitors.mu.Unlock()
|
||||
if ok && cur.done != nil {
|
||||
@@ -47,12 +46,11 @@ func stopVMMonitor(name string) {
|
||||
func stopAllVMMonitors() {
|
||||
vmMonitors.mu.Lock()
|
||||
waiters := make([]chan struct{}, 0, len(vmMonitors.entries))
|
||||
for name, cur := range vmMonitors.entries {
|
||||
for _, cur := range vmMonitors.entries {
|
||||
cur.cancel()
|
||||
if cur.done != nil {
|
||||
waiters = append(waiters, cur.done)
|
||||
}
|
||||
delete(vmMonitors.entries, name)
|
||||
}
|
||||
vmMonitors.mu.Unlock()
|
||||
for _, done := range waiters {
|
||||
@@ -94,10 +92,10 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer func() {
|
||||
cancel()
|
||||
vmMonitors.mu.Lock()
|
||||
close(done)
|
||||
if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID {
|
||||
delete(vmMonitors.entries, name)
|
||||
}
|
||||
|
||||
@@ -115,8 +115,14 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
return err
|
||||
}
|
||||
cloneTargetOpts := reims.CreateOpts{Name: cloneName}
|
||||
_, _ = reims.CleanAbortedCreateDir(cfg.XDGDataDir(), cloneTargetOpts, nil)
|
||||
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), cloneTargetOpts, nil, cfg.Locale); issue != nil {
|
||||
registered, err := c.List(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check clone target directory: %w", err)
|
||||
}
|
||||
if _, err := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), cloneTargetOpts, registered); err != nil {
|
||||
return err
|
||||
}
|
||||
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), cloneTargetOpts, registered, cfg.Locale); issue != nil {
|
||||
return errors.New(issue.Message)
|
||||
}
|
||||
if _, err := os.Lstat(overlayPath); err == nil {
|
||||
|
||||
@@ -52,10 +52,8 @@ func IsAbortedCreateDir(dir string) bool {
|
||||
|
||||
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
|
||||
// by a previously killed `reims-ctl create` run. It only removes a directory
|
||||
// when all three safety conditions hold:
|
||||
// 1. opts.Name is not present in registered VMs,
|
||||
// 2. `.reims-ctl-creating` exists inside the directory, and
|
||||
// 3. `vm.toml` does NOT exist inside the directory.
|
||||
// when the name and directory are unregistered and the directory contains
|
||||
// `.reims-ctl-creating` without `vm.toml`.
|
||||
//
|
||||
// Returns the removed path if cleaned, or "" if nothing was touched.
|
||||
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
|
||||
@@ -69,7 +67,7 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
|
||||
}
|
||||
}
|
||||
target := ResolveCreateTargetDir(xdgDataDir, opts)
|
||||
if target == "" || !IsAbortedCreateDir(target) {
|
||||
if target == "" || !IsAbortedCreateDir(target) || containsRegisteredVMDir(target, registered) {
|
||||
return "", nil
|
||||
}
|
||||
if err := os.RemoveAll(target); err != nil {
|
||||
@@ -125,7 +123,7 @@ func ValidateCreateTargetDir(xdgDataDir string, opts CreateOpts, registered []VM
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !isRegistered && IsAbortedCreateDir(target) {
|
||||
if !isRegistered && IsAbortedCreateDir(target) && !containsRegisteredVMDir(target, registered) {
|
||||
return nil
|
||||
}
|
||||
msgKey := "validate.default_dir_not_empty"
|
||||
@@ -140,6 +138,16 @@ func ValidateCreateTargetDir(xdgDataDir string, opts CreateOpts, registered []VM
|
||||
}
|
||||
}
|
||||
|
||||
func containsRegisteredVMDir(target string, registered []VMListItem) bool {
|
||||
absTarget := absoluteDiskPath(target)
|
||||
for _, vm := range registered {
|
||||
if vm.Dir != "" && (pathInDirectory(target, vm.Dir) || pathInDirectory(absTarget, absoluteDiskPath(vm.Dir))) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
|
||||
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
|
||||
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
|
||||
|
||||
@@ -342,6 +342,27 @@ func TestCleanAbortedCreateDir(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbortedCreatePreservesRegisteredVMInTarget(t *testing.T) {
|
||||
target := filepath.Join(t.TempDir(), "unfinished")
|
||||
child := filepath.Join(target, "existing")
|
||||
if err := os.MkdirAll(child, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{filepath.Join(target, creatingMarker), filepath.Join(child, "vm.toml")} {
|
||||
if err := os.WriteFile(path, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
opts := CreateOpts{Name: "new-vm", Dir: target}
|
||||
registered := []VMListItem{{Name: "existing", Dir: child}}
|
||||
if removed, err := CleanAbortedCreateDir("", opts, registered); err != nil || removed != "" {
|
||||
t.Fatalf("cleanup = %q, %v, want registered VM preserved", removed, err)
|
||||
}
|
||||
if issue := ValidateCreateTargetDir("", opts, registered, i18n.EnUS); issue == nil || issue.Code != "dir_not_empty" {
|
||||
t.Fatalf("validation = %+v, want directory conflict", issue)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWHPXNestedVirtCompat(t *testing.T) {
|
||||
sampleErr := "2026-11-28T13:04:47Z qemu: -accel whpx: WHPX: Failed to enable nested virtualization, hr=80370302\n"
|
||||
if !IsWHPXNestedVirtError(sampleErr) {
|
||||
|
||||
@@ -347,6 +347,9 @@ func (c *Client) deleteVMWithCoW(ctx context.Context, name string, keepFiles boo
|
||||
}
|
||||
}
|
||||
|
||||
if hadConfig && c.dirUsedByOtherVM(vms, name, vm.Directory) {
|
||||
return fmt.Errorf("VM directory %s is used by another registered VM", vm.Directory)
|
||||
}
|
||||
removeErr := removeVM()
|
||||
// Upstream `reims-ctl delete` writes vms.toml before calling remove_dir_all
|
||||
// without retries (reims-vgpu 2df30ff cli.rs:1049-1060). On Windows, a brief
|
||||
|
||||
@@ -509,13 +509,12 @@ func TestDeleteRetriesDirectoryCleanupAfterUnregister(t *testing.T) {
|
||||
child := testDiskVM(t, "child", childDir, filepath.Join(childDir, "disk.qcow2"))
|
||||
writeTestRegistrations(t, c, parent, child)
|
||||
|
||||
wantErr := errors.New("remove failed")
|
||||
err := c.deleteWithCoW(context.Background(), parent.Name, false, func() error {
|
||||
writeTestRegistrations(t, c, child)
|
||||
return wantErr
|
||||
t.Fatal("upstream delete must not run when another VM uses the directory")
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, wantErr)
|
||||
if err == nil || !strings.Contains(err.Error(), "used by another registered VM") {
|
||||
t.Fatalf("delete = %v, want shared directory error", err)
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(childDir, "vm.toml")); statErr != nil {
|
||||
t.Fatalf("shared directory holding another VM must not be removed: %v", statErr)
|
||||
|
||||
Reference in new issue
Block a user