fix: make Intel VM suspend and resume transactional

This commit is contained in:
YXC0915 committed 2026-12-01 08:37:30 +08:00
1 parent 2596728789
commit 4cc4b6c02c
16 files changed
+892 -422

No files matched your search

+35 -12
View File
@@ -220,7 +220,7 @@ func (a *App) shutdown(ctx context.Context) {
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
// Start, stop and delete call wakePoll so their result shows up at once.
const (
pollBusy = 2 * time.Second
pollBusy = 2 * time.Second
// Exits are caught at once by watchExits and GUI actions call wakePoll, so
// the steady tick only has to notice VMs started or removed elsewhere (CLI).
pollSteady = 10 * time.Second
@@ -682,13 +682,17 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
if err != nil {
return d, err
}
d.RecoveryMode = isRecoveryModeActive(d)
a.populateGuestToolsDetail(&d)
a.populateGuestLangDetail(&d)
a.populateSuspendDetail(&d)
a.populateVMDetail(&d)
return d, nil
}
func (a *App) populateVMDetail(d *reims.VMDetail) {
d.RecoveryMode = isRecoveryModeActive(*d)
a.populateGuestToolsDetail(d)
a.populateGuestLangDetail(d)
a.populateSuspendDetail(d)
}
func (a *App) SetLocale(raw string) error {
a.mu.Lock()
a.cfg.Locale = i18n.ParsePreference(raw)
@@ -1091,10 +1095,16 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
}
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
cur, err := a.GetVMDetail(opts.Name)
c, err := a.client()
if err != nil {
return err
}
cur, release, err := vmstart.LockVM(a.baseCtx(), c, opts.Name)
if err != nil {
return err
}
defer release()
a.populateVMDetail(&cur)
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
@@ -1102,10 +1112,6 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
c, err := a.client()
if err != nil {
return err
}
w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) })
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
@@ -1351,9 +1357,13 @@ func (a *App) StartVM(name string) error {
return err
}
c := prep.Client
curDetail, _ := c.Show(context.Background(), name)
curDetail, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) {
return a.ResumeVM(name)
return a.resumeLocked(prep, curDetail)
}
a.mu.Lock()
root := a.cfg.DataRoot
@@ -1502,6 +1512,11 @@ func (a *App) StopVM(name string, force bool) error {
if err != nil {
return err
}
_, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
@@ -1570,6 +1585,14 @@ func (a *App) EjectInstaller(name string) error {
if err != nil {
return err
}
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
if a.isVMSuspended(d) {
return i18n.NewCodedError(a.locale(), "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, "Ejecting installer from "+name+"...")
if err := c.Eject(context.Background(), name, w, w); err != nil {
+57 -230
View File
@@ -1,11 +1,7 @@
package app
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
@@ -18,8 +14,6 @@ import (
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// enrichVMListStates overlays state="suspended" onto stopped VMs that have a
// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder.
func enrichVMListStates(vms []reims.VMListItem) {
for i := range vms {
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
@@ -29,10 +23,7 @@ func enrichVMListStates(vms []reims.VMListItem) {
}
func (a *App) populateSuspendDetail(d *reims.VMDetail) {
if d == nil || d.Directory == "" {
return
}
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
d.State = "suspended"
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
d.SuspendInfo = info
@@ -44,73 +35,33 @@ func (a *App) isVMSuspended(d reims.VMDetail) bool {
return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory))
}
// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU
// state to suspend.vmstate, and cleanly exits QEMU so the host can close
// Reims-Go or reboot Windows and later resume instantaneously.
// SuspendVM saves a VM's running state and closes its QEMU process.
func (a *App) SuspendVM(name string) error {
loc := a.locale()
prep, err := a.prep(name)
if err != nil {
return err
}
if !prep.Runtime.Manifest.HasCapability("vm-suspend") {
return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
a.mu.Lock()
if tr := a.transitions[name]; tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
a.mu.Unlock()
ctx := a.baseCtx()
c := prep.Client
d, err := c.Show(ctx, name)
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
if !a.isVMRunning(ctx, c, name, d) {
return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil)
defer release()
end, err := a.beginSuspendTransition(name, "suspending")
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
if memGB, ok := reims.ParseSizeGB(d.Memory); ok {
dirRep := host.Inspect(d.Directory)
needGB := memGB + 1.0
if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB {
return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{
"need": fmt.Sprintf("%.1f", needGB),
"avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB),
}, nil)
}
}
oldPID := a.cachedVMPID(name)
a.cancelRebootWatcher(name)
stopVMMonitor(name)
defer end()
a.mu.Lock()
mgr := a.pluginMgr
gt := a.guestTools
a.transitions[name] = "suspending"
mgr, gt := a.pluginMgr, a.guestTools
a.mu.Unlock()
event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
VMName: name,
VMDir: d.Directory,
DriverID: builtin.IDDriverReimsMacOS,
})
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event)
}
a.emitStateChanged()
tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp"
_ = os.Remove(tmpPath)
a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName))
lastPct := -1
err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) {
info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) {
if p.Total > 0 {
pct := int(p.Transferred * 100 / p.Total)
if pct >= lastPct+25 || p.Status == "completed" {
@@ -120,221 +71,84 @@ func (a *App) SuspendVM(name string) error {
}
})
if err != nil {
_ = os.Remove(tmpPath)
a.clearTransition(name)
a.emitLog(name, "Suspend error: "+err.Error())
a.wakePoll()
a.emitStateChanged()
return err
}
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
st, statErr := os.Stat(tmpPath)
if statErr != nil || st.Size() <= 0 {
_ = os.Remove(tmpPath)
a.clearTransition(name)
a.wakePoll()
a.emitStateChanged()
if statErr != nil {
return fmt.Errorf("suspend snapshot missing after save: %w", statErr)
}
return fmt.Errorf("suspend snapshot is empty after save")
}
finalPath := reims.SuspendStatePath(d.Directory)
_ = os.Remove(finalPath)
if err := os.Rename(tmpPath, finalPath); err != nil {
_ = os.Remove(tmpPath)
a.clearTransition(name)
a.wakePoll()
a.emitStateChanged()
return fmt.Errorf("finalize suspend snapshot: %w", err)
}
info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size())
if err := reims.WriteSuspendInfo(d.Directory, info); err != nil {
_ = reims.RemoveSuspendState(d.Directory)
a.clearTransition(name)
a.wakePoll()
a.emitStateChanged()
return fmt.Errorf("write suspend metadata: %w", err)
}
a.cancelRebootWatcher(name)
stopVMMonitor(name)
if gt != nil {
gt.UnregisterVM(name)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
VMName: name,
VMDir: d.Directory,
DriverID: builtin.IDDriverReimsMacOS,
})
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event)
}
a.clearTransition(name)
a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30)))
a.wakePoll()
a.emitStateChanged()
a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30)))
return nil
}
// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via
// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU
// state from suspend.vmstate, and resumes guest execution. On any restore
// failure, suspend.vmstate and suspend.json are preserved so the user can retry.
// ResumeVM restores a suspended VM with its original media and devices.
func (a *App) ResumeVM(name string) error {
loc := a.locale()
prep, err := a.prep(name)
if err != nil {
return err
}
if !prep.Runtime.Manifest.HasCapability("vm-suspend") {
return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name)
if err != nil {
return err
}
defer release()
return a.resumeLocked(prep, d)
}
func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error {
name := d.Name
end, err := a.beginSuspendTransition(name, "resuming")
if err != nil {
return err
}
defer end()
a.mu.Lock()
root := a.cfg.DataRoot
if tr := a.transitions[name]; tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
mgr := a.pluginMgr
root, mgr := a.cfg.DataRoot, a.pluginMgr
a.mu.Unlock()
ctx := a.baseCtx()
c := prep.Client
d, err := c.Show(ctx, name)
if err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name))
}
if !reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil)
}
meta, err := reims.ReadSuspendInfo(d.Directory)
if err != nil {
return fmt.Errorf("read suspend metadata: %w", err)
}
if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 {
return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{
"diffs": strings.Join(diffs, ", "),
}, nil)
}
rep := host.Inspect(root)
if err := prep.CheckWHPX(rep); err != nil {
a.emitLog(name, "Resume refused: "+err.Error())
return err
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
a.emitLog(name, "Resume refused: "+err.Error())
return err
}
a.cancelRebootWatcher(name)
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 {
c.Env = append(c.Env, env...)
}
prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...)
}
if prep.Runtime.Manifest.HasCapability("display-fixed-mode") &&
host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs)
incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs)
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil {
return fmt.Errorf("prepare incoming extra-args: %w", err)
}
restoredExtra := false
restoreExtra := func() {
if restoredExtra {
return
}
restoredExtra = true
if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil {
a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error())
}
}
defer restoreExtra()
a.mu.Lock()
a.transitions[name] = "resuming"
a.mu.Unlock()
a.emitStateChanged()
startAt := time.Now()
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName))
if err := c.Start(ctx, name, w, w); err != nil {
restoreExtra()
a.clearTransition(name)
a.emitLog(name, "Resume launch error: "+err.Error())
a.wakePoll()
a.emitStateChanged()
out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil {
a.emitLog(name, "Resume error: "+err.Error())
return err
}
restoreExtra()
if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil {
a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error())
// Clean up the paused incoming QEMU process without touching suspend.vmstate.
if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil {
_ = c.StopForce(context.Background(), name, io.Discard, io.Discard)
}
a.clearTransition(name)
a.wakePoll()
a.emitStateChanged()
return err
}
if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil {
a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.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,
})
}
a.startVMMonitor(name, d, startAt)
a.clearTransition(name)
a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds()))
a.wakePoll()
a.emitStateChanged()
return nil
}
// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM
// returns to the ordinary stopped state (equivalent to powering off).
// DiscardSuspend deletes a stopped VM's saved execution state.
func (a *App) DiscardSuspend(name string) error {
loc := a.locale()
c, err := a.client()
if err != nil {
return err
}
a.mu.Lock()
if tr := a.transitions[name]; tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
a.mu.Unlock()
ctx := a.baseCtx()
d, err := c.Show(ctx, name)
d, release, err := vmstart.LockVM(a.baseCtx(), c, name)
if err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil)
}
if err := reims.RemoveSuspendState(d.Directory); err != nil {
defer release()
if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil {
return err
}
a.emitLog(name, "Discarded suspend state for "+name)
@@ -343,10 +157,23 @@ func (a *App) DiscardSuspend(name string) error {
return nil
}
func (a *App) clearTransition(name string) {
func (a *App) beginSuspendTransition(name, state string) (func(), error) {
a.mu.Lock()
delete(a.transitions, name)
loc := a.cfg.Locale
if a.transitions[name] != "" {
a.mu.Unlock()
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
a.transitions[name] = state
a.mu.Unlock()
a.emitStateChanged()
return func() {
a.mu.Lock()
delete(a.transitions, name)
a.mu.Unlock()
a.wakePoll()
a.emitStateChanged()
}, nil
}
func (a *App) emitStateChanged() {
+12 -5
View File
@@ -2,6 +2,7 @@ package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
@@ -12,14 +13,20 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
suspendedDir := t.TempDir()
stoppedDir := t.TempDir()
if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil {
if err := os.WriteFile(reims.SuspendStatePath(suspendedDir)+".tmp", []byte("0123456789"), 0o600); err != nil {
t.Fatal(err)
}
if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo(
reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"},
media := filepath.Join(suspendedDir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(suspendedDir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := reims.SealSuspend(
reims.VMDetail{Name: "mac-a", Directory: suspendedDir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"},
rt.Installed{Commit: "3731afd"},
10,
)); err != nil {
[]string{media},
); err != nil {
t.Fatal(err)
}
+19 -1
View File
@@ -529,7 +529,12 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
AudioBackend: strings.TrimSpace(*audioBackend),
GuestLang: strings.TrimSpace(*guestLang),
}
if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
d, release, err := vmstart.LockVM(ctx, client, setOpts.Name)
if err != nil {
return err
}
defer release()
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil)
}
if reims.HasCtlSetChanges(setOpts) {
@@ -556,6 +561,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 stop <name>")
}
_, release, err := vmstart.LockVM(ctx, client, args[1])
if err != nil {
return err
}
defer release()
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
case "suspend":
if len(args) < 2 {
@@ -576,6 +586,14 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm eject <name>")
}
d, release, err := vmstart.LockVM(ctx, client, args[1])
if err != nil {
return err
}
defer release()
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil)
}
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
case "type":
// Paste as keystrokes: the text argument, else stdin.
+9 -1
View File
@@ -50,8 +50,16 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s
if viaWindow && windowHandoffWorks {
return startInWindow(ctx, cfg, name)
}
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
defer release()
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name))
}
if d.State == "stopped" && reims.HasSuspendState(d.Directory) {
return resumeVM(ctx, cfg, prep, name)
return resumeLocked(ctx, cfg, prep, d, rep)
}
// Honour the core plugin's WHPX setting, as the window does.
+23 -131
View File
@@ -3,175 +3,67 @@ package cli
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
loc := cfg.Locale
if !prep.Runtime.Manifest.HasCapability("vm-suspend") {
return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
d, err := prep.Client.Show(ctx, name)
func suspendVM(ctx context.Context, _ *config.Config, prep *vmstart.Prep, name string) error {
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
if d.State != "running" {
return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil)
}
if memGB, ok := reims.ParseSizeGB(d.Memory); ok {
dirRep := host.Inspect(d.Directory)
needGB := memGB + 1.0
if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB {
return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{
"need": fmt.Sprintf("%.1f", needGB),
"avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB),
}, nil)
}
}
var oldPID int
if vms, lerr := prep.Client.List(ctx); lerr == nil {
for _, vm := range vms {
if vm.Name == name && vm.PID != nil && *vm.PID > 0 {
oldPID = *vm.PID
break
}
}
}
defer release()
tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp"
_ = os.Remove(tmpPath)
fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName)
if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil {
_ = os.Remove(tmpPath)
info, err := prep.SuspendSnapshot(ctx, d, nil)
if err != nil {
return err
}
if oldPID > 0 {
waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second)
_ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe")
cancel()
}
st, err := os.Stat(tmpPath)
if err != nil || st.Size() <= 0 {
_ = os.Remove(tmpPath)
if err != nil {
return err
}
return fmt.Errorf("suspend snapshot is empty after save")
}
finalPath := reims.SuspendStatePath(d.Directory)
_ = os.Remove(finalPath)
if err := os.Rename(tmpPath, finalPath); err != nil {
_ = os.Remove(tmpPath)
return err
}
if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil {
_ = reims.RemoveSuspendState(d.Directory)
return err
}
fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30))
fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(info.VMStateSize)/float64(1<<30))
return nil
}
func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
loc := cfg.Locale
if !prep.Runtime.Manifest.HasCapability("vm-suspend") {
return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
rep := host.Inspect(cfg.DataRoot)
d, err := prep.Client.Show(ctx, name)
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name))
}
if !reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil)
}
meta, err := reims.ReadSuspendInfo(d.Directory)
if err != nil {
return err
}
if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 {
return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{
"diffs": strings.Join(diffs, ", "),
}, nil)
}
if err := prep.CheckWHPX(rep); err != nil {
return err
}
if err := prep.CheckMemory(d.Memory, rep); err != nil {
return err
}
defer release()
return resumeLocked(ctx, cfg, prep, d, host.Inspect(cfg.DataRoot))
}
origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs)
incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs)
if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil {
return err
}
restored := false
restoreExtra := func() {
if restored {
return
}
restored = true
_ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard)
}
defer restoreExtra()
fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName)
func resumeLocked(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, d reims.VMDetail, rep host.Report) error {
fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", d.Name, reims.SuspendStateFileName)
startAt := time.Now()
if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil {
restoreExtra()
if err := prep.ResumeSnapshot(ctx, d, rep, os.Stdout, os.Stderr); err != nil {
return err
}
restoreExtra()
if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil {
if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil {
_ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard)
}
return err
}
_ = reims.RemoveSuspendState(d.Directory)
if vms, lerr := prep.Client.List(ctx); lerr == nil {
if vms, err := prep.Client.List(ctx); err == nil {
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
vmDir := vm.Dir
if vmDir == "" {
vmDir = d.Directory
}
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
fmt.Fprintln(os.Stderr, line)
}
if vm.Name != d.Name || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
continue
}
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, d.Directory, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" {
fmt.Fprintln(os.Stderr, line)
}
}
}
fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds())
fmt.Printf("Resumed %s in %.1fs\n", d.Name, time.Since(startAt).Seconds())
return nil
}
func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error {
loc := cfg.Locale
d, err := prep.Client.Show(ctx, name)
d, release, err := vmstart.LockVM(ctx, prep.Client, name)
if err != nil {
return err
}
if d.State == "running" {
return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil)
}
if err := reims.RemoveSuspendState(d.Directory); err != nil {
defer release()
if err := vmstart.DiscardSnapshot(cfg.Locale, d); err != nil {
return err
}
fmt.Printf("Discarded suspend state for %s\n", name)
+33 -32
View File
@@ -18,7 +18,7 @@ const (
// create suspend.vmstate so incompatible resumes are caught before launch.
SuspendMetaFileName = "suspend.json"
// SuspendSchemaVersion is the current metadata schema version.
SuspendSchemaVersion = 1
SuspendSchemaVersion = 2
)
// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder.
@@ -56,24 +56,46 @@ func SuspendMetaPath(vmDir string) string {
// HasSuspendState reports whether vmDir contains a complete suspend snapshot
// (both a non-empty suspend.vmstate and its suspend.json metadata).
func HasSuspendState(vmDir string) bool {
state, _ := suspendFiles(vmDir)
return state != ""
}
func suspendFiles(vmDir string) (state, meta string) {
if strings.TrimSpace(vmDir) == "" {
return false
return "", ""
}
st, err := os.Stat(SuspendStatePath(vmDir))
if err != nil || st.IsDir() || st.Size() <= 0 {
return false
state, meta = SuspendStatePath(vmDir), SuspendMetaPath(vmDir)
nonEmpty := func(path string) bool {
st, err := os.Stat(path)
return err == nil && st.Mode().IsRegular() && st.Size() > 0
}
mst, err := os.Stat(SuspendMetaPath(vmDir))
if err != nil || mst.IsDir() || mst.Size() <= 0 {
return false
if nonEmpty(meta) {
if nonEmpty(state) {
return state, meta
}
return "", ""
}
return true
// A staged record is written only after the full state file was
// synced. Preserve that pair if either of the publication steps fails.
if nonEmpty(meta + ".tmp") {
if nonEmpty(state) {
return state, meta + ".tmp"
}
if nonEmpty(state + ".tmp") {
return state + ".tmp", meta + ".tmp"
}
}
return "", ""
}
// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from
// the actual suspend.vmstate file on disk.
func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) {
b, err := os.ReadFile(SuspendMetaPath(vmDir))
state, meta := suspendFiles(vmDir)
if state == "" {
return nil, os.ErrNotExist
}
b, err := os.ReadFile(meta)
if err != nil {
return nil, err
}
@@ -81,33 +103,12 @@ func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) {
if err := json.Unmarshal(b, &info); err != nil {
return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err)
}
if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() {
if st, err := os.Stat(state); err == nil {
info.VMStateSize = st.Size()
}
return &info, nil
}
// WriteSuspendInfo atomically writes suspend.json inside vmDir.
func WriteSuspendInfo(vmDir string, info SuspendInfo) error {
if info.SchemaVersion == 0 {
info.SchemaVersion = SuspendSchemaVersion
}
if info.CreatedAt == "" {
info.CreatedAt = time.Now().UTC().Format(time.RFC3339)
}
info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs)
b, err := json.MarshalIndent(info, "", " ")
if err != nil {
return err
}
b = append(b, '\n')
tmp := SuspendMetaPath(vmDir) + ".tmp"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return err
}
return os.Rename(tmp, SuspendMetaPath(vmDir))
}
// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json.
func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo {
return SuspendInfo{
@@ -0,0 +1,26 @@
//go:build !windows
package reims
import (
"errors"
"fmt"
"os"
"syscall"
)
func lockVMFile(f *os.File) error {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if errors.Is(err, syscall.EWOULDBLOCK) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, info os.FileInfo) (uint64, uint64, error) {
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return 0, 0, fmt.Errorf("file identity unavailable for %s", path)
}
return uint64(st.Dev), uint64(st.Ino), nil
}
@@ -0,0 +1,39 @@
//go:build windows
package reims
import (
"errors"
"os"
"golang.org/x/sys/windows"
)
func lockVMFile(f *os.File) error {
err := windows.LockFileEx(windows.Handle(f.Fd()),
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
0, 1, 0, new(windows.Overlapped))
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) {
name, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, 0, err
}
handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES,
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 0, 0, err
}
defer windows.CloseHandle(handle)
var info windows.ByHandleFileInformation
if err := windows.GetFileInformationByHandle(handle, &info); err != nil {
return 0, 0, err
}
return uint64(info.VolumeSerialNumber), uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil
}
+11 -4
View File
@@ -2,6 +2,7 @@ package reims
import (
"os"
"path/filepath"
"strings"
"testing"
@@ -17,7 +18,7 @@ func TestSuspendStateLifecycle(t *testing.T) {
}
// Only vmstate without meta -> incomplete.
if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil {
if err := os.WriteFile(SuspendStatePath(dir)+".tmp", []byte("vmstate-bytes"), 0o644); err != nil {
t.Fatal(err)
}
if HasSuspendState(dir) {
@@ -32,6 +33,7 @@ func TestSuspendStateLifecycle(t *testing.T) {
}
detail := VMDetail{
Name: "tahoe",
Directory: dir,
CPUs: 8,
Memory: "8G",
Graphics: "reims-vgpu",
@@ -42,9 +44,14 @@ func TestSuspendStateLifecycle(t *testing.T) {
Network: true,
ExtraArgs: "-machine kernel-irqchip=on -incoming defer",
}
info := BuildSuspendInfo(detail, active, 13)
if err := WriteSuspendInfo(dir, info); err != nil {
t.Fatalf("WriteSuspendInfo: %v", err)
media := filepath.Join(dir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(dir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := SealSuspend(detail, active, []string{media}); err != nil {
t.Fatalf("SealSuspend: %v", err)
}
if !HasSuspendState(dir) {
t.Fatal("expected HasSuspendState=true after writing both files")
@@ -0,0 +1,185 @@
package reims
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
var ErrVMOperationBusy = errors.New("another operation holds the VM lock")
// LockVMOperation serializes GUI and CLI operations on the same VM directory.
// The lock file stays in place so contenders always lock the same inode.
func LockVMOperation(vmDir string) (func(), error) {
if strings.TrimSpace(vmDir) == "" {
return nil, fmt.Errorf("VM directory is required")
}
f, err := os.OpenFile(filepath.Join(vmDir, ".reims-go-vm-operation.lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := lockVMFile(f); err != nil {
_ = f.Close()
return nil, err
}
return func() { _ = f.Close() }, nil
}
type mediaFingerprint struct {
Path string `json:"path"`
Volume uint64 `json:"volume"`
FileID uint64 `json:"file_id"`
Size int64 `json:"size"`
MTime int64 `json:"mtime_ns"`
}
type suspendRecord struct {
SuspendInfo
ConfigHash string `json:"config_sha256"`
Media []mediaFingerprint `json:"media"`
}
func fingerprintMedia(path string) (mediaFingerprint, error) {
st, err := os.Stat(path)
if err != nil {
return mediaFingerprint{}, err
}
if !st.Mode().IsRegular() {
return mediaFingerprint{}, fmt.Errorf("attached path is not a regular file: %s", path)
}
volume, id, err := mediaFileID(path, st)
if err != nil {
return mediaFingerprint{}, err
}
return mediaFingerprint{Path: path, Volume: volume, FileID: id, Size: st.Size(), MTime: st.ModTime().UnixNano()}, nil
}
func suspendConfigHash(vmDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml"))
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]), nil
}
// SealSuspend publishes a completed migration as the only usable snapshot.
// Every failure leaves the migration file available and the sender still alive.
func SealSuspend(d VMDetail, active rt.Installed, paths []string) (SuspendInfo, error) {
if len(paths) == 0 {
return SuspendInfo{}, fmt.Errorf("cannot seal a snapshot without attached media")
}
dir := d.Directory
tmp := SuspendStatePath(dir) + ".tmp"
state, err := os.OpenFile(tmp, os.O_RDWR, 0)
if err != nil {
return SuspendInfo{}, err
}
st, err := state.Stat()
if err == nil && (!st.Mode().IsRegular() || st.Size() == 0) {
err = fmt.Errorf("suspend snapshot is empty or is not a regular file")
}
if err == nil {
err = state.Sync()
}
if err := errors.Join(err, state.Close()); err != nil {
return SuspendInfo{}, err
}
configHash, err := suspendConfigHash(dir)
if err != nil {
return SuspendInfo{}, err
}
record := suspendRecord{
SuspendInfo: BuildSuspendInfo(d, active, st.Size()),
ConfigHash: configHash,
Media: make([]mediaFingerprint, 0, len(paths)),
}
for _, path := range paths {
item, err := fingerprintMedia(path)
if err != nil {
return SuspendInfo{}, fmt.Errorf("fingerprint attached media: %w", err)
}
record.Media = append(record.Media, item)
}
metaTmp := SuspendMetaPath(dir) + ".tmp"
if err := stageSuspendRecord(metaTmp, record); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(tmp, SuspendStatePath(dir)); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(metaTmp, SuspendMetaPath(dir)); err != nil {
return SuspendInfo{}, err
}
return record.SuspendInfo, nil
}
func stageSuspendRecord(path string, record suspendRecord) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(record)
if err == nil {
err = f.Sync()
}
return errors.Join(err, f.Close())
}
// ValidateSuspendFiles checks contents and identities before starting incoming
// QEMU and returns the expected media paths for validation before load.
func ValidateSuspendFiles(d VMDetail, active rt.Installed) (string, []string, error) {
state, meta := suspendFiles(d.Directory)
if state == "" {
return "", nil, os.ErrNotExist
}
data, err := os.ReadFile(meta)
if err != nil {
return "", nil, err
}
var record suspendRecord
if err := json.Unmarshal(data, &record); err != nil {
return "", nil, err
}
if record.SchemaVersion != SuspendSchemaVersion || record.ConfigHash == "" || len(record.Media) == 0 {
return "", nil, fmt.Errorf("snapshot has no supported VM and media fingerprint")
}
st, err := os.Stat(state)
if err != nil {
return "", nil, err
}
if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() != record.VMStateSize {
return "", nil, fmt.Errorf("snapshot file size changed")
}
diffs := ValidateSuspendCompatibility(record.SuspendInfo, d, active)
configHash, err := suspendConfigHash(d.Directory)
if err != nil {
return "", nil, err
}
if configHash != record.ConfigHash {
diffs = append(diffs, "VM configuration changed")
}
paths := make([]string, 0, len(record.Media))
for _, expected := range record.Media {
current, err := fingerprintMedia(expected.Path)
if err != nil || current != expected {
diffs = append(diffs, fmt.Sprintf("attached media changed (%s)", expected.Path))
}
paths = append(paths, expected.Path)
}
if len(diffs) > 0 {
return "", nil, errors.New(strings.Join(diffs, ", "))
}
slices.Sort(paths)
return state, paths, nil
}
@@ -0,0 +1,89 @@
package reims
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestVMOperationLockExcludesAnotherHandle(t *testing.T) {
dir := t.TempDir()
release, err := LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
if _, err = LockVMOperation(dir); !errors.Is(err, ErrVMOperationBusy) {
t.Fatalf("second lock = %v, want busy", err)
}
release()
release, err = LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
release()
}
func TestSuspendTransactionRejectsChangedBackingFile(t *testing.T) {
dir := t.TempDir()
top := filepath.Join(dir, "disk.qcow2")
base := filepath.Join(dir, "base.qcow2")
for _, path := range []string{top, base, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} {
if err := os.WriteFile(path, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
}
d := VMDetail{Name: "test", Directory: dir, CPUs: 2, Memory: "4G"}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{top, base}); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err != nil {
t.Fatal(err)
}
st, err := os.Stat(base)
if err != nil {
t.Fatal(err)
}
if err := os.Rename(base, base+".old"); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(base, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(base, st.ModTime(), st.ModTime()); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err == nil || !strings.Contains(err.Error(), "base.qcow2") {
t.Fatalf("replaced backing file not detected: %v", err)
}
}
func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) {
dir := t.TempDir()
media := filepath.Join(dir, "OVMF_VARS.fd")
stagedState := SuspendStatePath(dir) + ".tmp"
for _, path := range []string{media, filepath.Join(dir, "vm.toml"), stagedState} {
if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(SuspendMetaPath(dir), 0o700); err != nil {
t.Fatal(err)
}
d := VMDetail{Name: "test", Directory: dir}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{media}); err == nil {
t.Fatal("expected publication to fail")
}
if !HasSuspendState(dir) {
t.Fatal("published state and staged metadata should be recoverable")
}
state, paths, err := ValidateSuspendFiles(d, runtime)
if err != nil || state != SuspendStatePath(dir) || len(paths) != 1 || paths[0] != media {
t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err)
}
}
+59
View File
@@ -0,0 +1,59 @@
package qmp
import (
"encoding/json"
"fmt"
"path/filepath"
"slices"
"strings"
)
// AttachedFiles lists the inserted image and backing files for each block
// device. QEMU's resolved image names include the real pflash and CD drives.
func (c *Conn) AttachedFiles(vmDir string) ([]string, error) {
raw, err := c.Query("query-block", nil)
if err != nil {
return nil, err
}
type image struct {
Filename string `json:"filename"`
Backing *image `json:"backing-image"`
}
var devices []struct {
Device string `json:"device"`
Inserted *struct {
Image *image `json:"image"`
Backing string `json:"backing_file"`
} `json:"inserted"`
}
if err := json.Unmarshal(raw, &devices); err != nil {
return nil, fmt.Errorf("decode query-block: %w", err)
}
var paths []string
for _, d := range devices {
if d.Inserted == nil {
continue
}
if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) {
return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain")
}
for img := d.Inserted.Image; img != nil; img = img.Backing {
if img.Filename == "" {
return nil, fmt.Errorf("block device has no filename")
}
name := img.Filename
if strings.HasPrefix(name, "json:") {
return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device)
}
if !filepath.IsAbs(name) {
name = filepath.Join(vmDir, name)
}
paths = append(paths, filepath.Clean(name))
}
}
if len(paths) == 0 {
return nil, fmt.Errorf("no attached media reported by QEMU")
}
slices.Sort(paths)
return slices.Compact(paths), nil
}
+20 -4
View File
@@ -53,16 +53,20 @@ type vmStatusReply struct {
// If migration fails before reaching completion while the VM is merely paused
// (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)) error {
func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error {
c, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer c.Close()
return suspendToFileConn(ctx, c, vmstatePath, onProgress)
paths, err := c.AttachedFiles(vmDir)
if err != nil {
return err
}
return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) })
}
func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error {
func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error {
if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil {
return fmt.Errorf("pause VM before suspend: %w", err)
}
@@ -92,6 +96,13 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr
tryResumePaused(c)
return fmt.Errorf("save snapshot: %w", err)
}
if seal != nil {
if err := seal(c); err != nil {
// The source still owns the session. Leave it paused and retain
// the completed file if publishing the save failed.
return fmt.Errorf("seal snapshot before exiting QEMU: %w", err)
}
}
// Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here;
// exit QEMU cleanly so the disk and WHPX partition close.
@@ -109,12 +120,17 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr
// completion, and resumes execution with `cont`.
//
// On any error, vmstatePath is left untouched so the caller can retry.
func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error {
func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), checkMedia func(*Conn) error) error {
c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second)
if err != nil {
return err
}
defer c.Close()
if checkMedia != nil {
if err := checkMedia(c); err != nil {
return err
}
}
return resumeFromFileConn(ctx, c, vmstatePath, onProgress)
}
+77 -2
View File
@@ -4,12 +4,87 @@ import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
func TestAttachedFiles(t *testing.T) {
vmDir := t.TempDir()
disk := filepath.Join(vmDir, "disk.qcow2")
parent := filepath.Join(vmDir, "base.qcow2")
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
if req.Execute != "query-block" {
t.Errorf("unexpected command: %s", req.Execute)
}
return map[string]any{"return": []map[string]any{
{"device": "disk", "inserted": map[string]any{"image": map[string]any{
"filename": disk, "backing-image": map[string]any{"filename": parent},
}}},
{"device": "empty", "inserted": nil},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
got, err := c.AttachedFiles(vmDir)
if err != nil || !slices.Equal(got, []string{parent, disk}) {
t.Fatalf("attached files = %v, %v", got, err)
}
}
func TestAttachedFilesRejectsTemporaryOverlay(t *testing.T) {
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
return map[string]any{"return": []map[string]any{
{"device": "installer", "inserted": map[string]any{"image": map[string]any{
"filename": "json:temporary disk descriptor",
}}},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := c.AttachedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "installer uses a non-persistent") {
t.Fatalf("temporary installer overlay = %v", err)
}
}
func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) {
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed"}}, false
case "quit":
t.Error("QEMU would exit with an unsealed snapshot")
}
return map[string]any{"return": map[string]any{}}, false
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
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) {
t.Fatalf("suspend error = %v", err)
}
cmds := recorded()
if len(cmds) == 0 || cmds[len(cmds)-1].Execute != "query-migrate" {
t.Fatalf("unexpected commands: %+v", cmds)
}
}
type mockQMPReq struct {
Execute string `json:"execute"`
Arguments json.RawMessage `json:"arguments"`
@@ -104,7 +179,7 @@ func TestSuspendToFileHappyPath(t *testing.T) {
var progress []MigrateProgress
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) {
progress = append(progress, p)
}); err != nil {
}, nil); err != nil {
t.Fatalf("suspendToFileConn: %v", err)
}
if len(progress) != 2 || progress[1].Status != "completed" {
@@ -141,7 +216,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) {
}
defer c.Close()
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil)
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
if err == nil || !strings.Contains(err.Error(), "disk full") {
t.Fatalf("expected disk full error, got %v", err)
}
+198
View File
@@ -0,0 +1,198 @@
package vmstart
import (
"context"
"errors"
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/qmp"
)
// LockVM reads the VM again after locking its directory so that another
// process cannot change the state between inspection and operation.
func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
d, err := c.Show(ctx, name)
if err != nil {
return d, nil, err
}
release, err := reims.LockVMOperation(d.Directory)
if errors.Is(err, reims.ErrVMOperationBusy) {
return d, nil, i18n.NewCodedError(c.Locale, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
if err != nil {
return d, nil, err
}
cur, err := c.Show(ctx, name)
if err == nil && cur.Directory != d.Directory {
err = fmt.Errorf("VM directory changed while waiting to operate on %s", name)
}
if err != nil {
release()
return cur, nil, err
}
return cur, release, nil
}
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") {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
return nil
}
// SuspendSnapshot saves and publishes a VM snapshot while the caller holds
// LockVM. The source exits only after the snapshot and metadata are durable.
func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress func(qmp.MigrateProgress)) (reims.SuspendInfo, error) {
var info reims.SuspendInfo
if err := p.checkSuspendRuntime(d); err != nil {
return info, err
}
pid, err := vmPID(ctx, p.Client, d.Name)
if err != nil {
return info, err
}
if pid == 0 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": d.Name}, nil)
}
if memGB, ok := reims.ParseSizeGB(d.Memory); ok {
if avail := host.Inspect(d.Directory).FreeDiskGB; avail > 0 && avail < memGB+1 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{
"need": fmt.Sprintf("%.1f", memGB+1), "avail": fmt.Sprintf("%.1f", avail),
}, nil)
}
}
state := reims.SuspendStatePath(d.Directory)
tmp := state + ".tmp"
meta := reims.SuspendMetaPath(d.Directory)
for _, path := range []string{state, tmp, meta, meta + ".tmp"} {
if _, err := os.Lstat(path); !os.IsNotExist(err) {
if err != nil {
return info, err
}
return info, fmt.Errorf("previous suspend data still exists: %s", path)
}
}
err = qmp.SuspendToFile(ctx, d.Directory, tmp, progress, func(paths []string) error {
var err error
info, err = reims.SealSuspend(d, p.Runtime, paths)
return err
})
if err != nil {
return info, err
}
waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := host.WaitProcessExit(waitCtx, uint32(pid), "qemu-system-x86_64.exe"); err != nil {
if !errors.Is(err, errors.ErrUnsupported) {
return info, err
}
for {
cur, err := vmPID(waitCtx, p.Client, d.Name)
if err != nil || cur == 0 {
return info, err
}
select {
case <-waitCtx.Done():
return info, waitCtx.Err()
case <-time.After(100 * time.Millisecond):
}
}
}
return info, nil
}
// ResumeSnapshot owns the incoming launch and snapshot consumption while
// the caller holds LockVM. The original configuration must be restored
// before guest execution can continue.
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error {
if err := p.checkSuspendRuntime(d); err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(p.Client.Locale, "vm.already_running", d.Name))
}
if !reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": d.Name}, nil)
}
state, paths, err := reims.ValidateSuspendFiles(d, p.Runtime)
if err != nil {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{"diffs": err.Error()}, err)
}
if err := p.CheckWHPX(rep); err != nil {
return err
}
if err := p.CheckMemory(d.Memory, rep); err != nil {
return err
}
c := p.Client
incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs)
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil {
return err
}
startErr := c.Start(ctx, d.Name, out, stderr)
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
restoreErr := c.Set(restoreCtx, reims.SetOpts{Name: d.Name, ExtraArgs: &d.ExtraArgs}, out, stderr)
cancel()
if restoreErr != nil {
restoreErr = fmt.Errorf("restore original VM start arguments: %w", restoreErr)
}
if err := errors.Join(startErr, restoreErr); err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
err = qmp.ResumeFromFile(ctx, d.Directory, state, nil, func(conn *qmp.Conn) error {
attached, err := conn.AttachedFiles(d.Directory)
if err != nil {
return err
}
if !slices.Equal(paths, attached) {
return fmt.Errorf("incoming QEMU opened different media from the saved VM")
}
return nil
})
if err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
if err := reims.RemoveSuspendState(d.Directory); err != nil {
p.log("Warning: could not remove consumed suspend files: " + err.Error())
}
return nil
}
func (p *Prep) stopFailedIncoming(ctx context.Context, d reims.VMDetail) {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := qmp.QuitVM(cleanup, d.Directory); err != nil {
_ = p.Client.StopForce(cleanup, d.Name, io.Discard, io.Discard)
}
}
func DiscardSnapshot(loc i18n.Locale, d reims.VMDetail) error {
if d.State == "running" {
return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": d.Name}, nil)
}
return reims.RemoveSuspendState(d.Directory)
}
func vmPID(ctx context.Context, c *reims.Client, name string) (int, error) {
vms, err := c.List(ctx)
if err != nil {
return 0, err
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil {
return *vm.PID, nil
}
}
return 0, nil
}