diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 8cfd783..ea960b6 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -63,8 +63,7 @@ func (a *App) SuspendVM(name string) error { } lastPct := -1 info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) { - if p.Total > 0 { - pct := int(p.Transferred * 100 / p.Total) + if pct, ok := suspendProgressPercent(p); ok { if pct >= lastPct+25 || p.Status == "completed" { lastPct = pct a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct)) @@ -189,6 +188,29 @@ func (a *App) beginSuspendTransition(name, state string) (func(), error) { }, nil } +func suspendProgressPercent(p qmp.MigrateProgress) (int, bool) { + if p.Status == "completed" { + return 100, true + } + if p.Total <= 0 { + return 0, false + } + // With mapped-ram, zero pages are skipped so Transferred stays below Total; + // Total - Remaining tracks actual scan/save completion across all RAM. + done := p.Total - p.Remaining + if done < 0 { + done = 0 + } + if done > p.Total { + done = p.Total + } + pct := int(done * 100 / p.Total) + if pct >= 100 { + pct = 99 + } + return pct, true +} + func (a *App) emitStateChanged() { if a.ctx != nil { wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go index a102794..76d8554 100644 --- a/internal/app/suspend_flow_test.go +++ b/internal/app/suspend_flow_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" ) @@ -63,3 +64,25 @@ func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) { t.Fatalf("stripLegacyManagedExtraArgs = %q", got) } } + +func TestSuspendProgressPercentTracksRemainingAcrossSparseRAM(t *testing.T) { + cases := []struct { + name string + prog qmp.MigrateProgress + pct int + ok bool + }{ + {"setup", qmp.MigrateProgress{Status: "setup"}, 0, false}, + {"active sparse", qmp.MigrateProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true}, + {"device stage caps below 100", qmp.MigrateProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true}, + {"completed always 100", qmp.MigrateProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + pct, ok := suspendProgressPercent(tc.prog) + if pct != tc.pct || ok != tc.ok { + t.Fatalf("suspendProgressPercent(%+v) = (%d, %t), want (%d, %t)", tc.prog, pct, ok, tc.pct, tc.ok) + } + }) + } +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go index 69b2ef8..4eb5fe0 100644 --- a/internal/qmp/migrate.go +++ b/internal/qmp/migrate.go @@ -13,9 +13,14 @@ import ( const ( // DefaultMultifdChannels is the parallel I/O channel count used for // mapped-ram file snapshots on Windows. - DefaultMultifdChannels = 4 + DefaultMultifdChannels = 8 - migratePollInterval = 200 * time.Millisecond + // 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 ) @@ -118,7 +123,8 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr return fmt.Errorf("VM remained running after stop (status=%s)", st.Status) } - if err := configureMappedRAM(c); err != nil { + directIO, err := configureMappedRAM(c, true) + if err != nil { tryResumePaused(c) return err } @@ -126,22 +132,21 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr args := map[string]any{ "channels": fileChannels(vmstatePath), } - if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { - var rejected *commandError - if errors.As(err, &rejected) { - tryResumePaused(c) - return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err) + err = runSuspendMigration(ctx, c, args, onProgress) + if err != nil && directIO && 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) + } } - 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) { + if err != nil { + if errors.Is(err, ErrIncompleteSuspend) { tryResumePaused(c) - return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err) } - return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)} + return err } if seal != nil { if err := seal(c); err != nil { @@ -182,7 +187,9 @@ func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress f } func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { - if err := configureMappedRAM(c); err != nil { + // 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{ @@ -215,7 +222,7 @@ func QuitVM(ctx context.Context, vmDir string) error { return nil } -func configureMappedRAM(c *Conn) error { +func configureMappedRAM(c *Conn, enableDirectIO bool) (bool, error) { caps := map[string]any{ "capabilities": []map[string]any{ {"capability": "mapped-ram", "state": true}, @@ -223,15 +230,28 @@ func configureMappedRAM(c *Conn) error { }, } if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil { - return fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err) + 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 fmt.Errorf("set multifd-channels: %w", err) + return false, fmt.Errorf("set migration parameters: %w", err) } - return nil + 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 { @@ -358,6 +378,32 @@ func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout } } +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 { + if err == nil { + return false + } + 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 diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go index 4a1b8bb..36d46e9 100644 --- a/internal/qmp/migrate_test.go +++ b/internal/qmp/migrate_test.go @@ -263,13 +263,124 @@ func TestSuspendToFileHappyPath(t *testing.T) { } 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, ¶ms); 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,query-migrate,query-migrate,quit" + 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 TestSuspendToFileRetriesBufferedOnDirectIOVolumeFailure(t *testing.T) { + migrateAttempts := 0 + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters": + 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": + migrateAttempts++ + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + if migrateAttempts == 1 { + return map[string]any{"return": map[string]any{ + "status": "failed", + "error-desc": "Unable to open 'suspend.vmstate.tmp' with direct I/O", + }}, false + } + return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1500}}, 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 direct-io fallback: %v", err) + } + if migrateAttempts != 2 { + t.Fatalf("migrate attempts = %d, want 2", migrateAttempts) + } + var sawDisableDirectIO bool + for _, r := range cmds() { + if r.Execute == "migrate-set-parameters" && strings.Contains(string(r.Arguments), `"direct-io":false`) { + sawDisableDirectIO = true + } + } + if !sawDisableDirectIO { + t.Fatal("expected retry to explicitly disable direct-io") + } } func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { @@ -334,12 +445,27 @@ func TestResumeFromFileHappyPath(t *testing.T) { } got := cmds() var names []string - var sawExitOnErrorFalse bool + 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, ¶ms); 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 { @@ -348,6 +474,13 @@ func TestResumeFromFileHappyPath(t *testing.T) { 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) {