Files
Reims-Go/internal/driver/driver.go
T
NwflowerandClaude Opus 5.5 44e2174fff fix: harden guest driver host APIs
- run elevated actions as fixed System32 tools instead of a hidden subcommand
- require a SHA-256 for plugin downloads
- keep records of secret files that could not be deleted, and never overwrite
  files the host did not create
- stop two concurrent requests from starting the same VM
- drop invalid endpoints instead of failing the whole VM list, and reject ssh
  users and IPv6 zones that could inject command-line text
- accept driver screenshots only at the requested path
- do not treat an unreadable guest phase as normal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:07:46 -07:00

757 lines
24 KiB
Go

// Package driver defines the generic guest VM driver contract and router.
package driver
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/host"
"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"
CapSuspend = "suspend"
// CapHosted marks VMs the driver runs itself: the host does not spawn,
// watch, pin or window-manage a process for them.
CapHosted = "hosted"
CapConsole = "console"
CapTPM = "tpm"
CapRDP = "rdp"
CapADB = "adb"
CapUnattended = "unattended"
)
// HasCapability reports whether caps contains capability.
func HasCapability(caps []string, capability string) bool {
for _, c := range caps {
if c == capability {
return true
}
}
return false
}
// IsHosted reports whether caps marks a driver-hosted VM.
func IsHosted(caps []string) bool { return HasCapability(caps, CapHosted) }
// Guest OS families reported in GuestOSInfo.Family.
const (
GuestFamilyMacOS = "macos"
GuestFamilyLinux = "linux"
GuestFamilyWindows = "windows"
GuestFamilyAndroid = "android"
)
// GuestOSInfo describes the guest operating system of a VM.
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
// Guest phases reported by PhaseReporter and VMInfo.Phase.
const (
PhaseNormal = "normal"
PhaseInstaller = "installer"
PhaseRecovery = "recovery"
)
// PhaseReporter is an optional interface for drivers that can tell whether a
// VM is in its normal, installer or recovery phase.
type PhaseReporter interface {
Phase(ctx context.Context, name string) (string, error)
}
// DriverMetadata is an optional interface exposing manifest-level console
// metadata of a driver.
type DriverMetadata interface {
ConsoleEndpoint() string
PasteCombo() string
Keymap() string
}
// 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"`
}
// VMListItem is the poll-facing process and state summary shared with the UI.
type VMListItem struct {
Name string `json:"name"`
DriverID string `json:"driver_id,omitempty"`
Dir string `json:"dir"`
PID *int `json:"pid"`
State string `json:"state"`
Capabilities []string `json:"capabilities,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
Phase string `json:"phase,omitempty"`
Ready *bool `json:"ready,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
}
// 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"`
DiskPath string `json:"disk_path,omitempty"`
Directory string `json:"directory,omitempty"`
Network bool `json:"network,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
DriverData map[string]any `json:"driver_data,omitempty"`
DriverUnavailable bool `json:"driver_unavailable,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
Phase string `json:"phase,omitempty"`
// Ready tells whether the guest finished booting; nil means unknown.
Ready *bool `json:"ready,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,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"`
ConsoleEndpoint string `json:"console_endpoint,omitempty"`
PasteCombo string `json:"paste_combo,omitempty"`
Keymap string `json:"keymap,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
}
// OptimizationAdvisor lets a driver add guest/runtime-specific recommendations
// to the host's generic facts. Startup preparation remains in the same driver.
type OptimizationAdvisor interface {
EvaluateOptimizations(context.Context, host.Report) []host.Optimization
}
// 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)
}
// LogDriver exposes driver-owned serial and QEMU logs.
type LogDriver interface {
ReadLogs(context.Context, string, bool) (string, error)
}
// SuspendProgress reports incremental progress while saving VM execution state.
type SuspendProgress struct {
Status string
Transferred int64
Remaining int64
Total int64
}
// SuspendRequest carries a VM reference, optional progress callback, and log sinks.
type SuspendRequest struct {
Ref VMRef
Progress func(SuspendProgress)
Stdout io.Writer
Stderr io.Writer
}
// SuspendResult describes the saved suspend snapshot produced by Suspend.
type SuspendResult struct {
VMStateSize int64
SavedAt string
}
// ResumeRequest carries a VM reference, host-side process environment overrides,
// and log sinks for restoring a suspended VM.
type ResumeRequest struct {
Ref VMRef
ExtraEnv []string
Stdout io.Writer
Stderr io.Writer
}
// SuspendDriver is an optional interface for drivers that support saving and
// restoring live VM execution state across host restarts.
type SuspendDriver interface {
Suspend(ctx context.Context, req SuspendRequest) (SuspendResult, error)
Resume(ctx context.Context, req ResumeRequest) (StartResult, error)
DiscardSuspend(ctx context.Context, name string) 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)
}
// HostedReportMaxAge is how long a driver-pushed state counts as fresh; past
// it the host asks the driver with `driver/show` while listing.
const HostedReportMaxAge = 15 * time.Second
// 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
inventories []VMInventory
states *StateTable
}
// SetStateTable attaches the table of driver-reported VM states that
// ListAllVMs and ResolveRef merge into what drivers return.
func (rt *Router) SetStateTable(t *StateTable) {
if rt != nil {
rt.states = t
}
}
// StateTable returns the attached reported-state table, if any.
func (rt *Router) StateTable() *StateTable {
if rt == nil {
return nil
}
return rt.states
}
// VMInventory exposes persisted registrations without invoking a guest driver.
type VMInventory struct {
DriverID string
List func(dataRoot string) ([]VMInfo, error)
}
// NewRouter creates a driver Router backed by reg.
func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
return &Router{reg: reg, legacyVMRoot: vmRootDir}
}
// NewRouterWithDataRoot discovers unavailable VMs through driver inventories
// or through ownership markers in declared roots.
func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router {
return &Router{reg: reg, dataRootDir: dataRootDir, inventories: inventories}
}
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 {
s := 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,
}
if md, ok := d.(DriverMetadata); ok {
s.ConsoleEndpoint, s.PasteCombo, s.Keymap = md.ConsoleEndpoint(), md.PasteCombo(), md.Keymap()
}
out = append(out, s)
}
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
// under declared VM roots whose owning driver is currently unavailable.
func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
seen := make(map[string]bool)
var out []VMInfo
var errs []error
for _, d := range rt.Drivers() {
fetchedAt := time.Now()
vms, err := d.List(ctx)
if err != nil {
errs = append(errs, fmt.Errorf("list VMs for driver %q: %w", d.ID(), err))
}
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()
}
// A hosted VM has no process the host can look at. A driver that has
// not pushed its state lately is asked with `driver/show`, which
// carries what a list entry may leave out (endpoints, readiness).
if IsHosted(vm.Capabilities) && rt.states != nil && rt.states.NeedsFallback(vm.Ref(), HostedReportMaxAge, time.Now()) {
if full, showErr := d.Show(ctx, vm.Name); showErr == nil {
full.DriverID = d.ID()
if len(full.Capabilities) == 0 {
full.Capabilities = vm.Capabilities
}
vm = full
}
}
rt.states.Merge(&vm, fetchedAt)
seen[key] = true
out = append(out, vm)
}
}
unavailable, err := rt.listUnavailableVMs("")
out = append(out, unavailable...)
errs = append(errs, err)
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, errors.Join(errs...)
}
func (rt *Router) listUnavailableVMs(driverID string) ([]VMInfo, error) {
var out []VMInfo
var errs []error
inventoried := make(map[string]bool)
seen := make(map[string]bool)
add := func(vm VMInfo) {
key := foldedRefKey(vm.DriverID, vm.Name)
if !seen[key] {
vm.State, vm.DriverUnavailable = "driver_unavailable", true
out = append(out, vm)
seen[key] = true
}
}
if rt.dataRootDir != nil {
for _, inventory := range rt.inventories {
id := CanonicalDriverID(inventory.DriverID)
if _, active := rt.reg.GuestDriver(id); active || (driverID != "" && driverID != id) {
continue
}
vms, err := inventory.List(rt.dataRootDir())
if err != nil {
errs = append(errs, fmt.Errorf("read VM registrations for driver %q: %w", id, err))
continue
}
inventoried[id] = true
for _, vm := range vms {
vm.DriverID = id
add(vm)
}
}
}
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)
if _, active := rt.reg.GuestDriver(owner); active || inventoried[owner] || (driverID != "" && owner != driverID) {
continue
}
add(VMInfo{Name: e.Name(), DriverID: owner, Directory: vmDir})
}
}
return out, errors.Join(errs...)
}
// ResolveVM resolves a bare name only when exactly one driver owns it.
func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, error) {
vms, err := rt.ListAllVMs(ctx)
if err != nil {
return nil, VMInfo{}, err
}
var matches []VMInfo
for _, vm := range vms {
if strings.EqualFold(vm.Name, vmName) {
matches = append(matches, vm)
}
}
if len(matches) == 0 {
return nil, VMInfo{}, fmt.Errorf("VM %q not found in any active driver", vmName)
}
if len(matches) > 1 {
ids := make([]string, 0, len(matches))
for _, vm := range matches {
ids = append(ids, vm.DriverID)
}
sort.Strings(ids)
return nil, VMInfo{}, &AmbiguousVMError{Name: vmName, DriverIDs: ids}
}
vm := matches[0]
if vm.DriverUnavailable {
return nil, vm, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, vm.DriverID)
}
d, err := rt.DriverByID(vm.DriverID)
return d, vm, err
}
// ResolveRef resolves a VM within an explicit owning driver.
func (rt *Router) ResolveRef(ctx context.Context, ref VMRef) (Driver, VMInfo, error) {
return rt.resolveRef(ctx, ref, false)
}
// ResolveRefForDelete can resolve by inventory when a driver cannot load a
// VM's settings. The driver still decides whether deletion is allowed.
func (rt *Router) ResolveRefForDelete(ctx context.Context, ref VMRef) (Driver, VMInfo, error) {
return rt.resolveRef(ctx, ref, true)
}
func (rt *Router) resolveRef(ctx context.Context, ref VMRef, deleting bool) (Driver, VMInfo, error) {
ref = NewVMRef(ref.DriverID, ref.Name)
d, err := rt.DriverByID(ref.DriverID)
if err == nil {
fetchedAt := time.Now()
vm, showErr := d.Show(ctx, ref.Name)
if showErr != nil {
if deleting {
list, err := d.List(ctx)
if err == nil {
item, found, err := matchDeletionVM(list, ref)
if err != nil || found {
return d, item, err
}
}
}
return nil, VMInfo{}, showErr
}
vm.DriverID = d.ID()
if len(vm.Capabilities) == 0 {
vm.Capabilities = d.Capabilities()
}
rt.states.Merge(&vm, fetchedAt)
return d, vm, nil
}
unavailable, inventoryErr := rt.listUnavailableVMs(ref.DriverID)
for _, vm := range unavailable {
if strings.EqualFold(vm.Name, ref.Name) {
return nil, vm, err
}
}
return nil, VMInfo{}, errors.Join(err, inventoryErr)
}
func matchDeletionVM(list []VMInfo, ref VMRef) (VMInfo, bool, error) {
var vm VMInfo
matches := 0
for _, item := range list {
item.DriverID = ref.DriverID
if item.Name == ref.Name {
return item, true, nil
}
if strings.EqualFold(item.Name, ref.Name) {
vm = item
matches++
}
}
if matches > 1 {
return VMInfo{}, false, fmt.Errorf("VM name %q matches multiple VMs in driver %q; use the registered spelling", ref.Name, ref.DriverID)
}
return vm, matches == 1, nil
}
// PluginInUseChecker reports a plugin as in use while a guest driver it
// declares (or registers under its own ID) owns any VM. It blocks removal.
func (rt *Router) PluginInUseChecker() plugin.InUseChecker {
return rt.pluginChecker(rt.CheckDriverInUse)
}
// PluginBusyChecker reports a plugin as busy while a VM of one of its guest
// drivers is not stopped. It blocks disabling.
func (rt *Router) PluginBusyChecker() plugin.InUseChecker {
return rt.pluginChecker(rt.CheckDriverRunning)
}
// pluginChecker must not call Registry.Info/List: both invoke the in-use
// checker, which recursed until the goroutine stack overflowed.
func (rt *Router) pluginChecker(check func(context.Context, string) (bool, string, error)) plugin.InUseChecker {
return func(pluginID string) (bool, string, error) {
seen := map[string]bool{}
for _, did := range append([]string{pluginID}, rt.reg.DeclaredDriverIDs(pluginID)...) {
if did == "" || seen[did] {
continue
}
seen[did] = true
if hit, reason, err := check(context.Background(), did); err != nil || hit {
return hit, reason, err
}
}
return false, "", nil
}
}
// vmIdle reports states in which a driver can go away without orphaning a
// live VM process. A suspended VM has no process: its saved state stays in
// the VM folder and resumes once the driver is back. Anything else (running,
// starting, stopping, paused or an unknown state) counts as live.
func vmIdle(state string) bool {
switch strings.ToLower(strings.TrimSpace(state)) {
case "stopped", "suspended", "broken", "driver_unavailable":
return true
}
return false
}
// CheckDriverRunning returns true if a VM of driverID is not stopped
// (fail-closed on list error). A driver that is not active runs nothing.
func (rt *Router) CheckDriverRunning(ctx context.Context, driverID string) (bool, string, error) {
if rt == nil || rt.reg == nil {
return false, "", errors.New("driver router not initialized")
}
raw, ok := rt.reg.GuestDriver(driverID)
if !ok {
return false, "", nil
}
d, ok := raw.(Driver)
if !ok || d == nil {
return false, "", nil
}
vms, err := d.List(ctx)
if err != nil {
return true, "", err
}
for _, vm := range vms {
if !vmIdle(vm.State) {
return true, fmt.Sprintf("VM %s is %s", vm.Name, vm.State), nil
}
}
return false, "", nil
}
// 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
}