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

537 lines
17 KiB
Go

package qmp
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"path/filepath"
"slices"
"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")
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) || errors.Is(err, ErrIncompleteSuspend) {
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"`
}
func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen mock QMP: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
var mu sync.Mutex
var recorded []mockQMPReq
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(nc net.Conn) {
defer nc.Close()
_, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n"))
sc := bufio.NewScanner(nc)
for sc.Scan() {
var req mockQMPReq
if err := json.Unmarshal(sc.Bytes(), &req); err != nil {
return
}
if req.Execute == "qmp_capabilities" {
_, _ = nc.Write([]byte(`{"return":{}}` + "\n"))
continue
}
mu.Lock()
recorded = append(recorded, req)
mu.Unlock()
reply, closeAfter := handle(req)
if reply != nil {
b, _ := json.Marshal(reply)
_, _ = nc.Write(append(b, '\n'))
}
if closeAfter {
return
}
}
}(conn)
}
}()
return ln.Addr().String(), func() []mockQMPReq {
mu.Lock()
defer mu.Unlock()
return append([]mockQMPReq(nil), recorded...)
}
}
func TestSuspendToFileHappyPath(t *testing.T) {
polls := 0
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
polls++
if polls == 1 {
return map[string]any{"return": map[string]any{
"status": "active",
"ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048},
}}, false
}
return map[string]any{"return": map[string]any{
"status": "completed",
"total-time": 4500,
"ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048},
}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
var progress []MigrateProgress
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) {
progress = append(progress, p)
}, nil); err != nil {
t.Fatalf("suspendToFileConn: %v", err)
}
if len(progress) != 2 || progress[1].Status != "completed" {
t.Fatalf("unexpected progress: %+v", progress)
}
got := cmds()
var names []string
var sawBandwidthZero, sawChannels, sawDirectIO bool
for _, r := range got {
names = append(names, r.Execute)
if r.Execute == "migrate-set-parameters" {
var params map[string]any
if err := json.Unmarshal(r.Arguments, &params); err != nil {
t.Fatalf("unmarshal migrate-set-parameters: %v", err)
}
if bw, ok := params["max-bandwidth"].(float64); ok && bw == UnlimitedMigrationBandwidth {
sawBandwidthZero = true
}
if ch, ok := params["multifd-channels"].(float64); ok && int(ch) == DefaultMultifdChannels {
sawChannels = true
}
if dio, ok := params["direct-io"].(bool); ok && dio {
sawDirectIO = true
}
}
}
want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate-set-parameters,migrate,query-migrate,query-migrate,quit"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
if !sawBandwidthZero || !sawChannels || !sawDirectIO {
t.Fatalf("expected max-bandwidth=0 (%t), multifd-channels=%d (%t), direct-io=true (%t)",
sawBandwidthZero, DefaultMultifdChannels, sawChannels, sawDirectIO)
}
}
func TestSuspendToFileFallsBackWhenDirectIOUnsupported(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate":
return map[string]any{"return": map[string]any{}}, false
case "migrate-set-parameters":
if strings.Contains(string(req.Arguments), `"direct-io":true`) {
return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "No build-time support for direct-io"}}, false
}
return map[string]any{"return": map[string]any{}}, false
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", "total-time": 1200}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil); err != nil {
t.Fatalf("suspendToFileConn with unsupported direct-io: %v", err)
}
var names []string
for _, r := range cmds() {
names = append(names, r.Execute)
}
want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate-set-parameters,migrate,query-migrate,quit"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
}
func TestSuspendToFileRetriesBufferedOnlyForDirectIOFailures(t *testing.T) {
for _, tc := range []struct {
name string
reason string
retry bool
}{
{"open rejected", "Unable to open 'suspend.vmstate.tmp' with direct I/O", true},
{"write rejected", "Unable to pwritev to file with direct I/O: The parameter is incorrect", true},
{"disk full", "Unable to pwritev to file: The disk is full", false},
} {
t.Run(tc.name, func(t *testing.T) {
attempts := 0
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "migrate":
attempts++
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
if attempts == 1 {
return map[string]any{"return": map[string]any{
"status": "failed", "error-desc": tc.reason,
}}, false
}
return map[string]any{"return": map[string]any{"status": "completed"}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = suspendToFileConn(ctx, c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
wantAttempts := 1
if tc.retry {
wantAttempts = 2
if err != nil {
t.Fatalf("buffered retry failed: %v", err)
}
} else if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), tc.reason) {
t.Fatalf("expected original write error, got %v", err)
}
gotAttempts := 0
var disabledDirectIO, resumed bool
for _, req := range cmds() {
switch req.Execute {
case "migrate":
gotAttempts++
case "migrate-set-parameters":
disabledDirectIO = disabledDirectIO || strings.Contains(string(req.Arguments), `"direct-io":false`)
case "cont":
resumed = true
}
}
if gotAttempts != wantAttempts || disabledDirectIO != tc.retry || resumed == tc.retry {
t.Fatalf("attempts = %d, direct I/O disabled = %t, guest resumed = %t", gotAttempts, disabledDirectIO, resumed)
}
})
}
}
func TestSuspendToFileFailureResumesPausedVM(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "migrate":
return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") {
t.Fatalf("expected disk full error, got %v", err)
}
var sawCont bool
for _, r := range cmds() {
if r.Execute == "cont" {
sawCont = true
}
if r.Execute == "quit" {
t.Fatal("must not quit QEMU when migrate fails")
}
}
if !sawCont {
t.Fatal("expected cont rollback when migrate fails while paused")
}
}
func TestResumeFromFileHappyPath(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil {
t.Fatalf("resumeFromFileConn: %v", err)
}
got := cmds()
var names []string
var sawExitOnErrorFalse, sawBandwidthZero, sawChannels, sawDirectIO bool
for _, r := range got {
names = append(names, r.Execute)
if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) {
sawExitOnErrorFalse = true
}
if r.Execute == "migrate-set-parameters" {
var params map[string]any
if err := json.Unmarshal(r.Arguments, &params); err != nil {
t.Fatalf("unmarshal migrate-set-parameters: %v", err)
}
if bw, ok := params["max-bandwidth"].(float64); ok && bw == UnlimitedMigrationBandwidth {
sawBandwidthZero = true
}
if ch, ok := params["multifd-channels"].(float64); ok && int(ch) == DefaultMultifdChannels {
sawChannels = true
}
if _, ok := params["direct-io"]; ok {
sawDirectIO = true
}
}
}
want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
if !sawExitOnErrorFalse {
t.Fatal("expected migrate-incoming to pass exit-on-error:false")
}
if !sawBandwidthZero || !sawChannels {
t.Fatalf("expected resume max-bandwidth=0 (%t) and multifd-channels=%d (%t)",
sawBandwidthZero, DefaultMultifdChannels, sawChannels)
}
if sawDirectIO {
t.Fatal("resume must keep direct-io disabled to preserve OS read-ahead")
}
}
func TestResumeFromFileFailedDoesNotCont(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil)
if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") {
t.Fatalf("expected corrupt snapshot error, got %v", err)
}
for _, r := range cmds() {
if r.Execute == "cont" {
t.Fatal("must not issue cont when restore failed")
}
}
}