Files
Reims-Go/internal/qmp/migrate.go
T

411 lines
12 KiB
Go

package qmp
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
)
const (
// DefaultMultifdChannels is the parallel I/O channel count used for
// mapped-ram file snapshots on Windows.
DefaultMultifdChannels = 8
// UnlimitedMigrationBandwidth disables QEMU's default 128 MiB/s throttle
// (RATE_LIMIT_DISABLED = 0 in migration/migration-stats.h) for paused
// local snapshot writes.
UnlimitedMigrationBandwidth = 0
migratePollInterval = 100 * time.Millisecond
migrateCmdTimeout = 2 * time.Minute
migrateTotalTimeout = 15 * time.Minute
)
// MigrateProgress carries the latest snapshot save/load progress from QMP
// `query-migrate`.
type MigrateProgress struct {
Status string `json:"status"`
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
TotalTimeMs int64 `json:"total_time_ms"`
}
type migrateInfo struct {
Status string `json:"status"`
ErrorDesc string `json:"error-desc"`
TotalTimeMs int64 `json:"total-time"`
RAM *struct {
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
} `json:"ram"`
}
type vmStatusReply struct {
Running bool `json:"running"`
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`.
//
// 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), seal func([]string) error) error {
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
}
defer c.Close()
paths, err := c.AttachedFiles(vmDir)
if err != nil {
return err
}
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 {
if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil {
return fmt.Errorf("pause VM before suspend: %w", err)
}
st, err := queryVMStatus(c)
if err != nil {
tryResumePaused(c)
return fmt.Errorf("verify paused state: %w", err)
}
if st.Running {
return fmt.Errorf("VM remained running after stop (status=%s)", st.Status)
}
directIO, err := configureMappedRAM(c, true)
if err != nil {
tryResumePaused(c)
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
}
err = runSuspendMigration(ctx, c, args, onProgress)
if directIO && errors.Is(err, ErrIncompleteSuspend) && isDirectIOErr(err) {
// Fall back to buffered file I/O if the target volume rejects Win32
// direct I/O (e.g., compressed directory or unsupported filesystem).
if st, stErr := queryVMStatus(c); stErr == nil && !st.Running && st.Status == "paused" {
if disableErr := c.ExecuteWithTimeout("migrate-set-parameters", map[string]any{"direct-io": false}, 15*time.Second); disableErr == nil {
err = runSuspendMigration(ctx, c, args, onProgress)
}
}
}
if err != nil {
if errors.Is(err, ErrIncompleteSuspend) {
tryResumePaused(c)
}
return 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.
if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil {
// QEMU may close the QMP socket immediately upon receiving `quit`.
if !isConnClosedErr(err) {
return fmt.Errorf("quit QEMU after suspend: %w", err)
}
}
return nil
}
// ResumeFromFile connects to a QEMU process started with `-incoming defer`,
// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for
// 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), 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)
}
func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error {
// Keep direct-io disabled on incoming resume so OS read-ahead accelerates
// sparse mapped-ram bitmap reads.
if _, err := configureMappedRAM(c, false); err != nil {
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
"exit-on-error": false,
}
if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil {
return fmt.Errorf("start snapshot restore: %w", err)
}
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
return fmt.Errorf("restore snapshot: %w", err)
}
if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil {
return fmt.Errorf("resume VM execution after restore: %w", err)
}
return nil
}
// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a
// failed incoming-resume QEMU process).
func QuitVM(ctx context.Context, vmDir string) error {
c, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer c.Close()
if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) {
return err
}
return nil
}
func configureMappedRAM(c *Conn, enableDirectIO bool) (bool, error) {
caps := map[string]any{
"capabilities": []map[string]any{
{"capability": "mapped-ram", "state": true},
{"capability": "multifd", "state": true},
},
}
if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil {
return false, fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err)
}
params := map[string]any{
"max-bandwidth": UnlimitedMigrationBandwidth,
"multifd-channels": DefaultMultifdChannels,
}
if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil {
return false, fmt.Errorf("set migration parameters: %w", err)
}
if !enableDirectIO {
return false, nil
}
if err := c.ExecuteWithTimeout("migrate-set-parameters", map[string]any{"direct-io": true}, 15*time.Second); err != nil {
var rejected *commandError
if errors.As(err, &rejected) {
// Older QEMU builds without Win32 direct-io reject the parameter;
// continue with buffered multifd I/O.
return false, nil
}
return false, fmt.Errorf("enable direct-io migration parameter: %w", err)
}
return true, nil
}
func fileChannels(vmstatePath string) []map[string]any {
return []map[string]any{
{
"channel-type": "main",
"addr": map[string]any{
"transport": "file",
"filename": filepath.Clean(vmstatePath),
"offset": 0,
},
},
}
}
func queryVMStatus(c *Conn) (vmStatusReply, error) {
raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second)
if err != nil {
return vmStatusReply{}, err
}
var st vmStatusReply
if err := json.Unmarshal(raw, &st); err != nil {
return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err)
}
return st, nil
}
func tryResumePaused(c *Conn) {
st, err := queryVMStatus(c)
if err != nil || st.Running {
return
}
// Only resume when QEMU is still in ordinary paused state (never postmigrate).
if st.Status == "paused" {
_ = c.ExecuteWithTimeout("cont", nil, 10*time.Second)
}
}
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 {
if err := ctx.Err(); err != nil {
return err
}
if time.Now().After(deadline) {
return errors.New("timed out waiting for migration to finish")
}
info, err := queryMigration(c, migrateCmdTimeout)
if err != nil {
return err
}
prog := MigrateProgress{
Status: info.Status,
TotalTimeMs: info.TotalTimeMs,
}
if info.RAM != nil {
prog.Transferred = info.RAM.Transferred
prog.Remaining = info.RAM.Remaining
prog.Total = info.RAM.Total
}
if onProgress != nil {
onProgress(prog)
}
switch info.Status {
case "completed":
return nil
case "failed", "cancelled":
return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)}
}
sleep(ctx, migratePollInterval)
}
}
func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) {
deadline := time.Now().Add(timeout)
var lastErr error
for {
c, err := Dial(ctx, network, addr)
if err == nil {
return c, nil
}
lastErr = err
if ctx.Err() != nil || time.Now().After(deadline) {
return nil, lastErr
}
sleep(ctx, 100*time.Millisecond)
}
}
func runSuspendMigration(ctx context.Context, c *Conn, args map[string]any, onProgress func(MigrateProgress)) error {
if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil {
var rejected *commandError
if errors.As(err, &rejected) {
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 {
var failed *migrationFailure
if errors.As(err, &failed) {
return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err)
}
return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)}
}
return nil
}
func isDirectIOErr(err error) bool {
s := strings.ToLower(err.Error())
return strings.Contains(s, "direct i/o") || strings.Contains(s, "direct-io") || strings.Contains(s, "o_direct")
}
func isConnClosedErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe")
}