The data folder had no record of which layout wrote it, so a new release could not tell old data from current data. <DataRoot>\.reims-go-data.json now records data_version and the app version that last raised it. It is kept out of reims-go.json, which is rewritten whole on every save and would drop the field under an older build. Each build carries every step from older layouts to its own; the GUI and CLI run them in order before reading the folder, so users can jump straight from any old version. A failed step leaves the version at the last success and resumes next launch; a folder from a newer build is left untouched. Step v1 writes the driver ownership marker into every reims-ctl VM. driver.RenamedDriverIDs maps old driver IDs to new ones for when a driver moves to another plugin; markers are not rewritten, so downgrades still resolve. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
362 lines
12 KiB
Go
362 lines
12 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"`
|
|
}
|
|
|
|
// 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, name string, stdout, stderr io.Writer) 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
|
|
vmRootDir func() string // optional directory to scan orphaned/unavailable driver VMs
|
|
}
|
|
|
|
// NewRouter creates a driver Router backed by reg.
|
|
func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
|
|
return &Router{reg: reg, vmRootDir: vmRootDir}
|
|
}
|
|
|
|
// 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 {
|
|
key := strings.ToLower(vm.Name)
|
|
if seen[key] {
|
|
continue
|
|
}
|
|
vm.DriverID = d.ID()
|
|
if len(vm.Capabilities) == 0 {
|
|
vm.Capabilities = d.Capabilities()
|
|
}
|
|
seen[key] = true
|
|
out = append(out, vm)
|
|
}
|
|
}
|
|
|
|
// Scan vmRootDir for VMs whose driver is disabled/missing so they show as
|
|
// driver_unavailable without breaking other VMs (§4.2).
|
|
if rt.vmRootDir != nil {
|
|
root := rt.vmRootDir()
|
|
if root != "" {
|
|
if entries, err := os.ReadDir(root); err == nil {
|
|
for _, e := range entries {
|
|
if !e.IsDir() || seen[strings.ToLower(e.Name())] {
|
|
continue
|
|
}
|
|
vmDir := filepath.Join(root, e.Name())
|
|
markerPath := filepath.Join(vmDir, OwnerMarkerFile)
|
|
if _, err := os.Stat(markerPath); err != nil {
|
|
continue
|
|
}
|
|
owner := ReadOwnerDriver(vmDir)
|
|
if _, ok := rt.reg.GuestDriver(owner); !ok {
|
|
out = append(out, VMInfo{
|
|
Name: e.Name(),
|
|
DriverID: owner,
|
|
State: "driver_unavailable",
|
|
Directory: vmDir,
|
|
DriverUnavailable: true,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
|
return out, nil
|
|
}
|
|
|
|
// ResolveVM finds the active driver owning vmName.
|
|
func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, error) {
|
|
for _, d := range rt.Drivers() {
|
|
vms, err := d.List(ctx)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, vm := range vms {
|
|
if vm.Name == vmName {
|
|
vm.DriverID = d.ID()
|
|
return d, vm, nil
|
|
}
|
|
}
|
|
}
|
|
// Check whether it exists as an unavailable-driver VM.
|
|
if rt.vmRootDir != nil && vmName != "" && vmName != "." && vmName != ".." && !strings.ContainsAny(vmName, `/\`) && filepath.Base(vmName) == vmName {
|
|
if root := rt.vmRootDir(); root != "" {
|
|
vmDir := filepath.Join(root, vmName)
|
|
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err == nil {
|
|
owner := ReadOwnerDriver(vmDir)
|
|
return nil, VMInfo{
|
|
Name: vmName,
|
|
DriverID: owner,
|
|
State: "driver_unavailable",
|
|
Directory: vmDir,
|
|
DriverUnavailable: true,
|
|
}, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, owner)
|
|
}
|
|
}
|
|
}
|
|
return nil, VMInfo{}, fmt.Errorf("VM %q not found in any active driver", vmName)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
}
|
|
}
|
|
if rt.vmRootDir != nil {
|
|
if root := rt.vmRootDir(); root != "" {
|
|
if entries, err := os.ReadDir(root); err == nil {
|
|
for _, e := range entries {
|
|
if !e.IsDir() {
|
|
continue
|
|
}
|
|
vmDir := filepath.Join(root, e.Name())
|
|
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err == nil {
|
|
if ReadOwnerDriver(vmDir) == driverID {
|
|
return true, fmt.Sprintf("VM %s owned by %s", e.Name(), driverID), nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return false, "", nil
|
|
}
|