Files
Reims-Go/internal/app/lifecycle_flow_test.go
T
千川白浪 107a8d73e0 refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 (#200)
* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积

* fix: preserve download recovery and bound PBZX decoding

Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
2026-12-05 20:54:41 +08:00

439 lines
16 KiB
Go

package app
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"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/macosdriver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
for _, version := range []string{"current", "backup"} {
dir := folderTestDir(t, cfg.RuntimesDir(), version)
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
}
a := &App{cfg: &cfg}
d := macosdriver.NewReimsMacOSDriver(a.runtimeConfig, macosdriver.Options{OwnerID: "test.macos"})
ref := driver.NewVMRef(d.ID(), "test")
for _, version := range []string{"current", "backup", "current"} {
saved := cfg
saved.ActiveRuntime = version
if err := config.Save("", &saved); err != nil {
t.Fatal(err)
}
want := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), version)}
prep, err := a.prep(ref.Name)
if err != nil {
t.Fatal(err)
}
c, err := a.client()
if err != nil {
t.Fatal(err)
}
if c.Binary != want.ControlPath() || prep.Client.Binary != c.Binary || a.activeQemuPath() != want.QemuPath() {
t.Fatalf("%s: native clients or bridge selected the wrong runtime", version)
}
// Only manifests are installed. The attempted control executable
// identifies which runtime the same driver used for each new request.
_, startErr := d.Start(t.Context(), driver.StartRequest{Ref: ref})
_, resumeErr := d.Resume(t.Context(), driver.ResumeRequest{Ref: ref})
for _, err := range []error{startErr, resumeErr} {
if err == nil || !strings.Contains(err.Error(), want.ControlPath()) {
t.Fatalf("expected a launch attempt with %q, got %v", want.ControlPath(), err)
}
}
}
}
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.StartVM(driverID, "ubuntu"); err != nil {
t.Fatal(err)
}
if err := a.StopVM(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.RestartVM(driverID, "ubuntu"); err != nil {
t.Fatal(err)
}
if err := a.DeleteVM(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.RestartVM(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 TestStopVMMonitorRespectsTimeoutWhenStuck(t *testing.T) {
origTimeout := vmMonitorStopTimeout
vmMonitorStopTimeout = 30 * time.Millisecond
t.Cleanup(func() { vmMonitorStopTimeout = origTimeout })
const name = "monitor-stuck-timeout-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()
close(done)
})
finished := make(chan struct{})
go func() {
stopVMMonitor(name)
close(finished)
}()
select {
case <-finished:
case <-time.After(time.Second):
t.Fatal("stopVMMonitor hung indefinitely when monitor goroutine did not exit")
}
if ctx.Err() == nil {
t.Fatal("stopVMMonitor did not cancel the monitor context")
}
allFinished := make(chan struct{})
go func() {
stopAllVMMonitors()
close(allFinished)
}()
select {
case <-allFinished:
case <-time.After(time.Second):
t.Fatal("stopAllVMMonitors hung indefinitely when monitor goroutine did not exit")
}
}
func TestValidateCreateProtectsDirectoryOfAnotherDriver(t *testing.T) {
const driverID = "test.driver.linux"
target := t.TempDir()
child := filepath.Join(target, "ubuntu")
if err := os.Mkdir(child, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(target, ".reims-ctl-creating"), nil, 0o600); err != nil {
t.Fatal(err)
}
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: child}}}
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(t.Context())
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
issues := a.ValidateCreate(reims.CreateOpts{Name: "new-mac", Dir: target})
for _, issue := range issues {
if issue.Field == "dir" && issue.Code == "dir_not_empty" {
return
}
}
t.Fatalf("expected directory conflict for VM registered by another driver, got %+v", issues)
}
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)
}
}