Change Driver.Start to StartRequest/StartResult with a compile-time macOS adapter assertion and registry-to-router coverage. Keep legacy Sidecar name alongside VMRef and grant argument privileges by driver ownership. Move macOS preparation into ReimsMacOSDriver after hook veto, fail preparation errors before launch, and verify veto leaves OpenCore, recovery markers and ledgers unchanged. Unify GUI, CLI and window list/start/stop through internal/lifecycle, select frontend VMs by VMRef, lazily initialize reims only in legacy CLI branches, and cover a second driver through App user entry points.
470 lines
14 KiB
Go
470 lines
14 KiB
Go
// Package driver defines the generic guest VM driver abstraction and router
|
|
// (docs/plugin-architecture.md §5.3). Existing macOS/reims VMs are served by
|
|
// builtin.driver.reims-macos with zero migration.
|
|
package driver
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
)
|
|
|
|
const (
|
|
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
|
|
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
|
|
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
|
|
OwnerMarkerFile = ".reims-go-driver"
|
|
)
|
|
|
|
// Standard VM capability bits (§5.3). UI and CLI gate actions by these bits.
|
|
const (
|
|
CapSnapshot = "snapshot"
|
|
CapCowClone = "cow_clone"
|
|
CapResize = "resize"
|
|
CapQMP = "qmp"
|
|
CapSSH = "ssh"
|
|
CapGuestTools = "guest_tools"
|
|
CapAffinity = "affinity"
|
|
CapOpenCore = "opencore"
|
|
CapRecovery = "recovery"
|
|
CapCloudInit = "cloud_init"
|
|
CapUEFIISO = "uefi_iso"
|
|
)
|
|
|
|
// ValidationIssue reports a field-level validation error before Create/Set.
|
|
type ValidationIssue struct {
|
|
Field string `json:"field"`
|
|
Code string `json:"code,omitempty"`
|
|
Params map[string]any `json:"params,omitempty"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// VMInfo is the generic cross-driver VM model (§5.3).
|
|
type VMInfo struct {
|
|
Name string `json:"name"`
|
|
DriverID string `json:"driver_id"`
|
|
DriverName string `json:"driver_name,omitempty"`
|
|
State string `json:"state"` // "stopped" | "running" | "broken" | "driver_unavailable"
|
|
PID *int `json:"pid,omitempty"`
|
|
CPUs int `json:"cpus,omitempty"`
|
|
Memory string `json:"memory,omitempty"`
|
|
DiskSummary string `json:"disk_summary,omitempty"`
|
|
Directory string `json:"directory,omitempty"`
|
|
Capabilities []string `json:"capabilities,omitempty"`
|
|
DriverData map[string]any `json:"driver_data,omitempty"`
|
|
DriverUnavailable bool `json:"driver_unavailable,omitempty"`
|
|
}
|
|
|
|
// DriverSummary exposes metadata and schemas for the creation wizard and UI.
|
|
type DriverSummary struct {
|
|
ID string `json:"id"`
|
|
Name plugin.LocalizedText `json:"name"`
|
|
RuntimeKind string `json:"runtime_kind"`
|
|
RuntimeAPIRange string `json:"runtime_api_range,omitempty"`
|
|
Capabilities []string `json:"capabilities,omitempty"`
|
|
CreateSchema *plugin.SettingsSchema `json:"create_schema,omitempty"`
|
|
SettingsSchema *plugin.SettingsSchema `json:"settings_schema,omitempty"`
|
|
Builtin bool `json:"builtin,omitempty"`
|
|
}
|
|
|
|
// CreateRequest is a driver-agnostic VM creation request.
|
|
type CreateRequest struct {
|
|
DriverID string `json:"driver_id"`
|
|
Name string `json:"name"`
|
|
Dir string `json:"dir,omitempty"`
|
|
Options map[string]any `json:"options,omitempty"`
|
|
}
|
|
|
|
// SetRequest is a driver-agnostic VM settings update request.
|
|
type SetRequest struct {
|
|
Name string `json:"name"`
|
|
Changes map[string]any `json:"changes,omitempty"`
|
|
}
|
|
|
|
// StartRequest carries a VM reference, third-party start intents and log sinks.
|
|
// Disk preparation belongs to the driver and runs only after hooks have finished.
|
|
type StartRequest struct {
|
|
Ref VMRef
|
|
Intents []plugin.StartIntent
|
|
ActivePlugins map[string]bool
|
|
Stdout io.Writer
|
|
Stderr io.Writer
|
|
}
|
|
|
|
// StartResult contains host-controlled actions to run after a successful start.
|
|
type StartResult struct {
|
|
PostStart []plugin.PostStartAction
|
|
}
|
|
|
|
// Driver is the core contract implemented by both builtin.driver.reims-macos
|
|
// and external L3 Sidecar guest drivers (such as Linux) (§5.3).
|
|
type Driver interface {
|
|
ID() string
|
|
DisplayName() plugin.LocalizedText
|
|
RuntimeKind() string
|
|
RuntimeAPIRange() string
|
|
Capabilities() []string
|
|
CreateSchema() *plugin.SettingsSchema
|
|
SettingsSchema() *plugin.SettingsSchema
|
|
|
|
List(ctx context.Context) ([]VMInfo, error)
|
|
Show(ctx context.Context, name string) (VMInfo, error)
|
|
ValidateCreate(ctx context.Context, req CreateRequest) []ValidationIssue
|
|
Create(ctx context.Context, req CreateRequest, stdout, stderr io.Writer) error
|
|
ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue
|
|
Set(ctx context.Context, req SetRequest, stdout, stderr io.Writer) error
|
|
Start(ctx context.Context, req StartRequest) (StartResult, error)
|
|
Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error
|
|
Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error
|
|
}
|
|
|
|
// ActionDriver is an optional interface for driver-specific commands (snapshots,
|
|
// clones, custom actions) (§5.3).
|
|
type ActionDriver interface {
|
|
InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error)
|
|
}
|
|
|
|
// RenamedDriverIDs maps a driver ID that VM owner markers may still carry
|
|
// to the ID that now provides that driver, for when a driver moves to
|
|
// another plugin (e.g. the built-in macOS driver becoming a market plugin,
|
|
// which cannot keep the reserved "builtin." prefix). Markers are not
|
|
// rewritten, so a downgrade still finds its own ID.
|
|
var RenamedDriverIDs = map[string]string{}
|
|
|
|
// CanonicalDriverID follows RenamedDriverIDs.
|
|
func CanonicalDriverID(id string) string {
|
|
if to, ok := RenamedDriverIDs[id]; ok && to != "" {
|
|
return to
|
|
}
|
|
return id
|
|
}
|
|
|
|
// ReadOwnerDriver returns the owning driver ID recorded in `<vmDir>/.reims-go-driver`.
|
|
// Unmarked legacy VMs automatically belong to builtin.driver.reims-macos (§5.3).
|
|
func ReadOwnerDriver(vmDir string) string {
|
|
if strings.TrimSpace(vmDir) == "" {
|
|
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(vmDir, OwnerMarkerFile))
|
|
if err != nil {
|
|
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
|
|
}
|
|
id := strings.TrimSpace(string(raw))
|
|
if id == "" {
|
|
return CanonicalDriverID(BuiltinReimsMacOSDriverID)
|
|
}
|
|
return CanonicalDriverID(id)
|
|
}
|
|
|
|
// WriteOwnerDriver records driverID in `<vmDir>/.reims-go-driver`.
|
|
func WriteOwnerDriver(vmDir, driverID string) error {
|
|
if strings.TrimSpace(vmDir) == "" || strings.TrimSpace(driverID) == "" {
|
|
return nil
|
|
}
|
|
if err := os.MkdirAll(vmDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
|
|
}
|
|
|
|
// Router aggregates active guest drivers from the plugin Registry and routes
|
|
// VM operations by ownership (§5.3).
|
|
type Router struct {
|
|
reg *plugin.Registry
|
|
dataRootDir func() string // DataRoot for statically declared guest VM roots
|
|
legacyVMRoot func() string // compatibility root for tests and older embedders
|
|
}
|
|
|
|
// NewRouter creates a driver Router backed by reg.
|
|
func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
|
|
return &Router{reg: reg, legacyVMRoot: vmRootDir}
|
|
}
|
|
|
|
// NewRouterWithDataRoot scans only VM roots declared by registered drivers.
|
|
func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string) *Router {
|
|
return &Router{reg: reg, dataRootDir: dataRootDir}
|
|
}
|
|
|
|
func (rt *Router) vmRoots() []string {
|
|
var roots []string
|
|
seen := map[string]bool{}
|
|
add := func(root string) {
|
|
if strings.TrimSpace(root) == "" {
|
|
return
|
|
}
|
|
root = filepath.Clean(root)
|
|
key := strings.ToLower(root)
|
|
if !seen[key] {
|
|
seen[key] = true
|
|
roots = append(roots, root)
|
|
}
|
|
}
|
|
if rt != nil && rt.reg != nil && rt.dataRootDir != nil {
|
|
if base := rt.dataRootDir(); base != "" {
|
|
for _, declarations := range rt.reg.DeclaredVMRoots() {
|
|
for _, rel := range declarations {
|
|
add(filepath.Join(base, filepath.FromSlash(rel)))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if rt != nil && rt.legacyVMRoot != nil {
|
|
add(rt.legacyVMRoot())
|
|
}
|
|
return roots
|
|
}
|
|
|
|
// Drivers returns all active Guest Drivers sorted with builtin first.
|
|
func (rt *Router) Drivers() []Driver {
|
|
if rt == nil || rt.reg == nil {
|
|
return nil
|
|
}
|
|
raw := rt.reg.GuestDrivers()
|
|
var out []Driver
|
|
for _, v := range raw {
|
|
if d, ok := v.(Driver); ok && d != nil {
|
|
out = append(out, d)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
bi := out[i].ID() == BuiltinReimsMacOSDriverID
|
|
bj := out[j].ID() == BuiltinReimsMacOSDriverID
|
|
if bi != bj {
|
|
return bi
|
|
}
|
|
return out[i].ID() < out[j].ID()
|
|
})
|
|
return out
|
|
}
|
|
|
|
// Summaries returns DriverSummary metadata for every active driver.
|
|
func (rt *Router) Summaries() []DriverSummary {
|
|
drvs := rt.Drivers()
|
|
out := make([]DriverSummary, 0, len(drvs))
|
|
for _, d := range drvs {
|
|
out = append(out, DriverSummary{
|
|
ID: d.ID(),
|
|
Name: d.DisplayName(),
|
|
RuntimeKind: d.RuntimeKind(),
|
|
RuntimeAPIRange: d.RuntimeAPIRange(),
|
|
Capabilities: d.Capabilities(),
|
|
CreateSchema: d.CreateSchema(),
|
|
SettingsSchema: d.SettingsSchema(),
|
|
Builtin: d.ID() == BuiltinReimsMacOSDriverID,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// DriverByID returns the active driver for id, or an error if unavailable.
|
|
func (rt *Router) DriverByID(id string) (Driver, error) {
|
|
if strings.TrimSpace(id) == "" {
|
|
id = BuiltinReimsMacOSDriverID
|
|
}
|
|
id = CanonicalDriverID(id)
|
|
if rt == nil || rt.reg == nil {
|
|
return nil, fmt.Errorf("driver %q unavailable: registry not initialized", id)
|
|
}
|
|
raw, ok := rt.reg.GuestDriver(id)
|
|
if !ok {
|
|
return nil, fmt.Errorf("driver %q is unavailable or disabled", id)
|
|
}
|
|
d, ok := raw.(Driver)
|
|
if !ok || d == nil {
|
|
return nil, fmt.Errorf("registered driver %q does not implement Driver", id)
|
|
}
|
|
return d, nil
|
|
}
|
|
|
|
// ListAllVMs merges VM listings from all active drivers and appends any VM
|
|
// directory under vmRootDir whose owning driver is currently unavailable (§4.2, §5.3).
|
|
func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
|
|
seen := make(map[string]bool)
|
|
var out []VMInfo
|
|
for _, d := range rt.Drivers() {
|
|
vms, err := d.List(ctx)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, vm := range vms {
|
|
vm.DriverID = d.ID()
|
|
key := foldedRefKey(vm.DriverID, vm.Name)
|
|
if seen[key] {
|
|
continue
|
|
}
|
|
if len(vm.Capabilities) == 0 {
|
|
vm.Capabilities = d.Capabilities()
|
|
}
|
|
seen[key] = true
|
|
out = append(out, vm)
|
|
}
|
|
}
|
|
|
|
// Declared roots retain VMs whose driver is disabled or missing.
|
|
for _, root := range rt.vmRoots() {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, e := range entries {
|
|
if !e.IsDir() {
|
|
continue
|
|
}
|
|
vmDir := filepath.Join(root, e.Name())
|
|
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err != nil {
|
|
continue
|
|
}
|
|
owner := ReadOwnerDriver(vmDir)
|
|
key := foldedRefKey(owner, e.Name())
|
|
if seen[key] {
|
|
continue
|
|
}
|
|
if _, ok := rt.reg.GuestDriver(owner); ok {
|
|
continue
|
|
}
|
|
seen[key] = true
|
|
out = append(out, VMInfo{
|
|
Name: e.Name(), DriverID: owner, State: "driver_unavailable",
|
|
Directory: vmDir, DriverUnavailable: true,
|
|
})
|
|
}
|
|
}
|
|
|
|
sort.Slice(out, func(i, j int) bool {
|
|
ni, nj := strings.ToLower(out[i].Name), strings.ToLower(out[j].Name)
|
|
if ni != nj {
|
|
return ni < nj
|
|
}
|
|
return out[i].DriverID < out[j].DriverID
|
|
})
|
|
return out, nil
|
|
}
|
|
|
|
// ResolveVM resolves a bare name only when exactly one driver owns it.
|
|
func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, error) {
|
|
type match struct {
|
|
d Driver
|
|
vm VMInfo
|
|
}
|
|
byRef := map[string]match{}
|
|
for _, d := range rt.Drivers() {
|
|
vms, err := d.List(ctx)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, vm := range vms {
|
|
if !strings.EqualFold(vm.Name, vmName) {
|
|
continue
|
|
}
|
|
vm.DriverID = d.ID()
|
|
byRef[foldedRefKey(vm.DriverID, vm.Name)] = match{d: d, vm: vm}
|
|
}
|
|
}
|
|
for _, root := range rt.vmRoots() {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, e := range entries {
|
|
if !e.IsDir() || !strings.EqualFold(e.Name(), vmName) {
|
|
continue
|
|
}
|
|
vmDir := filepath.Join(root, e.Name())
|
|
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err != nil {
|
|
continue
|
|
}
|
|
owner := ReadOwnerDriver(vmDir)
|
|
if _, active := rt.reg.GuestDriver(owner); active {
|
|
continue
|
|
}
|
|
byRef[foldedRefKey(owner, e.Name())] = match{vm: VMInfo{
|
|
Name: e.Name(), DriverID: owner, State: "driver_unavailable",
|
|
Directory: vmDir, DriverUnavailable: true,
|
|
}}
|
|
}
|
|
}
|
|
if len(byRef) == 0 {
|
|
return nil, VMInfo{}, fmt.Errorf("VM %q not found in any active driver", vmName)
|
|
}
|
|
if len(byRef) > 1 {
|
|
ids := make([]string, 0, len(byRef))
|
|
for _, m := range byRef {
|
|
ids = append(ids, m.vm.DriverID)
|
|
}
|
|
sort.Strings(ids)
|
|
return nil, VMInfo{}, &AmbiguousVMError{Name: vmName, DriverIDs: ids}
|
|
}
|
|
for _, m := range byRef {
|
|
if m.d == nil {
|
|
return nil, m.vm, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, m.vm.DriverID)
|
|
}
|
|
return m.d, m.vm, nil
|
|
}
|
|
panic("unreachable")
|
|
}
|
|
|
|
// ResolveRef resolves a VM within an explicit owning driver.
|
|
func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, error) {
|
|
ref = NewVMRef(ref.DriverID, ref.Name)
|
|
d, err := rt.DriverByID(ref.DriverID)
|
|
if err == nil {
|
|
vm, showErr := d.Show(ctx, ref.Name)
|
|
if showErr != nil {
|
|
return nil, VMInfo{}, showErr
|
|
}
|
|
vm.DriverID = d.ID()
|
|
return d, vm, nil
|
|
}
|
|
for _, root := range rt.vmRoots() {
|
|
vmDir := filepath.Join(root, ref.Name)
|
|
if _, statErr := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); statErr != nil {
|
|
continue
|
|
}
|
|
if ReadOwnerDriver(vmDir) == ref.DriverID {
|
|
return nil, VMInfo{Name: ref.Name, DriverID: ref.DriverID, State: "driver_unavailable", Directory: vmDir, DriverUnavailable: true}, err
|
|
}
|
|
}
|
|
return nil, VMInfo{}, err
|
|
}
|
|
|
|
// CheckDriverInUse returns true if any VM belongs to driverID (fail-closed on list error, §4.1).
|
|
func (rt *Router) CheckDriverInUse(ctx context.Context, driverID string) (bool, string, error) {
|
|
if rt == nil || rt.reg == nil {
|
|
return false, "", errors.New("driver router not initialized")
|
|
}
|
|
if raw, ok := rt.reg.GuestDriver(driverID); ok {
|
|
if d, ok := raw.(Driver); ok && d != nil {
|
|
vms, err := d.List(ctx)
|
|
if err != nil {
|
|
return true, "", err
|
|
}
|
|
if len(vms) > 0 {
|
|
return true, fmt.Sprintf("%d VM(s) owned by %s", len(vms), driverID), nil
|
|
}
|
|
}
|
|
}
|
|
for _, root := range rt.vmRoots() {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, e := range entries {
|
|
if !e.IsDir() {
|
|
continue
|
|
}
|
|
vmDir := filepath.Join(root, e.Name())
|
|
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err == nil && ReadOwnerDriver(vmDir) == driverID {
|
|
return true, fmt.Sprintf("VM %s owned by %s", e.Name(), driverID), nil
|
|
}
|
|
}
|
|
}
|
|
return false, "", nil
|
|
}
|