232 lines
7.6 KiB
Go
232 lines
7.6 KiB
Go
package startprep
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"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
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
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, 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 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.
|
|
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
|
|
}
|
|
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
|
|
}
|