Files
Reims-Go/internal/app/lifecycle_flow_test.go
T
千川白浪 e2cb665bee fix(vm): protect registered VM data during directory cleanup
model: magpie-responses/codex/gpt-6.2-sol
agent: Codex
2026-12-03 22:10:43 +08:00

321 lines
12 KiB
Go

package app
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"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 {
id string
vms []driver.VMInfo
listErr error
starts, stops, deletes, sets int
actions []string
actionResults map[string]any
}
func (d *appSecondDriver) ID() string { return d.id }
func (d *appSecondDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: d.id} }
func (d *appSecondDriver) RuntimeKind() string { return "test-runtime" }
func (d *appSecondDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (d *appSecondDriver) Capabilities() []string { return nil }
func (d *appSecondDriver) CreateSchema() *plugin.SettingsSchema { return nil }
func (d *appSecondDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
func (d *appSecondDriver) List(context.Context) ([]driver.VMInfo, error) { return d.vms, d.listErr }
func (d *appSecondDriver) Show(_ context.Context, name string) (driver.VMInfo, error) {
for _, vm := range d.vms {
if vm.Name == name {
return vm, nil
}
}
return driver.VMInfo{}, os.ErrNotExist
}
func (d *appSecondDriver) ValidateCreate(context.Context, driver.CreateRequest) []driver.ValidationIssue {
return nil
}
func (d *appSecondDriver) Create(context.Context, driver.CreateRequest, io.Writer, io.Writer) error {
return nil
}
func (d *appSecondDriver) ValidateSet(context.Context, driver.SetRequest) []driver.ValidationIssue {
return nil
}
func (d *appSecondDriver) Set(context.Context, driver.SetRequest, io.Writer, io.Writer) error {
d.sets++
return nil
}
func (d *appSecondDriver) Start(context.Context, driver.StartRequest) (driver.StartResult, error) {
d.starts++
return driver.StartResult{}, nil
}
func (d *appSecondDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error {
d.stops++
return nil
}
func (d *appSecondDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error {
d.deletes++
return nil
}
func (d *appSecondDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) {
d.actions = append(d.actions, action)
return d.actionResults[action], nil
}
func TestAppSecondDriverUserEntry(t *testing.T) {
const driverID = "test.driver.linux"
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "stopped"}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
}}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
router := driver.NewRouter(reg, nil)
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, router, nil),
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
info, err := a.GetVMInfo(driverID, "ubuntu")
if err != nil || info.DriverID != driverID {
t.Fatalf("GetVMInfo = %+v, %v", info, err)
}
vms, err := a.listVMsInternal(context.Background())
if err != nil || len(vms) != 1 || vms[0].DriverID != driverID {
t.Fatalf("list = %+v, %v", vms, err)
}
if err := a.StartVMWithDriver(driverID, "ubuntu"); err != nil {
t.Fatal(err)
}
if err := a.StopVMWithDriver(driverID, "ubuntu", false); err != nil {
t.Fatal(err)
}
if err := a.startHandedVM(driverID, "ubuntu"); err != nil {
t.Fatal(err)
}
if err := a.lifecycleSvc.Set(context.Background(), driver.NewVMRef(driverID, "ubuntu"), map[string]any{"memory": "8G"}, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
if err := a.RestartVMWithDriver(driverID, "ubuntu"); err != nil {
t.Fatal(err)
}
if err := a.DeleteVMWithDriver(driverID, "ubuntu", false); err != nil {
t.Fatal(err)
}
if drv.starts != 3 || drv.stops != 2 || drv.deletes != 1 || drv.sets != 1 {
t.Fatalf("starts=%d stops=%d deletes=%d", drv.starts, drv.stops, drv.deletes)
}
}
func TestForceQuitWithUnreachableVMDriver(t *testing.T) {
const driverID = "test.driver.unreachable"
listErr := errors.New("runtime unavailable")
drv := &appSecondDriver{id: driverID, listErr: listErr}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.unreachable", Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
a := &App{
cfg: &config.Config{DataRoot: t.TempDir()},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
}
if err := a.ForceQuitApp(); !errors.Is(err, listErr) || a.allowQuit {
t.Fatalf("force quit: err=%v, allowQuit=%v", err, a.allowQuit)
}
}
func TestAppRecoveryActionsUseLifecycle(t *testing.T) {
const driverID = driver.BuiltinReimsMacOSDriverID
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: t.TempDir(), State: "running"}}, actionResults: map[string]any{
"enter_recovery": map[string]any{"running": true, "scheduled": true},
"finish_install": map[string]any{"running": true, "installer_ejected": true, "network_enabled": true, "upgraded_nvme": true, "disk_controller_from": "ahci", "recovery_pending": true},
}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.recovery", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
}}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
if err := a.EnterRecovery("ubuntu"); err != nil {
t.Fatal(err)
}
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 1 || got[0].Field != "recovery" {
t.Fatalf("enter pending = %+v", got)
}
a.pendingChanges = map[string][]PendingChange{}
if err := a.FinishInstall("ubuntu"); err != nil {
t.Fatal(err)
}
if got := a.pendingChanges[vmKey("ubuntu")]; len(got) != 4 {
t.Fatalf("finish pending = %+v", got)
}
if len(drv.actions) != 2 || drv.actions[0] != "enter_recovery" || drv.actions[1] != "finish_install" {
t.Fatalf("actions = %v", drv.actions)
}
}
// A same-named VM in another driver must not make macOS-native flows or tray
// actions ambiguous once the owning driver is known.
func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
mac := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{Name: "dup", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(), State: "running"}}}
lin := &appSecondDriver{id: "test.driver.linux", vms: []driver.VMInfo{{Name: "dup", DriverID: "test.driver.linux", Directory: t.TempDir(), State: "running"}}}
reg := plugin.NewRegistry(nil)
for _, d := range []*appSecondDriver{mac, lin} {
d := d
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error { reg.RegisterGuestDriver(sc, d.id, d); return nil }}); err != nil {
t.Fatal(err)
}
}
reg.Reconcile(context.Background())
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
if err := a.StopVM("dup", false); err == nil {
t.Fatal("bare-name stop must stay ambiguous")
}
d, err := a.GetVMDetail("dup")
if err != nil || d.Directory != mac.vms[0].Directory {
t.Fatalf("GetVMDetail = %+v, %v", d, err)
}
if err := a.RestartVMWithDriver(driver.BuiltinReimsMacOSDriverID, "dup"); err != nil {
t.Fatal(err)
}
if mac.stops != 1 || mac.starts != 1 || lin.stops != 0 || lin.starts != 0 {
t.Fatalf("macOS restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
}
a.trayVMAction(lin.id, "dup", tray.ActRestart)
if lin.stops != 1 || lin.starts != 1 || mac.stops != 1 || mac.starts != 1 {
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
}
}
func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
vmDir := t.TempDir()
logDir := filepath.Join(vmDir, "logs")
if err := os.MkdirAll(logDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte("boot\n"), 0o644); err != nil {
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,
DriverID: driver.BuiltinReimsMacOSDriverID,
Directory: vmDir,
}, time.Now())
stopVMMonitor(vmName)
vmMonitors.mu.Lock()
_, stillRegistered := vmMonitors.entries[vmName]
vmMonitors.mu.Unlock()
if stillRegistered {
t.Fatal("monitor entry still registered after stopVMMonitor")
}
if err := os.RemoveAll(vmDir); err != nil {
t.Fatalf("removing VM dir after stopVMMonitor failed: %v", err)
}
}
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}}
leftoverDir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
if err := os.MkdirAll(leftoverDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(leftoverDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
opts := reims.CreateOpts{
Name: "macos-tahoe2",
SourceMode: "apple",
MacOS: "tahoe",
CPUs: 2,
Memory: "4G",
DiskSize: "64G",
}
hasDirIssue := func(issues []reims.ValidationIssue) bool {
for _, is := range issues {
if is.Field == "dir" && is.Code == "dir_not_empty" {
return true
}
}
return false
}
if issues := a.ValidateCreate(opts); !hasDirIssue(issues) {
t.Fatalf("expected dir_not_empty issue for leftover directory, got %+v", issues)
}
if err := os.RemoveAll(leftoverDir); err != nil {
t.Fatal(err)
}
if issues := a.ValidateCreate(opts); hasDirIssue(issues) {
t.Fatalf("unexpected dir_not_empty issue after clearing directory: %+v", issues)
}
}