Files
Reims-Go/internal/macos/startprep/suspend.go
T
千川白浪 2578ad4681 fix(macos): use the runtime QMP socket for suspend and resume
model: magpie-responses/codex/gpt-6.2-sol
agent: Codex
2026-12-03 22:10:39 +08:00

331 lines
11 KiB
Go

package startprep
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"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
}
// 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
}
// CleanStaleSuspendBeforeStart checks for a live QEMU before cleaning a stopped VM.
// The caller holds LockVM and has already checked for a recoverable snapshot.
func CleanStaleSuspendBeforeStart(ctx context.Context, vmDir, vmName, tmpDir string, log, warn func(string)) error {
return cleanStaleSuspendBeforeStart(ctx, vmDir, vmName, tmpDir, log, warn, qmp.QueryStatusAt)
}
func cleanStaleSuspendBeforeStart(ctx context.Context, vmDir, vmName, tmpDir string, log, warn func(string), queryStatus func(context.Context, string) (qmp.VMStatus, error)) error {
pidPath := filepath.Join(vmDir, "qemu.pid")
if _, err := os.Lstat(pidPath); err == nil {
if _, err := os.ReadFile(pidPath); err != nil {
return fmt.Errorf("cannot start VM: read QEMU PID: %w", err)
}
} else if !os.IsNotExist(err) {
return fmt.Errorf("cannot start VM: inspect QEMU PID: %w", err)
}
sockets := []string{qmp.SocketPathForVM(vmDir, vmName, tmpDir)}
if own := qmp.SocketPath(vmDir); own != sockets[0] {
sockets = append(sockets, own)
}
for _, socket := range sockets {
if _, err := os.Lstat(socket); os.IsNotExist(err) {
continue
} else if err != nil {
return fmt.Errorf("cannot start VM: inspect QMP socket: %w", err)
}
probe, cancel := context.WithTimeout(ctx, 2*time.Second)
status, err := queryStatus(probe, socket)
probeErr := probe.Err()
cancel()
if err == nil {
return fmt.Errorf("cannot start VM: QEMU is still active (QMP status: %s)", status.Status)
}
if probeErr != nil || !qmpEndpointGone(err) {
return fmt.Errorf("cannot start VM: could not determine QEMU status: %w", err)
}
}
removed, err := reims.CleanStaleSuspendArtifacts(vmDir)
if errors.Is(err, reims.ErrSuspendArtifactsUncertain) || errors.Is(err, reims.ErrSuspendStatePresent) {
return fmt.Errorf("cannot start VM: %w", err)
}
if len(removed) > 0 {
log(fmt.Sprintf("Removed %d stale suspend file(s).", len(removed)))
}
if err != nil {
warn("Warning: could not remove stale suspend files: " + err.Error())
}
return nil
}
func qmpEndpointGone(err error) bool {
var opErr *net.OpError
if !errors.As(err, &opErr) || opErr.Op != "dial" || opErr.Timeout() || errors.Is(err, context.Canceled) {
return false
}
return errors.Is(opErr.Err, os.ErrNotExist) || errors.Is(opErr.Err, syscall.ENOENT) ||
errors.Is(opErr.Err, syscall.ECONNREFUSED) || qmpPlatformEndpointGone(opErr.Err)
}
// 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") {
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)
}
}
socket := qmp.SocketPathForVM(d.Directory, d.Name, p.cfg.TempDir())
if err := p.prepareSuspendArtifacts(ctx, d.Directory, socket, qmp.QueryStatusAt); err != nil {
return info, err
}
tmp := reims.SuspendStatePath(d.Directory) + ".tmp"
err = qmp.SuspendToFile(ctx, socket, 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, cleanupSuspendAttempt(tmp, 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
}
func (p *Prep) prepareSuspendArtifacts(ctx context.Context, vmDir, socket string, queryStatus func(context.Context, string) (qmp.VMStatus, error)) error {
path, err := firstSuspendArtifact(vmDir)
if err != nil || path == "" {
return err
}
if reims.HasSuspendState(vmDir) {
return fmt.Errorf("previous suspend data still exists: %s", path)
}
st, err := queryStatus(ctx, socket)
if err != nil {
return fmt.Errorf("previous suspend data still exists: %s: query VM status: %w", path, err)
}
if !st.Running {
return fmt.Errorf("previous suspend data still exists: %s", path)
}
removed, err := reims.CleanStaleSuspendArtifacts(vmDir)
if len(removed) > 0 {
p.log(fmt.Sprintf("Removed %d stale suspend file(s).", len(removed)))
}
if errors.Is(err, reims.ErrSuspendStatePresent) {
return fmt.Errorf("previous suspend data still exists: %s: %w", path, err)
}
if err != nil {
return fmt.Errorf("remove stale suspend files: %w", err)
}
path, err = firstSuspendArtifact(vmDir)
if err == nil && path != "" {
return fmt.Errorf("previous suspend data still exists: %s", path)
}
return err
}
func firstSuspendArtifact(vmDir string) (string, error) {
state, meta := reims.SuspendStatePath(vmDir), reims.SuspendMetaPath(vmDir)
for _, path := range []string{state, state + ".tmp", meta, meta + ".tmp"} {
if _, err := os.Lstat(path); !os.IsNotExist(err) {
return path, err
}
}
return "", nil
}
func cleanupSuspendAttempt(tmp string, err error) error {
if errors.Is(err, qmp.ErrIncompleteSuspend) {
if removeErr := reims.RemoveSuspendFile(tmp); removeErr != nil {
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.
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, launchArgs string, 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(launchArgs)
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
}
socket := qmp.SocketPathForVM(d.Directory, d.Name, p.cfg.TempDir())
err = qmp.ResumeFromFile(ctx, socket, 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()
socket := qmp.SocketPathForVM(d.Directory, d.Name, p.cfg.TempDir())
if err := qmp.QuitVM(cleanup, socket); 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
}