Files
Reims-Go/pkg/drivertest/sidecar_runner.go
T

618 lines
17 KiB
Go

package drivertest
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// SidecarConfig describes a Sidecar plugin executable that serves one guest
// driver over Content-Length framed JSON-RPC 2.0 on stdin/stdout.
type SidecarConfig struct {
ExePath string
Args []string
// Env is added to the process environment.
Env []string
// PluginID is sent in the handshake (default "drivertest.plugin").
PluginID string
// DriverID and Capabilities are the manifest's declaration of the driver.
DriverID string
Capabilities []string
// Logs, Phase and Console say whether the driver serves `driver/logs`,
// `driver/phase` and `driver/console.*`.
Logs bool
Phase bool
Console bool
// Suite configures the checks; Suite.Driver is set by RunSidecar.
Suite Config
}
// RunSidecar starts the Sidecar, plays the host for its reverse calls, and runs
// the contract suite against the driver it serves. The mock host enforces the
// rules the real host enforces: a driver reports and spawns only for itself,
// reported states and endpoints must be valid.
func RunSidecar(t *testing.T, sc SidecarConfig) {
t.Helper()
if sc.ExePath == "" || sc.DriverID == "" {
t.Fatal("drivertest: SidecarConfig needs ExePath and DriverID")
}
if sc.PluginID == "" {
sc.PluginID = "drivertest.plugin"
}
h := startSidecar(t, sc)
suite := sc.Suite
suite.Driver = h.driver()
Run(t, suite)
t.Run("HostAPIContract", func(t *testing.T) {
for _, v := range h.violations() {
t.Error(v)
}
})
}
type rpcMsg struct {
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
type sidecarHost struct {
t *testing.T
cfg SidecarConfig
cmd *exec.Cmd
in io.WriteCloser
wmu sync.Mutex
mu sync.Mutex
pending map[string]chan rpcMsg
nextID atomic.Uint64
pid atomic.Int64
running map[string]bool // VM name -> spawned by the sidecar and not stopped
bad []string
stderr bytes.Buffer
done chan struct{}
}
func startSidecar(t *testing.T, sc SidecarConfig) *sidecarHost {
t.Helper()
cmd := exec.Command(sc.ExePath, sc.Args...)
cmd.Env = append(os.Environ(), sc.Env...)
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
h := &sidecarHost{t: t, cfg: sc, cmd: cmd, in: stdin, pending: map[string]chan rpcMsg{}, running: map[string]bool{}, done: make(chan struct{})}
cmd.Stderr = &lockedWriter{mu: &h.mu, buf: &h.stderr}
if err := cmd.Start(); err != nil {
t.Fatalf("start sidecar: %v", err)
}
go h.readLoop(bufio.NewReader(stdout))
t.Cleanup(h.stop)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var init struct {
PluginAPI string `json:"pluginApi"`
}
if err := h.call(ctx, "plugin/initialize", map[string]any{
"pluginId": sc.PluginID, "pluginApi": "1.2.0", "uiApi": "2.1.0", "bridgeApi": "1.0.0",
"features": []string{"driver.snapshot", "driver.clone", "driver.disk", "driver.logs", "driver.phase", "driver.hosted", "driver.console", "host.vm.spawn.ref", "host.vm.reportState"},
"dataDir": t.TempDir(),
}, &init); err != nil {
t.Fatalf("sidecar handshake: %v", err)
}
return h
}
type lockedWriter struct {
mu *sync.Mutex
buf *bytes.Buffer
}
func (w *lockedWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.buf.Write(p)
}
func (h *sidecarHost) stop() {
_ = h.notify("plugin/shutdown")
_ = h.in.Close()
exited := make(chan struct{})
go func() { _ = h.cmd.Wait(); close(exited) }()
select {
case <-exited:
case <-time.After(3 * time.Second):
_ = h.cmd.Process.Kill()
<-exited
}
if h.t.Failed() {
h.mu.Lock()
out := strings.TrimSpace(h.stderr.String())
h.mu.Unlock()
if out != "" {
h.t.Logf("sidecar stderr:\n%s", out)
}
}
}
func (h *sidecarHost) violate(format string, args ...any) {
h.mu.Lock()
h.bad = append(h.bad, fmt.Sprintf(format, args...))
h.mu.Unlock()
}
func (h *sidecarHost) violations() []string {
h.mu.Lock()
defer h.mu.Unlock()
return append([]string(nil), h.bad...)
}
func (h *sidecarHost) writeFrame(v any) error {
raw, err := json.Marshal(v)
if err != nil {
return err
}
h.wmu.Lock()
defer h.wmu.Unlock()
if _, err := fmt.Fprintf(h.in, "Content-Length: %d\r\n\r\n", len(raw)); err != nil {
return err
}
_, err = h.in.Write(raw)
return err
}
func (h *sidecarHost) notify(method string) error {
return h.writeFrame(map[string]any{"jsonrpc": "2.0", "method": method})
}
func (h *sidecarHost) call(ctx context.Context, method string, params any, out any) error {
id := strconv.FormatUint(h.nextID.Add(1), 10)
ch := make(chan rpcMsg, 1)
h.mu.Lock()
h.pending[id] = ch
h.mu.Unlock()
defer func() {
h.mu.Lock()
delete(h.pending, id)
h.mu.Unlock()
}()
var raw json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
raw = b
}
if err := h.writeFrame(map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(id), "method": method, "params": raw}); err != nil {
return err
}
select {
case msg := <-ch:
if msg.Error != nil {
return errors.New(msg.Error.Message)
}
if out != nil && len(msg.Result) > 0 && string(msg.Result) != "null" {
return json.Unmarshal(msg.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
case <-h.done:
return errors.New("sidecar exited")
}
}
func readFrame(r *bufio.Reader) ([]byte, error) {
n := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
if k, v, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
if n, err = strconv.Atoi(strings.TrimSpace(v)); err != nil {
return nil, err
}
}
}
if n < 0 {
return nil, errors.New("missing Content-Length")
}
buf := make([]byte, n)
_, err := io.ReadFull(r, buf)
return buf, err
}
func (h *sidecarHost) readLoop(r *bufio.Reader) {
defer close(h.done)
for {
frame, err := readFrame(r)
if err != nil {
return
}
var msg rpcMsg
if json.Unmarshal(frame, &msg) != nil {
continue
}
if msg.Method != "" {
go h.serve(msg)
continue
}
h.mu.Lock()
ch := h.pending[strings.TrimSpace(string(msg.ID))]
h.mu.Unlock()
if ch != nil {
ch <- msg
}
}
}
func (h *sidecarHost) serve(msg rpcMsg) {
result, err := h.hostAPI(msg.Method, msg.Params)
if len(msg.ID) == 0 {
return
}
resp := map[string]any{"jsonrpc": "2.0", "id": msg.ID}
if err != nil {
resp["error"] = map[string]any{"code": -32000, "message": err.Error()}
} else {
if result == nil {
result = map[string]any{"ok": true}
}
resp["result"] = result
}
_ = h.writeFrame(resp)
}
func (h *sidecarHost) checkRef(method string, ref *VMRef) error {
if ref == nil {
return nil
}
if ref.DriverID != "" && ref.DriverID != h.cfg.DriverID {
h.violate("%s named driver %q, but the plugin declares only %q", method, ref.DriverID, h.cfg.DriverID)
return fmt.Errorf("plugin does not declare driver %q", ref.DriverID)
}
return nil
}
// hostAPI answers the reverse calls a driver may make.
func (h *sidecarHost) hostAPI(method string, raw json.RawMessage) (any, error) {
switch method {
case "host/notify", "host/audit":
return map[string]any{"ok": true}, nil
case "host/vm.spawn":
var req struct {
VMName string `json:"vm_name"`
Ref *VMRef `json:"ref"`
ExePath string `json:"exe_path"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if err := h.checkRef(method, req.Ref); err != nil {
return nil, err
}
name := req.VMName
if req.Ref != nil && req.Ref.Name != "" {
name = req.Ref.Name
}
if req.ExePath == "" || name == "" {
h.violate("host/vm.spawn needs a VM name and an executable path")
return nil, errors.New("executable path and VM name required")
}
h.mu.Lock()
h.running[name] = true
h.mu.Unlock()
return map[string]any{"pid": h.pid.Add(1) + 40000}, nil
case "host/vm.stop", "host/vm.isRunning":
var req struct {
Ref *VMRef `json:"ref"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if err := h.checkRef(method, req.Ref); err != nil {
return nil, err
}
h.mu.Lock()
defer h.mu.Unlock()
if req.Ref == nil {
return map[string]any{"ok": true, "running": false}, nil
}
if method == "host/vm.stop" {
delete(h.running, req.Ref.Name)
return map[string]any{"ok": true}, nil
}
return map[string]any{"running": h.running[req.Ref.Name]}, nil
case "host/vm.reportState":
var rep struct {
Ref VMRef `json:"ref"`
State string `json:"state"`
Phase string `json:"phase"`
Endpoints []VMEndpoint `json:"endpoints"`
}
if err := json.Unmarshal(raw, &rep); err != nil {
return nil, err
}
if err := h.checkRef(method, &rep.Ref); err != nil {
return nil, err
}
if strings.TrimSpace(rep.Ref.Name) == "" {
h.violate("host/vm.reportState without a VM name")
return nil, errors.New("reported state needs a VM name")
}
if !validStates[rep.State] {
h.violate("host/vm.reportState with state %q", rep.State)
return nil, fmt.Errorf("reported state %q is not allowed", rep.State)
}
switch rep.Phase {
case "", PhaseNormal, PhaseInstaller, PhaseRecovery:
default:
h.violate("host/vm.reportState with phase %q", rep.Phase)
return nil, fmt.Errorf("reported phase %q is not allowed", rep.Phase)
}
for _, ep := range rep.Endpoints {
if !endpointKinds[ep.Kind] {
h.violate("host/vm.reportState with endpoint kind %q", ep.Kind)
return nil, fmt.Errorf("unknown endpoint kind %q", ep.Kind)
}
}
return map[string]any{"ok": true}, nil
}
return nil, fmt.Errorf("method not found: %s", method)
}
// sidecarSuite adapts the Sidecar's driver/* RPCs to SuiteDriver.
type sidecarSuite struct{ h *sidecarHost }
func (h *sidecarHost) driver() SuiteDriver {
base := &sidecarSuite{h}
logs, phase, con := logsSuite{base}, phaseSuite{base}, consoleSuite{base}
switch {
case h.cfg.Logs && h.cfg.Phase && h.cfg.Console:
return struct {
*sidecarSuite
logsSuite
phaseSuite
consoleSuite
}{base, logs, phase, con}
case h.cfg.Logs && h.cfg.Phase:
return struct {
*sidecarSuite
logsSuite
phaseSuite
}{base, logs, phase}
case h.cfg.Logs && h.cfg.Console:
return struct {
*sidecarSuite
logsSuite
consoleSuite
}{base, logs, con}
case h.cfg.Phase && h.cfg.Console:
return struct {
*sidecarSuite
phaseSuite
consoleSuite
}{base, phase, con}
case h.cfg.Logs:
return struct {
*sidecarSuite
logsSuite
}{base, logs}
case h.cfg.Phase:
return struct {
*sidecarSuite
phaseSuite
}{base, phase}
case h.cfg.Console:
return struct {
*sidecarSuite
consoleSuite
}{base, con}
}
return base
}
func (s *sidecarSuite) ref(name string) VMRef { return VMRef{DriverID: s.h.cfg.DriverID, Name: name} }
func (s *sidecarSuite) call(method string, params, out any) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return s.h.call(ctx, method, params, out)
}
func (s *sidecarSuite) declared(c string) bool { return has(s.h.cfg.Capabilities, c) }
func (s *sidecarSuite) ID() string { return s.h.cfg.DriverID }
func (s *sidecarSuite) Capabilities() []string { return append([]string(nil), s.h.cfg.Capabilities...) }
func (s *sidecarSuite) normalize(vm *VMInfo) {
vm.DriverID = s.h.cfg.DriverID
}
func (s *sidecarSuite) List(context.Context) ([]VMInfo, error) {
var resp struct {
VMs []VMInfo `json:"vms"`
}
if err := s.call("driver/list", nil, &resp); err != nil {
return nil, err
}
for i := range resp.VMs {
s.normalize(&resp.VMs[i])
}
return resp.VMs, nil
}
func (s *sidecarSuite) Show(_ context.Context, name string) (VMInfo, error) {
var vm VMInfo
if err := s.call("driver/show", map[string]any{"name": name, "ref": s.ref(name)}, &vm); err != nil {
return VMInfo{}, err
}
s.normalize(&vm)
return vm, nil
}
func (s *sidecarSuite) ValidateCreate(_ context.Context, req CreateRequest) []ValidationIssue {
var resp struct {
Issues []ValidationIssue `json:"issues"`
}
if err := s.call("driver/validateCreate", req, &resp); err != nil {
return []ValidationIssue{{Field: "driver", Message: err.Error()}}
}
return resp.Issues
}
func (s *sidecarSuite) Create(_ context.Context, req CreateRequest) error {
return s.call("driver/create", req, nil)
}
func (s *sidecarSuite) Start(_ context.Context, name string) error {
return s.call("driver/start", map[string]any{"name": name, "ref": s.ref(name)}, nil)
}
func (s *sidecarSuite) Stop(_ context.Context, name string, force bool) error {
return s.call("driver/stop", map[string]any{"name": name, "force": force}, nil)
}
func (s *sidecarSuite) Delete(_ context.Context, name string, keepFiles bool) error {
return s.call("driver/delete", map[string]any{"name": name, "keep_files": keepFiles}, nil)
}
// The storage operations refuse to run for an undeclared capability, as the
// host does, so the suite can check the refusal.
func (s *sidecarSuite) ListSnapshots(_ context.Context, name string) ([]DiskSnapshot, error) {
if !s.declared(CapSnapshot) {
return nil, errors.New("snapshots are not declared")
}
var resp struct {
Snapshots []DiskSnapshot `json:"snapshots"`
}
err := s.call("driver/snapshot.list", map[string]any{"name": name, "ref": s.ref(name)}, &resp)
return resp.Snapshots, err
}
func (s *sidecarSuite) RunSnapshot(_ context.Context, name, operation, snapName string) error {
if !s.declared(CapSnapshot) {
return errors.New("snapshots are not declared")
}
switch operation {
case "create", "restore", "delete":
default:
return fmt.Errorf("unknown snapshot operation %q", operation)
}
return s.call("driver/snapshot."+operation, map[string]any{"name": name, "ref": s.ref(name), "snapshot": snapName}, nil)
}
func (s *sidecarSuite) CloneCoW(_ context.Context, source, clone string) error {
if !s.declared(CapCowClone) {
return errors.New("clones are not declared")
}
return s.call("driver/clone", map[string]any{"name": source, "ref": s.ref(source), "clone_name": clone, "clone_ref": s.ref(clone)}, nil)
}
func (s *sidecarSuite) ResizeDisk(_ context.Context, name, size string) (DiskResizeResult, error) {
if !s.declared(CapResize) {
return DiskResizeResult{}, errors.New("disk resize is not declared")
}
var res DiskResizeResult
err := s.call("driver/disk.resize", map[string]any{"name": name, "ref": s.ref(name), "size": size}, &res)
return res, err
}
func (s *sidecarSuite) CompactDisk(_ context.Context, name string) (DiskCompactResult, error) {
if !s.declared(CapResize) {
return DiskCompactResult{}, errors.New("disk compaction is not declared")
}
var res DiskCompactResult
err := s.call("driver/disk.compact", map[string]any{"name": name, "ref": s.ref(name)}, &res)
return res, err
}
type logsSuite struct{ s *sidecarSuite }
func (l logsSuite) ReadLogs(_ context.Context, name string, serial bool) (string, error) {
var resp struct {
Content string `json:"content"`
}
err := l.s.call("driver/logs", map[string]any{"name": name, "ref": l.s.ref(name), "serial": serial}, &resp)
return resp.Content, err
}
type phaseSuite struct{ s *sidecarSuite }
func (p phaseSuite) Phase(_ context.Context, name string) (string, error) {
var resp struct {
Phase string `json:"phase"`
}
err := p.s.call("driver/phase", map[string]any{"name": name, "ref": p.s.ref(name)}, &resp)
if resp.Phase == "" && err == nil {
return PhaseNormal, nil
}
return resp.Phase, err
}
type consoleSuite struct{ s *sidecarSuite }
func (c consoleSuite) ConsoleScreenshot(_ context.Context, name, path string) error {
if !c.s.declared(CapConsole) {
return errors.New("console is not declared")
}
return c.s.call("driver/console.screenshot", map[string]any{"name": name, "ref": c.s.ref(name), "path": path}, nil)
}
func (c consoleSuite) ConsolePointer(_ context.Context, name string, req ConsolePointerRequest) error {
if !c.s.declared(CapConsole) {
return errors.New("console is not declared")
}
return c.s.call("driver/console.pointer", map[string]any{
"name": name, "ref": c.s.ref(name),
"action": req.Action, "x": req.X, "y": req.Y, "width": req.Width, "height": req.Height, "button": req.Button,
}, nil)
}
func (c consoleSuite) ConsoleKey(_ context.Context, name, key string, modifiers []string) error {
if !c.s.declared(CapConsole) {
return errors.New("console is not declared")
}
return c.s.call("driver/console.key", map[string]any{"name": name, "ref": c.s.ref(name), "key": key, "modifiers": modifiers}, nil)
}
func (c consoleSuite) ConsoleType(_ context.Context, name, text string) (int, error) {
if !c.s.declared(CapConsole) {
return 0, errors.New("console is not declared")
}
var resp struct {
Characters int `json:"characters"`
}
if err := c.s.call("driver/console.type", map[string]any{"name": name, "ref": c.s.ref(name), "text": text}, &resp); err != nil {
return 0, err
}
return resp.Characters, nil
}