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

445 lines
13 KiB
Go

package drivertest
import (
"context"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"os"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
// fakeEngine is an in-memory VM host used by the in-process driver and by the
// helper Sidecar below.
type fakeVM struct {
name string
state string
ready *bool
snaps map[string]bool
disk uint64
}
type fakeEngine struct {
mu sync.Mutex
driverID string
hosted bool
vms map[string]*fakeVM
onChange func(vm VMInfo)
}
func newFakeEngine(driverID string, hosted bool) *fakeEngine {
return &fakeEngine{driverID: driverID, hosted: hosted, vms: map[string]*fakeVM{}}
}
func (e *fakeEngine) info(vm *fakeVM) VMInfo {
info := VMInfo{Name: vm.name, DriverID: e.driverID, State: vm.state, GuestOS: &GuestOSInfo{Family: "linux"}, CPUs: 2}
if vm.ready != nil {
r := *vm.ready
info.Ready = &r
}
if vm.state == "running" {
info.Endpoints = []VMEndpoint{{Kind: "wsl", Distro: vm.name, Ready: vm.ready != nil && *vm.ready}}
}
if !e.hosted && vm.state == "running" {
pid := 4242
info.PID = &pid
}
return info
}
func (e *fakeEngine) get(name string) (*fakeVM, error) {
vm, ok := e.vms[name]
if !ok {
return nil, fmt.Errorf("VM %q not found", name)
}
return vm, nil
}
func (e *fakeEngine) list() []VMInfo {
e.mu.Lock()
defer e.mu.Unlock()
out := []VMInfo{}
for _, vm := range e.vms {
out = append(out, e.info(vm))
}
return out
}
func (e *fakeEngine) show(name string) (VMInfo, error) {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(name)
if err != nil {
return VMInfo{}, err
}
return e.info(vm), nil
}
func (e *fakeEngine) validate(req CreateRequest) []ValidationIssue {
if strings.TrimSpace(req.Name) == "" {
return []ValidationIssue{{Field: "name", Message: "name is required"}}
}
return nil
}
func (e *fakeEngine) create(req CreateRequest) error {
if issues := e.validate(req); len(issues) > 0 {
return errors.New(issues[0].Message)
}
e.mu.Lock()
defer e.mu.Unlock()
if _, ok := e.vms[req.Name]; ok {
return fmt.Errorf("VM %q exists", req.Name)
}
e.vms[req.Name] = &fakeVM{name: req.Name, state: "stopped", snaps: map[string]bool{}, disk: 1 << 30}
return nil
}
func (e *fakeEngine) notify(vm *fakeVM) {
if e.onChange != nil {
e.onChange(e.info(vm))
}
}
func (e *fakeEngine) start(name string) error {
e.mu.Lock()
vm, err := e.get(name)
if err != nil {
e.mu.Unlock()
return err
}
if vm.state == "running" {
e.mu.Unlock()
return nil
}
notReady := false
vm.state, vm.ready = "running", &notReady
e.notify(vm)
e.mu.Unlock()
time.AfterFunc(60*time.Millisecond, func() {
e.mu.Lock()
defer e.mu.Unlock()
if vm.state == "running" {
ready := true
vm.ready = &ready
e.notify(vm)
}
})
return nil
}
func (e *fakeEngine) stop(name string) error {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(name)
if err != nil {
return err
}
vm.state, vm.ready = "stopped", nil
e.notify(vm)
return nil
}
func (e *fakeEngine) delete(name string) error {
e.mu.Lock()
defer e.mu.Unlock()
if _, err := e.get(name); err != nil {
return err
}
delete(e.vms, name)
return nil
}
func (e *fakeEngine) snapshot(name, op, snap string) error {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(name)
if err != nil {
return err
}
if vm.state != "stopped" {
return errors.New("stop the VM first")
}
switch op {
case "create":
vm.snaps[snap] = true
case "restore":
if !vm.snaps[snap] {
return fmt.Errorf("no restore point %q", snap)
}
case "delete":
delete(vm.snaps, snap)
default:
return fmt.Errorf("unknown snapshot operation %q", op)
}
return nil
}
func (e *fakeEngine) snapshots(name string) ([]DiskSnapshot, error) {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(name)
if err != nil {
return nil, err
}
out := []DiskSnapshot{}
for s := range vm.snaps {
out = append(out, DiskSnapshot{ID: s, Name: s})
}
return out, nil
}
func (e *fakeEngine) clone(src, dst string) error {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(src)
if err != nil {
return err
}
if vm.state != "stopped" {
return errors.New("stop the source VM before cloning")
}
if _, ok := e.vms[dst]; ok {
return fmt.Errorf("VM %q exists", dst)
}
e.vms[dst] = &fakeVM{name: dst, state: "stopped", snaps: map[string]bool{}, disk: vm.disk}
return nil
}
func (e *fakeEngine) resize(name string) (DiskResizeResult, error) {
e.mu.Lock()
defer e.mu.Unlock()
vm, err := e.get(name)
if err != nil {
return DiskResizeResult{}, err
}
old := vm.disk
vm.disk += 1 << 30
return DiskResizeResult{Path: name + ".vhdx", OldVirtualBytes: old, NewVirtualBytes: vm.disk}, nil
}
// memDriver runs the engine in process.
type memDriver struct {
e *fakeEngine
caps []string
}
func (d *memDriver) ID() string { return d.e.driverID }
func (d *memDriver) Capabilities() []string { return d.caps }
func (d *memDriver) List(context.Context) ([]VMInfo, error) {
return d.e.list(), nil
}
func (d *memDriver) Show(_ context.Context, n string) (VMInfo, error) { return d.e.show(n) }
func (d *memDriver) ValidateCreate(_ context.Context, r CreateRequest) []ValidationIssue {
return d.e.validate(r)
}
func (d *memDriver) Create(_ context.Context, r CreateRequest) error { return d.e.create(r) }
func (d *memDriver) Start(_ context.Context, n string) error { return d.e.start(n) }
func (d *memDriver) Stop(_ context.Context, n string, _ bool) error { return d.e.stop(n) }
func (d *memDriver) Delete(_ context.Context, n string, _ bool) error {
return d.e.delete(n)
}
func (d *memDriver) ListSnapshots(_ context.Context, n string) ([]DiskSnapshot, error) {
if !has(d.caps, CapSnapshot) {
return nil, errors.New("not declared")
}
return d.e.snapshots(n)
}
func (d *memDriver) RunSnapshot(_ context.Context, n, op, s string) error {
if !has(d.caps, CapSnapshot) {
return errors.New("not declared")
}
return d.e.snapshot(n, op, s)
}
func (d *memDriver) CloneCoW(_ context.Context, src, dst string) error {
if !has(d.caps, CapCowClone) {
return errors.New("not declared")
}
return d.e.clone(src, dst)
}
func (d *memDriver) ResizeDisk(_ context.Context, n, _ string) (DiskResizeResult, error) {
if !has(d.caps, CapResize) {
return DiskResizeResult{}, errors.New("not declared")
}
return d.e.resize(n)
}
func (d *memDriver) CompactDisk(_ context.Context, n string) (DiskCompactResult, error) {
if !has(d.caps, CapResize) {
return DiskCompactResult{}, errors.New("not declared")
}
return DiskCompactResult{Path: n + ".vhdx"}, nil
}
func (d *memDriver) ReadLogs(context.Context, string, bool) (string, error) { return "log", nil }
func (d *memDriver) Phase(context.Context, string) (string, error) { return PhaseNormal, nil }
func TestRunAgainstInProcessDrivers(t *testing.T) {
hosted := &memDriver{e: newFakeEngine("test.driver.hosted", true), caps: []string{CapHosted, CapSnapshot, CapCowClone, CapResize}}
process := &memDriver{e: newFakeEngine("test.driver.process", false), caps: []string{CapSnapshot}}
Run(t, Config{Driver: hosted, PeerDriver: process, Settle: 5 * time.Second})
}
// helperSidecar serves the fake engine over JSON-RPC when the test binary is
// started with REIMS_DRIVERTEST_SIDECAR set to "hosted" or "process".
func TestHelperSidecar(t *testing.T) {
mode := os.Getenv("REIMS_DRIVERTEST_SIDECAR")
if mode == "" {
return
}
driverID := "test.driver." + mode
srv := pluginsdk.New()
hosted := mode == "hosted" || mode == "hosted-console"
e := newFakeEngine(driverID, hosted)
if hosted {
e.onChange = func(vm VMInfo) {
go func() {
_ = srv.ReportVMState(context.Background(), pluginsdk.VMStateReport{
Ref: pluginsdk.VMRef{DriverID: driverID, Name: vm.Name}, State: vm.State, Ready: vm.Ready,
Endpoints: toSDKEndpoints(vm.Endpoints), GuestOS: &pluginsdk.GuestOSInfo{Family: "linux"},
})
}()
}
}
type nameReq struct {
Name string `json:"name"`
Snapshot string `json:"snapshot"`
CloneTo string `json:"clone_name"`
Force bool `json:"force"`
}
handle := func(method string, fn func(nameReq, json.RawMessage) (any, error)) {
srv.Handle(method, func(_ context.Context, raw json.RawMessage) (any, error) {
var req nameReq
_ = json.Unmarshal(raw, &req)
return fn(req, raw)
})
}
handle("driver/list", func(nameReq, json.RawMessage) (any, error) { return map[string]any{"vms": e.list()}, nil })
handle("driver/show", func(r nameReq, _ json.RawMessage) (any, error) { return e.show(r.Name) })
handle("driver/validateCreate", func(_ nameReq, raw json.RawMessage) (any, error) {
var req CreateRequest
_ = json.Unmarshal(raw, &req)
return map[string]any{"issues": e.validate(req)}, nil
})
handle("driver/create", func(_ nameReq, raw json.RawMessage) (any, error) {
var req CreateRequest
_ = json.Unmarshal(raw, &req)
return map[string]any{}, e.create(req)
})
handle("driver/start", func(r nameReq, _ json.RawMessage) (any, error) {
if mode == "process" {
if _, err := srv.SpawnVMProcessWithRef(context.Background(), pluginsdk.VMRef{DriverID: driverID, Name: r.Name}, os.Args[0], nil, "", nil); err != nil {
return nil, err
}
}
return map[string]any{}, e.start(r.Name)
})
handle("driver/stop", func(r nameReq, _ json.RawMessage) (any, error) {
if mode == "process" {
_ = srv.StopVMProcessByRef(context.Background(), pluginsdk.VMRef{DriverID: driverID, Name: r.Name})
}
return map[string]any{}, e.stop(r.Name)
})
handle("driver/delete", func(r nameReq, _ json.RawMessage) (any, error) { return map[string]any{}, e.delete(r.Name) })
handle("driver/snapshot.list", func(r nameReq, _ json.RawMessage) (any, error) {
s, err := e.snapshots(r.Name)
return map[string]any{"snapshots": s}, err
})
for _, op := range []string{"create", "restore", "delete"} {
op := op
handle("driver/snapshot."+op, func(r nameReq, _ json.RawMessage) (any, error) {
return map[string]any{}, e.snapshot(r.Name, op, r.Snapshot)
})
}
handle("driver/clone", func(r nameReq, _ json.RawMessage) (any, error) { return map[string]any{}, e.clone(r.Name, r.CloneTo) })
handle("driver/disk.resize", func(r nameReq, _ json.RawMessage) (any, error) { return e.resize(r.Name) })
handle("driver/disk.compact", func(r nameReq, _ json.RawMessage) (any, error) {
return DiskCompactResult{Path: r.Name + ".vhdx"}, nil
})
handle("driver/logs", func(nameReq, json.RawMessage) (any, error) { return map[string]any{"content": "log"}, nil })
handle("driver/phase", func(nameReq, json.RawMessage) (any, error) { return map[string]any{"phase": PhaseNormal}, nil })
handle("driver/console.screenshot", func(r nameReq, raw json.RawMessage) (any, error) {
if _, err := e.show(r.Name); err != nil {
return nil, err
}
var req struct {
Path string `json:"path"`
}
_ = json.Unmarshal(raw, &req)
img := image.NewRGBA(image.Rect(0, 0, 8, 8))
img.SetRGBA(0, 0, color.RGBA{R: 40, G: 120, B: 220, A: 255})
f, err := os.Create(req.Path)
if err != nil {
return nil, err
}
err = png.Encode(f, img)
_ = f.Close()
return map[string]any{"format": "png", "width": 8, "height": 8}, err
})
handle("driver/console.pointer", func(r nameReq, _ json.RawMessage) (any, error) {
_, err := e.show(r.Name)
return map[string]any{"ok": true}, err
})
handle("driver/console.key", func(r nameReq, _ json.RawMessage) (any, error) {
_, err := e.show(r.Name)
return map[string]any{"ok": true}, err
})
handle("driver/console.type", func(r nameReq, raw json.RawMessage) (any, error) {
if _, err := e.show(r.Name); err != nil {
return nil, err
}
var req struct {
Text string `json:"text"`
}
_ = json.Unmarshal(raw, &req)
return map[string]any{"characters": utf8.RuneCountInString(req.Text)}, nil
})
_ = srv.Serve(context.Background())
os.Exit(0)
}
func toSDKEndpoints(in []VMEndpoint) []pluginsdk.VMEndpoint {
out := make([]pluginsdk.VMEndpoint, 0, len(in))
for _, ep := range in {
out = append(out, pluginsdk.VMEndpoint{Kind: ep.Kind, Host: ep.Host, Port: ep.Port, User: ep.User, Distro: ep.Distro, VM: ep.VM, Serial: ep.Serial, Ready: ep.Ready})
}
return out
}
func TestRunSidecarAgainstHelperDrivers(t *testing.T) {
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
mode string
caps []string
console bool
}{
{"hosted", []string{CapHosted, CapSnapshot, CapCowClone, CapResize}, false},
{"process", []string{CapSnapshot}, false},
{"hosted-console", []string{CapHosted, CapConsole}, true},
} {
t.Run(tc.mode, func(t *testing.T) {
RunSidecar(t, SidecarConfig{
ExePath: exe,
Args: []string{"-test.run=^TestHelperSidecar$"},
Env: []string{"REIMS_DRIVERTEST_SIDECAR=" + tc.mode},
DriverID: "test.driver." + tc.mode,
Capabilities: tc.caps,
Logs: true,
Phase: true,
Console: tc.console,
Suite: Config{Settle: 5 * time.Second},
})
})
}
}