Files
Reims-Go/internal/console/manager.go
T
2026-12-03 21:31:11 -07:00

434 lines
12 KiB
Go

// Package console serializes host-owned QMP console operations per VM.
package console
import (
"context"
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/qmp"
)
const vmLifecycleLockFile = ".reims-go-vm-operation.lock"
// Manager arbitrates screen and input operations so concurrent host features
// never open competing QMP clients for the same VM.
type Manager struct {
mu sync.Mutex
locks map[string]*vmLock
dial func(context.Context, string) (qmpSession, error)
}
type vmLock struct {
semaphore chan struct{}
users int
}
type lockScopeKey struct{}
type lockScope struct {
manager *Manager
key string
active atomic.Bool
}
type qmpSession interface {
qmp.Executor
qmp.QueryExecutor
Screendump(string) (string, error)
Close() error
}
func NewManager() *Manager {
return &Manager{
locks: make(map[string]*vmLock),
dial: func(ctx context.Context, vmDir string) (qmpSession, error) {
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
},
}
}
// WithVM serializes a lifecycle operation with computer-use requests for the
// same VM. Nested operations inherit the lock scope through their context.
func (m *Manager) WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
return m.withVM(ctx, vmDir, operation)
}
// Forget is retained for lifecycle hooks. Each QMP operation closes its
// connection before returning, so no session remains to release.
func (m *Manager) Forget(_ context.Context, _ string) error {
return nil
}
// Close is retained for the service lifecycle. The manager owns no persistent
// QMP connections.
func (m *Manager) Close() {
}
// Screendump writes one PPM frame while holding the VM's console lock.
func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, error) {
var format string
err := m.withConn(ctx, vmDir, func(conn qmpSession) error {
var err error
format, err = conn.Screendump(path)
return err
})
return format, err
}
// ScreendumpDisplay selects a specific guest display under the same console lock.
func (m *Manager) ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error) {
var format string
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
var err error
format, err = qmp.ScreendumpDisplay(conn, path, device, head)
return err
})
return format, err
}
// TypeText sends US-layout key strokes as one serialized console job.
func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
strokes, err := qmp.Strokes(text)
if err != nil {
return 0, err
}
if len(strokes) == 0 {
return 0, errors.New("nothing to type")
}
done := 0
err = m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.TypeStrokes(ctx, conn, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
done = n
if progress != nil {
progress(n, len(strokes))
}
})
})
return done, err
}
// SendAbsoluteClickAndPaste clicks at normalized coordinates and presses Command+V
// while holding the VM's exclusive console lock.
func (m *Manager) SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
if focusWait <= 0 {
focusWait = 120 * time.Millisecond
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ClickAndPaste(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
})
}
// SendPasteShortcut sends Command+V through the same exclusive console path.
func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error {
return m.SendPasteShortcutCombo(ctx, vmDir, "")
}
// SendPasteShortcutCombo presses a guest's paste combination (such as
// "ctrl+shift+v") through the exclusive console path; an empty combo means
// the macOS default.
func (m *Manager) SendPasteShortcutCombo(ctx context.Context, vmDir, combo string) error {
if strings.TrimSpace(combo) == "" {
combo = qmp.DefaultPasteCombo
}
key, modifiers, err := qmp.ParseKeyCombo(combo)
if err != nil {
return err
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, modifiers...)
})
}
func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) {
var available bool
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
mice, err := qmp.QueryMice(conn)
if err == nil {
available = qmp.HasCurrentAbsoluteMouse(mice)
}
return err
})
return available, err
}
func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseMove(conn, x, y, width, height)
})
}
func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseButton(conn, button, down)
})
}
func (m *Manager) MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseButtonAt(conn, x, y, width, height, button, down)
})
}
func (m *Manager) SendKey(ctx context.Context, vmDir, key string, down bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.SendKey(conn, key, down)
})
}
func (m *Manager) ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ReleaseInputs(conn, keys, buttons)
})
}
func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
if err := qmp.MouseButton(conn, button, true); err != nil {
return err
}
released := false
defer func() {
if !released {
_ = qmp.MouseButton(conn, button, false)
}
}()
timer := time.NewTimer(50 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
if err := qmp.MouseButton(conn, button, false); err != nil {
return err
}
released = true
return nil
})
}
func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error {
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.MouseScroll(conn, delta, horizontal)
})
}
func (m *Manager) PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error {
key, err := normalizeKeyCode(key)
if err != nil {
return err
}
normalizedModifiers := make([]string, len(modifiers))
for i, modifier := range modifiers {
normalizedModifiers[i], err = normalizeModifier(modifier)
if err != nil {
return err
}
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.PressCombo(ctx, conn, 25*time.Millisecond, key, normalizedModifiers...)
})
}
func normalizeKeyCode(key string) (string, error) {
if key == " " {
return "spc", nil
}
code := strings.ToLower(strings.TrimSpace(key))
switch code {
case "space":
code = "spc"
case "escape":
code = "esc"
case "enter", "return":
code = "ret"
case "pageup":
code = "page_up"
case "pagedown":
code = "page_down"
}
if code == "" {
return "", errors.New("key is required")
}
for _, r := range code {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
return "", fmt.Errorf("unsupported key code %q", key)
}
}
return code, nil
}
func normalizeModifier(modifier string) (string, error) {
code := strings.ToLower(strings.TrimSpace(modifier))
switch code {
case "cmd", "command", "meta", "super":
code = "meta_l"
case "ctrl", "control":
code = "ctrl"
case "option":
code = "alt"
}
switch code {
case "shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "meta_l", "meta_r":
return code, nil
default:
return "", fmt.Errorf("unsupported key modifier %q", modifier)
}
}
func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
return m.withConnMode(ctx, vmDir, false, operation)
}
// Single-command operations can close their connection on cancellation.
// Multi-command jobs need it to release any held guest keys or buttons.
func (m *Manager) withCancelableConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
return m.withConnMode(ctx, vmDir, true, operation)
}
func (m *Manager) withConnMode(ctx context.Context, vmDir string, cancelIO bool, operation func(qmpSession) error) error {
if operation == nil {
return errors.New("console operation is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return err
}
nested := m.hasLockScope(ctx, key)
release, err := m.acquire(ctx, vmDir)
if err != nil {
return err
}
defer release()
if !nested {
unlockFile, err := filelock.Acquire(ctx, filepath.Join(vmDir, vmLifecycleLockFile), 25*time.Millisecond)
if err != nil {
return err
}
defer unlockFile()
}
// QEMU serves one QMP client at a time. Keep both locks through this
// short-lived connection and close it before releasing them.
dial := m.dial
if dial == nil {
dial = func(ctx context.Context, vmDir string) (qmpSession, error) {
return qmp.Dial(ctx, "unix", qmp.SocketPath(vmDir))
}
}
conn, err := dial(ctx, vmDir)
if err != nil {
return err
}
closeConn := sync.OnceFunc(func() { _ = conn.Close() })
defer closeConn()
if cancelIO {
stopCancel := context.AfterFunc(ctx, closeConn)
defer stopCancel()
}
return operation(conn)
}
func (m *Manager) withVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
if operation == nil {
return errors.New("console operation is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return err
}
if m.hasLockScope(ctx, key) {
return operation(ctx)
}
release, err := m.acquire(ctx, vmDir)
if err != nil {
return err
}
defer release()
scope := &lockScope{manager: m, key: key}
scope.active.Store(true)
defer scope.active.Store(false)
return operation(context.WithValue(ctx, lockScopeKey{}, scope))
}
func (m *Manager) acquire(ctx context.Context, vmDir string) (func(), error) {
if m == nil {
return nil, errors.New("console manager is unavailable")
}
if ctx == nil {
return nil, errors.New("console context is unavailable")
}
key, err := lockKey(vmDir)
if err != nil {
return nil, err
}
if m.hasLockScope(ctx, key) {
return func() {}, nil
}
m.mu.Lock()
if m.locks == nil {
m.locks = make(map[string]*vmLock)
}
lock := m.locks[key]
if lock == nil {
lock = &vmLock{semaphore: make(chan struct{}, 1)}
m.locks[key] = lock
}
lock.users++
m.mu.Unlock()
select {
case lock.semaphore <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() {
<-lock.semaphore
m.release(key, lock)
})
}, nil
case <-ctx.Done():
m.release(key, lock)
return nil, ctx.Err()
}
}
func (m *Manager) hasLockScope(ctx context.Context, key string) bool {
if ctx == nil {
return false
}
scope, ok := ctx.Value(lockScopeKey{}).(*lockScope)
return ok && scope.manager == m && scope.key == key && scope.active.Load()
}
func (m *Manager) release(key string, lock *vmLock) {
m.mu.Lock()
defer m.mu.Unlock()
lock.users--
if lock.users == 0 && m.locks[key] == lock {
delete(m.locks, key)
}
}
func lockKey(vmDir string) (string, error) {
if strings.TrimSpace(vmDir) == "" {
return "", errors.New("VM directory is unavailable")
}
abs, err := filepath.Abs(vmDir)
if err != nil {
return "", fmt.Errorf("resolve VM directory: %w", err)
}
key := filepath.Clean(abs)
if runtime.GOOS == "windows" {
key = strings.ToLower(key)
}
return key, nil
}