Every VM action had two bindings: one by name and one by driver and name. The window used only the second, so the first is gone and the WithDriver suffix with it. Unused bindings and frontend exports are removed too. Tests now reject bindings the window never calls, stale generated bindings and unused frontend exports. TypeScript rejects unused locals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
289 lines
8.1 KiB
Go
289 lines
8.1 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
)
|
|
|
|
// SuspendVM saves a VM's running state and closes its QEMU process.
|
|
func (a *App) SuspendVM(driverID, name string) error {
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
svc, gt := a.lifecycleSvc, a.guestTools
|
|
a.mu.Unlock()
|
|
if svc == nil {
|
|
return errors.New("driver lifecycle is not initialized")
|
|
}
|
|
ctx := a.baseCtx()
|
|
_, vm, err := svc.Resolve(ctx, driverID, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ref := vm.Ref()
|
|
key := ref.Key()
|
|
end, err := a.beginSuspendTransition(key, ref.Name, "suspending")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer end()
|
|
|
|
lastPct := -1
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
|
var res driver.SuspendResult
|
|
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
|
var suspendErr error
|
|
res, suspendErr = svc.Suspend(operationCtx, ref, func(p driver.SuspendProgress) {
|
|
if pct, ok := suspendProgressPercent(p); ok {
|
|
if pct >= lastPct+25 || p.Status == "completed" {
|
|
lastPct = pct
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
|
}
|
|
}
|
|
}, w, w)
|
|
return suspendErr
|
|
})
|
|
if err != nil {
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Suspend error: "+err.Error())
|
|
return err
|
|
}
|
|
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
|
a.cancelRebootWatcherKey(key)
|
|
stopVMMonitor(ref.Name)
|
|
a.stopPacketBridge(ref.Name)
|
|
}
|
|
if gt != nil {
|
|
gt.UnregisterVM(key)
|
|
}
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", ref.Name, float64(res.VMStateSize)/float64(1<<30)))
|
|
return nil
|
|
}
|
|
|
|
// ResumeVM restores a suspended VM with its original media and devices.
|
|
func (a *App) ResumeVM(driverID, name string) error {
|
|
if err := a.beginVMStart(); err != nil {
|
|
return err
|
|
}
|
|
defer a.vmStarts.Done()
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
cfgCopy := *a.cfg
|
|
a.mu.Unlock()
|
|
if svc == nil {
|
|
return errors.New("driver lifecycle is not initialized")
|
|
}
|
|
ctx := a.baseCtx()
|
|
_, vm, err := svc.Resolve(ctx, driverID, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ref := vm.Ref()
|
|
key := ref.Key()
|
|
end, err := a.beginSuspendTransition(key, ref.Name, "resuming")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer end()
|
|
|
|
var extraEnv []string
|
|
var newRegistration *guesttools.Server
|
|
var newRegGen uint64
|
|
var epoch uint64
|
|
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
|
a.cancelRebootWatcherKey(key)
|
|
epoch = a.vmDeleteEpoch(ref.Name)
|
|
active, rerr := rt.ResolveActive(&cfgCopy)
|
|
hasRuntime := rerr == nil && active != nil
|
|
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
|
|
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
|
|
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop)
|
|
if unicodeInput && len(extraEnv) > 0 {
|
|
a.syncKeymapRules()
|
|
}
|
|
}
|
|
|
|
startAt := time.Now()
|
|
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
|
var result driver.StartResult
|
|
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
|
var resumeErr error
|
|
result, resumeErr = svc.Resume(operationCtx, ref, extraEnv, w, w)
|
|
return resumeErr
|
|
})
|
|
if err != nil {
|
|
if newRegistration != nil && newRegGen > 0 {
|
|
unlock := a.lockGuestToolsVM(ref.Name)
|
|
if a.vmDeleteEpoch(ref.Name) == epoch {
|
|
newRegistration.UnregisterVMIfGen(key, newRegGen)
|
|
}
|
|
unlock()
|
|
}
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
|
|
return err
|
|
}
|
|
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
|
for _, action := range result.PostStart {
|
|
if action.Kind != "qmp.watch_cold_reboot" {
|
|
continue
|
|
}
|
|
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
|
|
a.watchWin10ColdReboot(ref.Name, addr)
|
|
}
|
|
}
|
|
a.startVMMonitor(ref.Name, vm, startAt)
|
|
}
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Resumed %s in %.1fs", ref.Name, time.Since(startAt).Seconds()))
|
|
return nil
|
|
}
|
|
|
|
func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeInput, windowDrop bool) ([]string, *guesttools.Server, uint64) {
|
|
ref := vm.Ref()
|
|
unlock := a.lockGuestToolsVM(ref.Name)
|
|
defer unlock()
|
|
if a.vmDeleteEpoch(ref.Name) != epoch {
|
|
return nil, nil, 0
|
|
}
|
|
cfg, configured, err := guesttools.ReadVMConfigStrict(vm.Directory)
|
|
if err != nil {
|
|
a.emitLog(ref.Name, "Warning: could not load Guest Tools config: "+err.Error())
|
|
return nil, nil, 0
|
|
}
|
|
if !configured {
|
|
return nil, nil, 0
|
|
}
|
|
if err := requireGuestToolsVM(vm.Directory); err != nil {
|
|
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
|
|
return nil, nil, 0
|
|
}
|
|
srv, port, err := a.ensureGuestToolsBridge()
|
|
if err != nil {
|
|
return nil, nil, 0
|
|
}
|
|
existing := srv.HasVM(ref.Key())
|
|
oldName := cfg.VMName
|
|
cfg.VMName = ref.Name
|
|
oldDir := cfg.SharedDir
|
|
windowBridge := unicodeInput || windowDrop
|
|
if windowBridge || cfg.SharedDir == "" {
|
|
cfg.SharedDir = a.vmSharedDir(ref.Name)
|
|
}
|
|
if cfg.Port != port || (windowBridge && (oldName != cfg.VMName || oldDir != cfg.SharedDir)) {
|
|
cfg.Port = port
|
|
if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil {
|
|
a.emitLog(ref.Name, "Warning: could not save Guest Tools config: "+err.Error())
|
|
return nil, nil, 0
|
|
}
|
|
}
|
|
if err := a.registerGuestToolsConfig(srv, vm.Directory, cfg); err != nil {
|
|
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
|
|
return nil, nil, 0
|
|
}
|
|
|
|
var newRegistration *guesttools.Server
|
|
var newRegGen uint64
|
|
if !existing {
|
|
newRegistration = srv
|
|
newRegGen = srv.RegistrationGen(ref.Key())
|
|
}
|
|
var env []string
|
|
if unicodeInput {
|
|
srv.SetKeymapCarrier(ref.Name, false)
|
|
env = append(env,
|
|
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
|
|
"REIMS_GO_INPUT_TOKEN="+cfg.Token,
|
|
)
|
|
}
|
|
if windowDrop {
|
|
if token := srv.HostDropToken(ref.DriverID, ref.Name); token != "" {
|
|
env = append(env,
|
|
fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port),
|
|
"REIMS_GO_DROP_TOKEN="+token,
|
|
)
|
|
}
|
|
}
|
|
return env, newRegistration, newRegGen
|
|
}
|
|
|
|
// DiscardSuspend deletes a stopped VM's saved execution state.
|
|
func (a *App) DiscardSuspend(driverID, name string) error {
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
if svc == nil {
|
|
return errors.New("driver lifecycle is not initialized")
|
|
}
|
|
ctx := a.baseCtx()
|
|
_, vm, err := svc.Resolve(ctx, driverID, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ref := vm.Ref()
|
|
if err := svc.DiscardSuspend(ctx, ref); err != nil {
|
|
return err
|
|
}
|
|
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Discarded suspend state for "+ref.Name)
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
return nil
|
|
}
|
|
|
|
func (a *App) beginSuspendTransition(key, displayName, state string) (func(), error) {
|
|
a.mu.Lock()
|
|
loc := a.cfg.Locale
|
|
if a.transitions[key] != "" {
|
|
a.mu.Unlock()
|
|
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": displayName}, nil)
|
|
}
|
|
a.transitions[key] = state
|
|
a.mu.Unlock()
|
|
a.emitStateChanged()
|
|
return func() {
|
|
a.mu.Lock()
|
|
delete(a.transitions, key)
|
|
a.mu.Unlock()
|
|
a.wakePoll()
|
|
a.emitStateChanged()
|
|
}, nil
|
|
}
|
|
|
|
func suspendProgressPercent(p driver.SuspendProgress) (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
|
|
}
|
|
|
|
// Keep context import used cleanly for future cancellation hooks.
|
|
var _ context.Context
|