Files
Reims-Go/internal/driver/sidecar_driver.go
T

442 lines
14 KiB
Go

package driver
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/plugin"
)
// SidecarDriver adapts an L3 Sidecar guest driver plugin into the unified
// driver.Driver + driver.ActionDriver interfaces over JSON-RPC 2.0 (§5.3, §8).
// Because VM processes are spawned via the reverse Host API (`host/vm.spawn`),
// a Sidecar crash or restart never terminates running VMs.
//
// Snapshot, clone and disk operations exist only when the manifest declares
// the matching capability bit: NewSidecarDriver wraps the base driver so the
// optional driver interfaces are satisfied exactly for the declared bits.
type SidecarDriver struct {
contrib plugin.GuestDriverContribution
sup *plugin.SidecarSupervisor
}
// NewSidecarDriver constructs a JSON-RPC proxy driver backed by sup.
func NewSidecarDriver(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) Driver {
base := &SidecarDriver{contrib: contrib, sup: sup}
snap := HasCapability(contrib.Capabilities, CapSnapshot)
clone := HasCapability(contrib.Capabilities, CapCowClone)
disk := HasCapability(contrib.Capabilities, CapResize)
s, c, k := &sidecarSnapshots{base}, &sidecarClones{base}, &sidecarDisks{base}
switch {
case snap && clone && disk:
return struct {
*SidecarDriver
*sidecarSnapshots
*sidecarClones
*sidecarDisks
}{base, s, c, k}
case snap && clone:
return struct {
*SidecarDriver
*sidecarSnapshots
*sidecarClones
}{base, s, c}
case snap && disk:
return struct {
*SidecarDriver
*sidecarSnapshots
*sidecarDisks
}{base, s, k}
case clone && disk:
return struct {
*SidecarDriver
*sidecarClones
*sidecarDisks
}{base, c, k}
case snap:
return struct {
*SidecarDriver
*sidecarSnapshots
}{base, s}
case clone:
return struct {
*SidecarDriver
*sidecarClones
}{base, c}
case disk:
return struct {
*SidecarDriver
*sidecarDisks
}{base, k}
default:
return base
}
}
func (d *SidecarDriver) ID() string { return d.contrib.ID }
func (d *SidecarDriver) DisplayName() plugin.LocalizedText { return d.contrib.Name }
func (d *SidecarDriver) RuntimeKind() string { return d.contrib.RuntimeKind }
func (d *SidecarDriver) RuntimeAPIRange() string { return d.contrib.RuntimeAPIRange }
func (d *SidecarDriver) Capabilities() []string {
return append([]string(nil), d.contrib.Capabilities...)
}
func (d *SidecarDriver) CreateSchema() *plugin.SettingsSchema { return d.contrib.CreateSchema }
func (d *SidecarDriver) SettingsSchema() *plugin.SettingsSchema { return d.contrib.SettingsSchema }
// ConsoleEndpoint is "qmp" unless the manifest asks for a driver console.
func (d *SidecarDriver) ConsoleEndpoint() string {
if d.contrib.ConsoleEndpoint == "" {
return "qmp"
}
return d.contrib.ConsoleEndpoint
}
func (d *SidecarDriver) PasteCombo() string { return d.contrib.PasteCombo }
func (d *SidecarDriver) Keymap() string { return d.contrib.Keymap }
var (
_ Driver = (*SidecarDriver)(nil)
_ ActionDriver = (*SidecarDriver)(nil)
_ LogDriver = (*SidecarDriver)(nil)
_ PhaseReporter = (*SidecarDriver)(nil)
_ DriverMetadata = (*SidecarDriver)(nil)
_ SnapshotDriver = (*sidecarSnapshots)(nil)
_ CloneDriver = (*sidecarClones)(nil)
_ DiskDriver = (*sidecarDisks)(nil)
)
func (d *SidecarDriver) ref(name string) VMRef { return VMRef{DriverID: d.contrib.ID, Name: name} }
// normalize pins a VM the Sidecar returned to this driver: its capabilities
// can only narrow the manifest's, its endpoints must be valid, and the ssh
// endpoint and SSH port agree.
func (d *SidecarDriver) normalize(vm *VMInfo) error {
vm.DriverID = d.contrib.ID
if len(vm.Capabilities) == 0 {
vm.Capabilities = d.Capabilities()
} else {
kept := vm.Capabilities[:0:0]
for _, c := range vm.Capabilities {
if HasCapability(d.contrib.Capabilities, c) {
kept = append(kept, c)
}
}
vm.Capabilities = kept
}
if err := ValidateEndpoints(vm.Endpoints); err != nil {
return fmt.Errorf("VM %q of driver %q reports an invalid endpoint: %w", vm.Name, d.contrib.ID, err)
}
SyncSSHEndpoint(vm)
return nil
}
func (d *SidecarDriver) List(ctx context.Context) ([]VMInfo, error) {
var resp struct {
VMs []VMInfo `json:"vms"`
}
if err := d.sup.Call(ctx, "driver/list", nil, &resp); err != nil {
return nil, err
}
for i := range resp.VMs {
if err := d.normalize(&resp.VMs[i]); err != nil {
return nil, err
}
}
return resp.VMs, nil
}
func (d *SidecarDriver) Show(ctx context.Context, name string) (VMInfo, error) {
var info VMInfo
if err := d.sup.Call(ctx, "driver/show", map[string]any{"name": name, "ref": d.ref(name)}, &info); err != nil {
return VMInfo{}, err
}
if err := d.normalize(&info); err != nil {
return VMInfo{}, err
}
return info, nil
}
// ReadLogs implements LogDriver through `driver/logs`.
func (d *SidecarDriver) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
var resp struct {
Content string `json:"content"`
}
if err := d.sup.Call(ctx, "driver/logs", map[string]any{"name": name, "ref": d.ref(name), "serial": serial}, &resp); err != nil {
return "", err
}
return resp.Content, nil
}
// Phase implements PhaseReporter through `driver/phase`.
func (d *SidecarDriver) Phase(ctx context.Context, name string) (string, error) {
var resp struct {
Phase string `json:"phase"`
}
if err := d.sup.Call(ctx, "driver/phase", map[string]any{"name": name, "ref": d.ref(name)}, &resp); err != nil {
return "", err
}
switch resp.Phase {
case "", PhaseNormal, PhaseInstaller, PhaseRecovery:
if resp.Phase == "" {
return PhaseNormal, nil
}
return resp.Phase, nil
}
return "", fmt.Errorf("driver %q reported unknown phase %q", d.contrib.ID, resp.Phase)
}
// sidecarSnapshots, sidecarClones and sidecarDisks implement the storage
// interfaces. Each refuses to run unless the manifest declared its capability.
type sidecarSnapshots struct{ d *SidecarDriver }
type sidecarClones struct{ d *SidecarDriver }
type sidecarDisks struct{ d *SidecarDriver }
func (s *sidecarSnapshots) ListSnapshots(ctx context.Context, name string) ([]DiskSnapshot, error) {
if !HasCapability(s.d.contrib.Capabilities, CapSnapshot) {
return nil, fmt.Errorf("driver %q does not support snapshots", s.d.contrib.ID)
}
var resp struct {
Snapshots []DiskSnapshot `json:"snapshots"`
}
if err := s.d.sup.Call(ctx, "driver/snapshot.list", map[string]any{"name": name, "ref": s.d.ref(name)}, &resp); err != nil {
return nil, err
}
return resp.Snapshots, nil
}
func (s *sidecarSnapshots) RunSnapshot(ctx context.Context, name, operation, snapName string, stdout, _ io.Writer) error {
if !HasCapability(s.d.contrib.Capabilities, CapSnapshot) {
return fmt.Errorf("driver %q does not support snapshots", s.d.contrib.ID)
}
switch operation {
case "create", "restore", "delete":
default:
return fmt.Errorf("unknown snapshot operation %q", operation)
}
clean, err := ValidateSnapshotName(snapName)
if err != nil {
return err
}
var resp struct {
Logs []string `json:"logs"`
}
if err := s.d.sup.Call(ctx, "driver/snapshot."+operation, map[string]any{"name": name, "ref": s.d.ref(name), "snapshot": clean}, &resp); err != nil {
return err
}
writeLogs(stdout, resp.Logs)
return nil
}
func (c *sidecarClones) CloneCoW(ctx context.Context, sourceName, cloneName string, stdout, _ io.Writer) error {
if !HasCapability(c.d.contrib.Capabilities, CapCowClone) {
return fmt.Errorf("driver %q does not support CoW clones", c.d.contrib.ID)
}
var resp struct {
Directory string `json:"directory"`
Logs []string `json:"logs"`
}
if err := c.d.sup.Call(ctx, "driver/clone", map[string]any{
"name": sourceName, "ref": c.d.ref(sourceName), "clone_name": cloneName, "clone_ref": c.d.ref(cloneName),
}, &resp); err != nil {
return err
}
writeLogs(stdout, resp.Logs)
if resp.Directory == "" {
return nil
}
// Stamp ownership only for a folder next to the source VM, never at a
// path the Sidecar picked freely.
src, err := c.d.Show(ctx, sourceName)
if err != nil || src.Directory == "" {
return nil
}
dir := filepath.Clean(resp.Directory)
if !strings.EqualFold(filepath.Dir(dir), filepath.Dir(filepath.Clean(src.Directory))) {
return fmt.Errorf("sidecar driver returned clone directory %q outside the source VM's folder", resp.Directory)
}
if st, err := os.Stat(dir); err != nil || !st.IsDir() {
return nil
}
if _, err := os.Stat(filepath.Join(dir, OwnerMarkerFile)); err == nil {
if existing := ReadOwnerDriver(dir); existing != c.d.contrib.ID {
return fmt.Errorf("refusing to overwrite VM owner marker %q with %q", existing, c.d.contrib.ID)
}
}
if err := WriteOwnerDriver(dir, c.d.contrib.ID); err != nil {
return fmt.Errorf("write driver owner marker: %w", err)
}
return nil
}
func (k *sidecarDisks) ResizeDisk(ctx context.Context, name, newSize string, stdout, _ io.Writer) (DiskResizeResult, error) {
if !HasCapability(k.d.contrib.Capabilities, CapResize) {
return DiskResizeResult{}, fmt.Errorf("driver %q does not support disk resize", k.d.contrib.ID)
}
var resp struct {
DiskResizeResult
Logs []string `json:"logs"`
}
if err := k.d.sup.Call(ctx, "driver/disk.resize", map[string]any{"name": name, "ref": k.d.ref(name), "size": newSize}, &resp); err != nil {
return DiskResizeResult{}, err
}
writeLogs(stdout, resp.Logs)
return resp.DiskResizeResult, nil
}
func (k *sidecarDisks) CompactDisk(ctx context.Context, name string, stdout, _ io.Writer) (DiskCompactResult, error) {
if !HasCapability(k.d.contrib.Capabilities, CapResize) {
return DiskCompactResult{}, fmt.Errorf("driver %q does not support disk compaction", k.d.contrib.ID)
}
var resp struct {
DiskCompactResult
Logs []string `json:"logs"`
}
if err := k.d.sup.Call(ctx, "driver/disk.compact", map[string]any{"name": name, "ref": k.d.ref(name)}, &resp); err != nil {
return DiskCompactResult{}, err
}
writeLogs(stdout, resp.Logs)
return resp.DiskCompactResult, nil
}
func writeLogs(w io.Writer, lines []string) {
if w == nil {
return
}
for _, l := range lines {
_, _ = fmt.Fprintln(w, l)
}
}
func (d *SidecarDriver) ValidateCreate(ctx context.Context, req CreateRequest) []ValidationIssue {
var resp struct {
Issues []ValidationIssue `json:"issues"`
}
if err := d.sup.Call(ctx, "driver/validateCreate", req, &resp); err != nil {
return []ValidationIssue{{Field: "driver", Message: err.Error()}}
}
return resp.Issues
}
func (d *SidecarDriver) Create(ctx context.Context, req CreateRequest, stdout, _ io.Writer) error {
var resp struct {
Directory string `json:"directory"`
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/create", req, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
if resp.Directory != "" {
cleanDir := filepath.Clean(resp.Directory)
// Only stamp ownership inside an existing directory returned for this VM,
// and refuse to hijack a directory already owned by a different driver.
if req.Dir != "" {
cleanReq := filepath.Clean(req.Dir)
if !strings.EqualFold(cleanDir, cleanReq) && !strings.HasPrefix(strings.ToLower(cleanDir), strings.ToLower(cleanReq+string(os.PathSeparator))) {
return fmt.Errorf("sidecar driver returned directory %q outside requested %q", resp.Directory, req.Dir)
}
}
if st, err := os.Stat(cleanDir); err == nil && st.IsDir() {
markerPath := filepath.Join(cleanDir, OwnerMarkerFile)
if _, mErr := os.Stat(markerPath); mErr == nil {
if existing := ReadOwnerDriver(cleanDir); existing != d.contrib.ID {
return fmt.Errorf("refusing to overwrite VM owner marker %q with %q", existing, d.contrib.ID)
}
}
if err := WriteOwnerDriver(cleanDir, d.contrib.ID); err != nil {
return fmt.Errorf("write driver owner marker: %w", err)
}
}
}
return nil
}
func (d *SidecarDriver) ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue {
var resp struct {
Issues []ValidationIssue `json:"issues"`
}
if err := d.sup.Call(ctx, "driver/validateSet", req, &resp); err != nil {
return []ValidationIssue{{Field: "driver", Message: err.Error()}}
}
return resp.Issues
}
func (d *SidecarDriver) Set(ctx context.Context, req SetRequest, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/set", req, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) Start(ctx context.Context, req StartRequest) (StartResult, error) {
var resp struct {
Logs []string `json:"logs"`
PostStart []plugin.PostStartAction `json:"post_start"`
}
payload := map[string]any{"name": req.Ref.Name, "ref": req.Ref, "intents": req.Intents}
if err := d.sup.Call(ctx, "driver/start", payload, &resp); err != nil {
return StartResult{}, err
}
for _, l := range resp.Logs {
if req.Stdout != nil {
_, _ = fmt.Fprintln(req.Stdout, l)
}
}
return StartResult{PostStart: resp.PostStart}, nil
}
func (d *SidecarDriver) Stop(ctx context.Context, name string, force bool, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/stop", map[string]any{"name": name, "force": force}, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) Delete(ctx context.Context, name string, keepFiles bool, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/delete", map[string]any{"name": name, "keep_files": keepFiles}, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) {
var resp any
err := d.sup.Call(ctx, "driver/invokeAction", map[string]any{
"vm_name": vmName,
"action": action,
"params": params,
}, &resp)
return resp, err
}