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

331 lines
12 KiB
Go

package driver_test
import (
"context"
"encoding/json"
"errors"
"io"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
"github.com/Nwflower/reims-go/pkg/drivertest"
)
// TestHelperFakeDriver and TestHelperFakeVM turn the test binary into the
// fake Sidecar driver and the VM process it spawns.
func TestHelperFakeDriver(t *testing.T) { fakedriver.MaybeServe() }
func TestHelperFakeVM(t *testing.T) { fakedriver.MaybeRunVM() }
// suiteAdapter presents a host driver.Driver to the public contract suite.
type suiteAdapter struct{ d driver.Driver }
func convert[T any](in any) (T, error) {
var out T
raw, err := json.Marshal(in)
if err != nil {
return out, err
}
return out, json.Unmarshal(raw, &out)
}
func (a suiteAdapter) ID() string { return a.d.ID() }
func (a suiteAdapter) Capabilities() []string { return a.d.Capabilities() }
func (a suiteAdapter) List(ctx context.Context) ([]drivertest.VMInfo, error) {
vms, err := a.d.List(ctx)
if err != nil {
return nil, err
}
return convert[[]drivertest.VMInfo](vms)
}
func (a suiteAdapter) Show(ctx context.Context, name string) (drivertest.VMInfo, error) {
vm, err := a.d.Show(ctx, name)
if err != nil {
return drivertest.VMInfo{}, err
}
return convert[drivertest.VMInfo](vm)
}
func (a suiteAdapter) ValidateCreate(ctx context.Context, req drivertest.CreateRequest) []drivertest.ValidationIssue {
issues := a.d.ValidateCreate(ctx, driver.CreateRequest{DriverID: req.DriverID, Name: req.Name, Dir: req.Dir, Options: req.Options})
out, _ := convert[[]drivertest.ValidationIssue](issues)
return out
}
func (a suiteAdapter) Create(ctx context.Context, req drivertest.CreateRequest) error {
return a.d.Create(ctx, driver.CreateRequest{DriverID: req.DriverID, Name: req.Name, Dir: req.Dir, Options: req.Options}, io.Discard, io.Discard)
}
func (a suiteAdapter) Start(ctx context.Context, name string) error {
_, err := a.d.Start(ctx, driver.StartRequest{Ref: driver.NewVMRef(a.d.ID(), name), Stdout: io.Discard, Stderr: io.Discard})
return err
}
func (a suiteAdapter) Stop(ctx context.Context, name string, force bool) error {
return a.d.Stop(ctx, name, force, io.Discard, io.Discard)
}
func (a suiteAdapter) Delete(ctx context.Context, name string, keepFiles bool) error {
return a.d.Delete(ctx, name, keepFiles, io.Discard, io.Discard)
}
func (a suiteAdapter) ListSnapshots(ctx context.Context, name string) ([]drivertest.DiskSnapshot, error) {
sd, ok := a.d.(driver.SnapshotDriver)
if !ok {
return nil, errors.New("driver has no snapshots")
}
snaps, err := sd.ListSnapshots(ctx, name)
if err != nil {
return nil, err
}
return convert[[]drivertest.DiskSnapshot](snaps)
}
func (a suiteAdapter) RunSnapshot(ctx context.Context, name, op, snap string) error {
sd, ok := a.d.(driver.SnapshotDriver)
if !ok {
return errors.New("driver has no snapshots")
}
return sd.RunSnapshot(ctx, name, op, snap, io.Discard, io.Discard)
}
func (a suiteAdapter) CloneCoW(ctx context.Context, src, dst string) error {
cd, ok := a.d.(driver.CloneDriver)
if !ok {
return errors.New("driver has no clones")
}
return cd.CloneCoW(ctx, src, dst, io.Discard, io.Discard)
}
func (a suiteAdapter) ResizeDisk(ctx context.Context, name, size string) (drivertest.DiskResizeResult, error) {
dd, ok := a.d.(driver.DiskDriver)
if !ok {
return drivertest.DiskResizeResult{}, errors.New("driver has no disk operations")
}
res, err := dd.ResizeDisk(ctx, name, size, io.Discard, io.Discard)
if err != nil {
return drivertest.DiskResizeResult{}, err
}
return convert[drivertest.DiskResizeResult](res)
}
func (a suiteAdapter) CompactDisk(ctx context.Context, name string) (drivertest.DiskCompactResult, error) {
dd, ok := a.d.(driver.DiskDriver)
if !ok {
return drivertest.DiskCompactResult{}, errors.New("driver has no disk operations")
}
res, err := dd.CompactDisk(ctx, name, io.Discard, io.Discard)
if err != nil {
return drivertest.DiskCompactResult{}, err
}
return convert[drivertest.DiskCompactResult](res)
}
func (a suiteAdapter) ReadLogs(ctx context.Context, name string, serial bool) (string, error) {
ld, ok := a.d.(driver.LogDriver)
if !ok {
return "", errors.New("driver has no logs")
}
return ld.ReadLogs(ctx, name, serial)
}
func (a suiteAdapter) Phase(ctx context.Context, name string) (string, error) {
pd, ok := a.d.(driver.PhaseReporter)
if !ok {
return "", errors.New("driver reports no phase")
}
return pd.Phase(ctx, name)
}
func TestSidecarDriversPassTheContractSuite(t *testing.T) {
h := fakedriver.NewHarness(t)
hosted := h.Add("hosted", "test.fake.hosted", "test.driver.hosted")
process := h.Add("process", "test.fake.process", "test.driver.process")
console := h.Add("hosted-console", "test.fake.console", "test.driver.console")
drivertest.Run(t, drivertest.Config{
Driver: suiteAdapter{hosted},
PeerDriver: suiteAdapter{process},
Settle: 10 * time.Second,
})
// The process driver passes the suite on its own as well.
drivertest.Run(t, drivertest.Config{Driver: suiteAdapter{process}, VMName: "process-vm", Settle: 10 * time.Second})
// A driver that serves its own console also passes the console checks.
drivertest.Run(t, drivertest.Config{Driver: consoleSuiteAdapter{suiteAdapter{console}}, VMName: "console-vm", Settle: 10 * time.Second})
}
// consoleSuiteAdapter adds the driver console to the contract suite adapter.
type consoleSuiteAdapter struct{ suiteAdapter }
func (a consoleSuiteAdapter) console() (driver.ConsoleDriver, error) {
cd, ok := a.d.(driver.ConsoleDriver)
if !ok {
return nil, errors.New("driver has no console")
}
return cd, nil
}
func (a consoleSuiteAdapter) ConsoleScreenshot(ctx context.Context, name, path string) error {
cd, err := a.console()
if err != nil {
return err
}
_, err = cd.ConsoleScreenshot(ctx, name, driver.ConsoleScreenshotRequest{Path: path})
return err
}
func (a consoleSuiteAdapter) ConsolePointer(ctx context.Context, name string, req drivertest.ConsolePointerRequest) error {
cd, err := a.console()
if err != nil {
return err
}
return cd.ConsolePointer(ctx, name, driver.ConsolePointerRequest{
Action: req.Action, X: req.X, Y: req.Y, Width: req.Width, Height: req.Height, Button: req.Button,
})
}
func (a consoleSuiteAdapter) ConsoleKey(ctx context.Context, name, key string, modifiers []string) error {
cd, err := a.console()
if err != nil {
return err
}
return cd.ConsoleKey(ctx, name, driver.ConsoleKeyRequest{Key: key, Modifiers: modifiers})
}
func (a consoleSuiteAdapter) ConsoleType(ctx context.Context, name, text string) (int, error) {
cd, err := a.console()
if err != nil {
return 0, err
}
return cd.ConsoleType(ctx, name, text)
}
func TestNewSidecarDriverImplementsStorageExactlyForDeclaredCapabilities(t *testing.T) {
cases := []struct {
caps []string
snap, clone, resize bool
}{
{nil, false, false, false},
{[]string{"snapshot"}, true, false, false},
{[]string{"cow_clone"}, false, true, false},
{[]string{"resize"}, false, false, true},
{[]string{"snapshot", "cow_clone"}, true, true, false},
{[]string{"snapshot", "resize"}, true, false, true},
{[]string{"cow_clone", "resize"}, false, true, true},
{[]string{"snapshot", "cow_clone", "resize", "hosted"}, true, true, true},
{[]string{"hosted", "qmp", "ssh"}, false, false, false},
}
for _, tc := range cases {
d := driver.NewSidecarDriver(plugin.GuestDriverContribution{ID: "test.driver.caps", Capabilities: tc.caps}, nil)
_, snap := d.(driver.SnapshotDriver)
_, clone := d.(driver.CloneDriver)
_, disk := d.(driver.DiskDriver)
if snap != tc.snap || clone != tc.clone || disk != tc.resize {
t.Errorf("caps %v: snapshot=%v clone=%v disk=%v, want %v %v %v", tc.caps, snap, clone, disk, tc.snap, tc.clone, tc.resize)
}
if _, ok := d.(driver.LogDriver); !ok {
t.Errorf("caps %v: sidecar driver lost LogDriver", tc.caps)
}
if _, ok := d.(driver.PhaseReporter); !ok {
t.Errorf("caps %v: sidecar driver lost PhaseReporter", tc.caps)
}
if _, ok := d.(driver.ActionDriver); !ok {
t.Errorf("caps %v: sidecar driver lost ActionDriver", tc.caps)
}
}
}
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(25 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
func TestSameNameVMsOfTwoSidecarDriversStayIndependentThroughTheRouter(t *testing.T) {
h := fakedriver.NewHarness(t)
hosted := h.Add("hosted", "test.fake.hosted", "test.driver.hosted")
process := h.Add("process", "test.fake.process", "test.driver.process")
ctx := context.Background()
for _, d := range []driver.Driver{hosted, process} {
if err := d.Create(ctx, driver.CreateRequest{DriverID: d.ID(), Name: "dev"}, io.Discard, io.Discard); err != nil {
t.Fatalf("create on %s: %v", d.ID(), err)
}
}
svc := lifecycle.New(h.Registry, h.Router, nil)
hostedRef, processRef := driver.NewVMRef(hosted.ID(), "dev"), driver.NewVMRef(process.ID(), "dev")
state := func(ref driver.VMRef) driver.VMInfo {
t.Helper()
_, vm, err := h.Router.ResolveRef(ctx, ref)
if err != nil {
t.Fatalf("ResolveRef %v: %v", ref, err)
}
return vm
}
if vms, err := h.Router.ListAllVMs(ctx); err != nil || len(vms) != 2 {
t.Fatalf("ListAllVMs = %d VMs, %v", len(vms), err)
}
if _, err := svc.Start(ctx, driver.VMRef{Name: "dev"}, io.Discard, io.Discard); err == nil {
t.Fatal("a bare same-name start was not rejected as ambiguous")
}
// The hosted driver pushes its state: the table sees running, then ready.
if _, err := svc.Start(ctx, hostedRef, io.Discard, io.Discard); err != nil {
t.Fatalf("start hosted: %v", err)
}
eventually(t, "hosted VM to report ready through host/vm.reportState", func() bool {
rep, ok := h.States.Get(hostedRef)
return ok && rep.State == "running" && rep.Ready != nil && *rep.Ready
})
hv := state(hostedRef)
if hv.State != "running" || hv.Ready == nil || !*hv.Ready || len(hv.Endpoints) == 0 || !driver.IsHosted(hv.Capabilities) || hv.PID != nil {
t.Fatalf("hosted VM as the host sees it = %+v", hv)
}
if pv := state(processRef); pv.State != "stopped" {
t.Fatalf("starting the hosted VM moved the same-name process VM to %q", pv.State)
}
// The process driver spawns a real VM process through the broker.
if _, err := svc.Start(ctx, processRef, io.Discard, io.Discard); err != nil {
t.Fatalf("start process VM: %v", err)
}
eventually(t, "broker to track the spawned VM", func() bool {
return h.Broker.IsManagedVMRunning(process.ID(), "dev")
})
if len(h.Broker.ManagedVMPIDs(process.ID(), "dev")) == 0 {
t.Fatal("no PIDs for the spawned VM")
}
if h.Broker.IsManagedVMRunning(hosted.ID(), "dev") {
t.Fatal("the hosted same-name VM was reported as a spawned process")
}
if pv := state(processRef); pv.State != "running" || pv.PID == nil || *pv.PID <= 0 {
t.Fatalf("process VM as the host sees it = %+v", pv)
}
if hv := state(hostedRef); hv.PID != nil {
t.Fatalf("hosted VM gained a PID: %+v", hv)
}
if err := svc.Stop(ctx, hostedRef, false, io.Discard, io.Discard); err != nil {
t.Fatalf("stop hosted: %v", err)
}
eventually(t, "hosted VM to report stopped", func() bool { return state(hostedRef).State == "stopped" })
if !h.Broker.IsManagedVMRunning(process.ID(), "dev") || state(processRef).State != "running" {
t.Fatal("stopping the hosted VM stopped the same-name process VM")
}
if err := svc.Stop(ctx, processRef, false, io.Discard, io.Discard); err != nil {
t.Fatalf("stop process VM: %v", err)
}
eventually(t, "the process VM's job to end", func() bool { return !h.Broker.IsManagedVMRunning(process.ID(), "dev") })
eventually(t, "process VM to list as stopped", func() bool { return state(processRef).State == "stopped" })
}