fix: preserve force stop and recover incomplete VM suspend attempts
This commit is contained in:
1 parent
4cc4b6c02c
commit
a32fe323ab
15 files changed
+348
-48
No files matched your search
+1
-1
@@ -1512,7 +1512,7 @@ func (a *App) StopVM(name string, force bool) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, release, err := vmstart.LockVM(a.baseCtx(), c, name)
|
||||
release, err := vmstart.LockVMForStop(a.baseCtx(), c, name, force)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -39,10 +39,12 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
src, err := a.GetVMDetail(sourceName)
|
||||
src, release, err := vmstart.LockVM(ctx, c, sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
a.populateVMDetail(&src)
|
||||
if a.isVMRunning(ctx, c, sourceName, src) {
|
||||
return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -24,10 +25,11 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error)
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskResizeResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
|
||||
}
|
||||
@@ -73,10 +75,11 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) {
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return reims.DiskCompactResult{}, err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
|
||||
}
|
||||
|
||||
@@ -225,13 +225,11 @@ func (a *App) AttachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Directory == "" {
|
||||
return fmt.Errorf("VM %s has no directory", name)
|
||||
}
|
||||
defer release()
|
||||
srv, port, err := a.ensureGuestToolsBridge()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -281,10 +279,11 @@ func (a *App) DetachGuestTools(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
|
||||
ctx := context.Background()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
|
||||
@@ -80,10 +80,11 @@ func (a *App) EnterRecovery(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -126,10 +127,11 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
path := strings.TrimSpace(installerPath)
|
||||
if path == "" {
|
||||
path, err = a.pickCachedRecoveryInstaller()
|
||||
@@ -232,10 +234,11 @@ func (a *App) FinishInstall(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -325,10 +328,11 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.HasInstaller {
|
||||
return errors.New("exit recovery mode (eject installer) before switching disk controller")
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/vmstart"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -78,10 +79,11 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error {
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
ctx := a.baseCtx()
|
||||
|
||||
d, err := a.GetVMDetail(name)
|
||||
d, release, err := vmstart.LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if a.isVMRunning(ctx, c, name, d) {
|
||||
return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver/reims"
|
||||
@@ -109,10 +110,20 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
|
||||
defer end()
|
||||
|
||||
a.mu.Lock()
|
||||
root, mgr := a.cfg.DataRoot, a.pluginMgr
|
||||
root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(root)
|
||||
a.cancelRebootWatcher(name)
|
||||
var qmpAddr string
|
||||
if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround {
|
||||
sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name)
|
||||
if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) {
|
||||
a.cancelRebootWatcher(name)
|
||||
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove stale reboot socket: %w", err)
|
||||
}
|
||||
qmpAddr = "unix:" + sockPath
|
||||
}
|
||||
}
|
||||
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
|
||||
prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...)
|
||||
}
|
||||
@@ -129,8 +140,10 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
|
||||
}
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
|
||||
VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS,
|
||||
VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr,
|
||||
})
|
||||
} else if qmpAddr != "" {
|
||||
a.watchWin10ColdReboot(name, qmpAddr)
|
||||
}
|
||||
a.startVMMonitor(name, d, startAt)
|
||||
a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds()))
|
||||
|
||||
+5
-3
@@ -561,7 +561,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm stop <name>")
|
||||
}
|
||||
_, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
release, err := vmstart.LockVMForStop(ctx, client, args[1], false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -622,10 +622,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
if len(args) < 3 {
|
||||
return fmt.Errorf("usage: reims-go vm resize <name> <size> (e.g. 256G or +64G)")
|
||||
}
|
||||
d, err := client.Show(ctx, args[1])
|
||||
d, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "running" {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1]))
|
||||
}
|
||||
@@ -644,10 +645,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go vm compact <name>")
|
||||
}
|
||||
d, err := client.Show(ctx, args[1])
|
||||
d, release, err := vmstart.LockVM(ctx, client, args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if d.State == "running" {
|
||||
return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1]))
|
||||
}
|
||||
|
||||
+10
-6
@@ -45,13 +45,17 @@ func (c *Conn) Close() error { return c.nc.Close() }
|
||||
|
||||
type qmpReply struct {
|
||||
Return json.RawMessage `json:"return"`
|
||||
Error *struct {
|
||||
Class string `json:"class"`
|
||||
Desc string `json:"desc"`
|
||||
} `json:"error"`
|
||||
Event string `json:"event"`
|
||||
Error *commandError `json:"error"`
|
||||
Event string `json:"event"`
|
||||
}
|
||||
|
||||
type commandError struct {
|
||||
Class string `json:"class"`
|
||||
Desc string `json:"desc"`
|
||||
}
|
||||
|
||||
func (e *commandError) Error() string { return e.Class + ": " + e.Desc }
|
||||
|
||||
// Query runs one command with the default 5-second timeout and waits for its
|
||||
// JSON return value, skipping async events.
|
||||
func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
|
||||
@@ -82,7 +86,7 @@ func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration)
|
||||
continue
|
||||
}
|
||||
if r.Error != nil {
|
||||
return nil, fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc)
|
||||
return nil, fmt.Errorf("QMP %s: %w", command, r.Error)
|
||||
}
|
||||
if r.Return != nil {
|
||||
return append(json.RawMessage(nil), r.Return...), nil
|
||||
|
||||
+92
-16
@@ -46,6 +46,27 @@ type vmStatusReply struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// ErrIncompleteSuspend marks a save that QEMU rejected, failed, or cancelled.
|
||||
// The caller may remove its staging file once QEMU no longer writes to it.
|
||||
var ErrIncompleteSuspend = errors.New("incomplete suspend snapshot")
|
||||
|
||||
type migrationFailure struct {
|
||||
status string
|
||||
desc string
|
||||
}
|
||||
|
||||
func (e *migrationFailure) Error() string {
|
||||
if e.desc != "" {
|
||||
return fmt.Sprintf("migration %s: %s", e.status, e.desc)
|
||||
}
|
||||
return "migration " + e.status
|
||||
}
|
||||
|
||||
// A timeout or a dropped connection can hide a completed migration.
|
||||
type unknownSuspendOutcome struct{ error }
|
||||
|
||||
func (e *unknownSuspendOutcome) Unwrap() error { return e.error }
|
||||
|
||||
// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram +
|
||||
// multifd file snapshot to vmstatePath, waits for completion, and shuts down
|
||||
// QEMU cleanly via `quit`.
|
||||
@@ -54,7 +75,11 @@ type vmStatusReply struct {
|
||||
// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so
|
||||
// the running VM is not left frozen.
|
||||
func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error {
|
||||
c, err := Dial(ctx, "unix", SocketPath(vmDir))
|
||||
if seal == nil {
|
||||
return errors.New("suspend snapshot requires a seal callback")
|
||||
}
|
||||
addr := SocketPath(vmDir)
|
||||
c, err := Dial(ctx, "unix", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -63,7 +88,21 @@ func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress fu
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) })
|
||||
err = suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) })
|
||||
var unknown *unknownSuspendOutcome
|
||||
if errors.As(err, &unknown) {
|
||||
_ = c.Close()
|
||||
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second)
|
||||
defer cancel()
|
||||
fresh, dialErr := dialMigrateConnWithRetry(cleanup, "unix", addr, 3*time.Second)
|
||||
if dialErr == nil {
|
||||
defer fresh.Close()
|
||||
if cancelIncompleteSuspend(cleanup, fresh) {
|
||||
return fmt.Errorf("%w: %w", ErrIncompleteSuspend, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error {
|
||||
@@ -88,13 +127,21 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr
|
||||
"channels": fileChannels(vmstatePath),
|
||||
}
|
||||
if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil {
|
||||
tryResumePaused(c)
|
||||
return fmt.Errorf("start snapshot save: %w", err)
|
||||
var rejected *commandError
|
||||
if errors.As(err, &rejected) {
|
||||
tryResumePaused(c)
|
||||
return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err)
|
||||
}
|
||||
return &unknownSuspendOutcome{fmt.Errorf("start snapshot save: %w", err)}
|
||||
}
|
||||
|
||||
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
|
||||
tryResumePaused(c)
|
||||
return fmt.Errorf("save snapshot: %w", err)
|
||||
var failed *migrationFailure
|
||||
if errors.As(err, &failed) {
|
||||
tryResumePaused(c)
|
||||
return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err)
|
||||
}
|
||||
return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)}
|
||||
}
|
||||
if seal != nil {
|
||||
if err := seal(c); err != nil {
|
||||
@@ -223,6 +270,43 @@ func tryResumePaused(c *Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
func cancelIncompleteSuspend(ctx context.Context, c *Conn) bool {
|
||||
cancelSent := false
|
||||
for ctx.Err() == nil {
|
||||
info, err := queryMigration(c, 2*time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch info.Status {
|
||||
case "failed", "cancelled":
|
||||
tryResumePaused(c)
|
||||
return true
|
||||
case "completed", "none", "":
|
||||
return false
|
||||
}
|
||||
if !cancelSent {
|
||||
// Completion can race cancellation. Check the terminal status
|
||||
// even if QEMU rejects the cancel request.
|
||||
_ = c.ExecuteWithTimeout("migrate_cancel", nil, 2*time.Second)
|
||||
cancelSent = true
|
||||
}
|
||||
sleep(ctx, migratePollInterval)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func queryMigration(c *Conn, timeout time.Duration) (migrateInfo, error) {
|
||||
var info migrateInfo
|
||||
raw, err := c.QueryWithTimeout("query-migrate", nil, timeout)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
return info, fmt.Errorf("parse query-migrate: %w", err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error {
|
||||
deadline := time.Now().Add(migrateTotalTimeout)
|
||||
for {
|
||||
@@ -232,14 +316,10 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre
|
||||
if time.Now().After(deadline) {
|
||||
return errors.New("timed out waiting for migration to finish")
|
||||
}
|
||||
raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout)
|
||||
info, err := queryMigration(c, migrateCmdTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var info migrateInfo
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
return fmt.Errorf("parse query-migrate: %w", err)
|
||||
}
|
||||
prog := MigrateProgress{
|
||||
Status: info.Status,
|
||||
TotalTimeMs: info.TotalTimeMs,
|
||||
@@ -256,11 +336,7 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre
|
||||
case "completed":
|
||||
return nil
|
||||
case "failed", "cancelled":
|
||||
desc := strings.TrimSpace(info.ErrorDesc)
|
||||
if desc != "" {
|
||||
return fmt.Errorf("migration %s: %s", info.Status, desc)
|
||||
}
|
||||
return fmt.Errorf("migration %s", info.Status)
|
||||
return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)}
|
||||
}
|
||||
sleep(ctx, migratePollInterval)
|
||||
}
|
||||
|
||||
@@ -11,8 +11,84 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSuspendToFileRequiresSeal(t *testing.T) {
|
||||
if err := SuspendToFile(context.Background(), t.TempDir(), "state", nil, nil); err == nil ||
|
||||
!strings.Contains(err.Error(), "seal callback") {
|
||||
t.Fatalf("suspend without a seal callback: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuspendMigrationFailedBeforeSeal(t *testing.T) {
|
||||
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
|
||||
reply := map[string]any{}
|
||||
switch req.Execute {
|
||||
case "query-status":
|
||||
reply["status"] = "paused"
|
||||
reply["running"] = false
|
||||
case "query-migrate":
|
||||
reply["status"] = "failed"
|
||||
reply["error-desc"] = "write failed"
|
||||
case "quit":
|
||||
t.Error("QEMU would exit after an incomplete save")
|
||||
}
|
||||
return map[string]any{"return": reply}, false
|
||||
})
|
||||
ctx := context.Background()
|
||||
c, err := Dial(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
err = suspendToFileConn(ctx, c, "state.tmp", nil, func(*Conn) error {
|
||||
t.Error("an incomplete save reached seal")
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "write failed") {
|
||||
t.Fatalf("incomplete save = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelIncompleteSuspendRechecksTerminalStatus(t *testing.T) {
|
||||
for _, terminal := range []string{"cancelled", "completed"} {
|
||||
t.Run(terminal, func(t *testing.T) {
|
||||
cancelled := false
|
||||
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
|
||||
switch req.Execute {
|
||||
case "query-migrate":
|
||||
status := "active"
|
||||
if cancelled {
|
||||
status = terminal
|
||||
}
|
||||
return map[string]any{"return": map[string]any{"status": status}}, false
|
||||
case "migrate_cancel":
|
||||
cancelled = true
|
||||
case "query-status":
|
||||
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
|
||||
}
|
||||
return map[string]any{"return": map[string]any{}}, false
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
c, err := Dial(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
want := terminal == "cancelled"
|
||||
if got := cancelIncompleteSuspend(ctx, c); got != want {
|
||||
t.Fatalf("safe discard = %t, want %t", got, want)
|
||||
}
|
||||
cmds := recorded()
|
||||
if sawCont := len(cmds) > 0 && cmds[len(cmds)-1].Execute == "cont"; sawCont != want {
|
||||
t.Fatalf("unexpected rollback commands: %v", cmds)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachedFiles(t *testing.T) {
|
||||
vmDir := t.TempDir()
|
||||
disk := filepath.Join(vmDir, "disk.qcow2")
|
||||
@@ -76,7 +152,7 @@ func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) {
|
||||
}
|
||||
defer c.Close()
|
||||
sealErr := errors.New("unable to publish state")
|
||||
if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) {
|
||||
if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) || errors.Is(err, ErrIncompleteSuspend) {
|
||||
t.Fatalf("suspend error = %v", err)
|
||||
}
|
||||
cmds := recorded()
|
||||
@@ -217,7 +293,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) {
|
||||
defer c.Close()
|
||||
|
||||
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "disk full") {
|
||||
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") {
|
||||
t.Fatalf("expected disk full error, got %v", err)
|
||||
}
|
||||
var sawCont bool
|
||||
|
||||
+24
-3
@@ -89,9 +89,7 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
|
||||
}
|
||||
cleaned = append(cleaned, tok)
|
||||
}
|
||||
escaped := strings.ReplaceAll(sockPath, ",", ",,")
|
||||
escaped = strings.ReplaceAll(escaped, `\`, `/`)
|
||||
qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped)
|
||||
qmpVal := win10RebootUnixTarget(sockPath)
|
||||
if strings.ContainsAny(qmpVal, " \t") {
|
||||
qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"`
|
||||
}
|
||||
@@ -99,6 +97,29 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
|
||||
return strings.Join(cleaned, " ")
|
||||
}
|
||||
|
||||
func win10RebootUnixTarget(sockPath string) string {
|
||||
escaped := strings.ReplaceAll(sockPath, ",", ",,")
|
||||
escaped = strings.ReplaceAll(escaped, "\\", "/")
|
||||
return "unix:" + escaped + ",server=on,wait=off"
|
||||
}
|
||||
|
||||
// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured,
|
||||
// without accepting other monitors declared in extra-args.
|
||||
func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool {
|
||||
tokens := splitShellTokens(extraArgs)
|
||||
want := win10RebootUnixTarget(sockPath)
|
||||
var noReboot, socket bool
|
||||
for i, token := range tokens {
|
||||
if token == "-no-reboot" {
|
||||
noReboot = true
|
||||
}
|
||||
if token == "-qmp" && i+1 < len(tokens) && strings.Trim(tokens[i+1], "'\"") == want {
|
||||
socket = true
|
||||
}
|
||||
}
|
||||
return noReboot && socket
|
||||
}
|
||||
|
||||
func isManagedQMPTarget(arg string) bool {
|
||||
arg = strings.Trim(arg, "'\"")
|
||||
if !strings.HasSuffix(arg, ",server=on,wait=off") {
|
||||
|
||||
@@ -10,6 +10,23 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHasWin10RebootUnixArgs(t *testing.T) {
|
||||
sock := "D:\\VM data\\group,1\\reims-go-reboot.sock"
|
||||
args := MergeWin10RebootUnixArgs("-machine q35", sock)
|
||||
if !HasWin10RebootUnixArgs(args, sock) {
|
||||
t.Fatal("saved socket with escaped comma and quoted path was not recognized")
|
||||
}
|
||||
if HasWin10RebootUnixArgs(strings.ReplaceAll(args, "-no-reboot", ""), sock) {
|
||||
t.Fatal("recognized a monitor without the cold-reboot flag")
|
||||
}
|
||||
if HasWin10RebootUnixArgs(args, "D:/other/reims-go-reboot.sock") {
|
||||
t.Fatal("recognized a different monitor")
|
||||
}
|
||||
if HasWin10RebootUnixArgs("-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off", sock) {
|
||||
t.Fatal("recognized a legacy TCP monitor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeWin10RebootUnixArgs(t *testing.T) {
|
||||
got := MergeWin10RebootUnixArgs("", `D:\Data\reims-go\vms\m0\reims-go-reboot.sock`)
|
||||
want := "-no-reboot -qmp unix:D:/Data/reims-go/vms/m0/reims-go-reboot.sock,server=on,wait=off"
|
||||
|
||||
@@ -41,6 +41,30 @@ func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail,
|
||||
return cur, release, nil
|
||||
}
|
||||
|
||||
// LockMutableVM protects configuration and media updates and rejects updates
|
||||
// while a published suspend state depends on the current configuration.
|
||||
func LockMutableVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
|
||||
d, release, err := LockVM(ctx, c, name)
|
||||
if err != nil {
|
||||
return d, nil, err
|
||||
}
|
||||
if reims.HasSuspendState(d.Directory) {
|
||||
release()
|
||||
return d, nil, i18n.NewCodedError(c.Locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
|
||||
}
|
||||
return d, release, nil
|
||||
}
|
||||
|
||||
// LockVMForStop serializes graceful shutdown. Emergency shutdown is also
|
||||
// the escape path for a stalled operation that already holds the lock.
|
||||
func LockVMForStop(ctx context.Context, c *reims.Client, name string, force bool) (func(), error) {
|
||||
if force {
|
||||
return func() {}, nil
|
||||
}
|
||||
_, release, err := LockVM(ctx, c, name)
|
||||
return release, err
|
||||
}
|
||||
|
||||
func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error {
|
||||
kind := strings.ToLower(d.Kind)
|
||||
if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") {
|
||||
@@ -87,7 +111,7 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return info, err
|
||||
return info, cleanupSuspendAttempt(tmp, err)
|
||||
}
|
||||
waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
|
||||
defer cancel()
|
||||
@@ -110,6 +134,15 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func cleanupSuspendAttempt(tmp string, err error) error {
|
||||
if errors.Is(err, qmp.ErrIncompleteSuspend) {
|
||||
if removeErr := os.Remove(tmp); removeErr != nil && !os.IsNotExist(removeErr) {
|
||||
return errors.Join(err, fmt.Errorf("remove incomplete snapshot: %w", removeErr))
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ResumeSnapshot owns the incoming launch and snapshot consumption while
|
||||
// the caller holds LockVM. The original configuration must be restored
|
||||
// before guest execution can continue.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package vmstart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
)
|
||||
|
||||
func TestForceStopDoesNotWaitForVMInspectionOrLock(t *testing.T) {
|
||||
// A forced stop must not ask reims-ctl to show the VM before it can
|
||||
// invoke stop --force. A stalled owner may also be holding its lock.
|
||||
release, err := LockVMForStop(context.Background(), nil, "stalled", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
}
|
||||
|
||||
func TestCleanupSuspendAttempt(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
err error
|
||||
keep bool
|
||||
}{
|
||||
{"migration failed", fmt.Errorf("%w: disk full", qmp.ErrIncompleteSuspend), false},
|
||||
{"seal failed", errors.New("could not publish suspend metadata"), true},
|
||||
{"unknown outcome", errors.New("connection closed"), true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tmp := filepath.Join(t.TempDir(), "suspend.vmstate.tmp")
|
||||
if err := os.WriteFile(tmp, []byte("snapshot data"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cleanupSuspendAttempt(tmp, tt.err); !errors.Is(err, tt.err) {
|
||||
t.Fatalf("cleanup lost the save error: %v", err)
|
||||
}
|
||||
_, err := os.Stat(tmp)
|
||||
if tt.keep && err != nil || !tt.keep && !os.IsNotExist(err) {
|
||||
t.Fatalf("stat after cleanup = %v, want keep=%t", err, tt.keep)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user