Files
reims-agent/internal/mcp/test_runs.go
T

662 lines
18 KiB
Go

package mcp
import (
"context"
"crypto/rand"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// agentState keeps test orchestration state in the plugin process. A session
// is only ever disposable by the plugin that created it.
type agentState struct {
mu sync.Mutex
root string
sessions map[string]*agentSession
runs map[string]*testRun
}
type agentSession struct {
ID string
VM string
CloneVM string
Owned bool
Disposed bool
}
type testRun struct {
mu sync.Mutex
ID string
Status string
VM string
Session string
Started time.Time
Finished time.Time
Config testConfig
Result map[string]any
Cancel context.CancelFunc
Done chan struct{}
LogPath string
Files testFiles
}
type testFiles struct {
JUnit []map[string]any `json:"junit,omitempty"`
Artifacts []map[string]any `json:"artifacts,omitempty"`
}
type testConfig struct {
VM string `json:"vm"`
Isolation string `json:"isolation"`
BaseSnapshot string `json:"base_snapshot"`
Workspace string `json:"workspace"`
Sync syncConfig `json:"sync"`
Steps []testStep `json:"steps"`
JUnit []string `json:"junit"`
Artifacts []string `json:"artifacts"`
KeepOnFailure bool `json:"keep_on_failure"`
}
type syncConfig struct {
Dest string `json:"dest"`
Exclude []string `json:"exclude"`
}
type testStep struct {
Name string `json:"name"`
Run string `json:"run"`
CWD string `json:"cwd"`
Timeout string `json:"timeout"`
}
func newAgentState(root string) *agentState {
return &agentState{root: root, sessions: make(map[string]*agentSession), runs: make(map[string]*testRun)}
}
func newOpaqueID(prefix string) string {
var raw [8]byte
if _, err := rand.Read(raw[:]); err != nil {
return fmt.Sprintf("%s-%d", prefix, time.Now().UnixNano())
}
return fmt.Sprintf("%s-%x", prefix, raw)
}
func (s *Server) createSession(ctx context.Context, vm, baseSnapshot, isolation string) (map[string]any, error) {
if s.state == nil {
return nil, errors.New("plugin state is unavailable")
}
vm = strings.TrimSpace(vm)
if vm == "" {
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
}
if isolation == "" {
isolation = "clone"
}
if isolation != "clone" && isolation != "live" {
return nil, fmt.Errorf("%w: isolation must be clone or live", errInvalidParams)
}
if strings.TrimSpace(baseSnapshot) != "" {
return nil, errors.New("base_snapshot is not supported by the current host API")
}
session := &agentSession{ID: newOpaqueID("s"), VM: vm}
if isolation == "clone" {
cloneName := "__agent-" + strings.TrimPrefix(session.ID, "s-")
var cloned map[string]any
if err := s.host.Call(ctx, "host/vm.clone", map[string]any{"vm": vm, "clone_name": cloneName}, &cloned); err != nil {
return nil, err
}
cloneVM, _ := cloned["vm"].(string)
if cloneVM == "" {
cloneVM = cloneName
}
session.CloneVM, session.VM, session.Owned = cloneVM, cloneVM, true
}
s.state.mu.Lock()
s.state.sessions[session.ID] = session
s.state.mu.Unlock()
return map[string]any{"session_id": session.ID, "vm": session.VM, "owned": session.Owned, "base_snapshot": strings.TrimSpace(baseSnapshot)}, nil
}
func (s *Server) disposeSession(ctx context.Context, id string) error {
s.state.mu.Lock()
session := s.state.sessions[id]
if session == nil {
s.state.mu.Unlock()
return errors.New("session not found")
}
if session.Disposed {
s.state.mu.Unlock()
return nil
}
session.Disposed = true
s.state.mu.Unlock()
if !session.Owned {
s.state.mu.Lock()
delete(s.state.sessions, id)
s.state.mu.Unlock()
return nil
}
_ = s.host.Call(ctx, "host/vm.shutdown", map[string]any{"vm": session.VM}, &map[string]any{})
if err := s.host.Call(ctx, "host/vm.delete", map[string]any{"vm": session.VM}, &map[string]any{}); err != nil {
s.state.mu.Lock()
session.Disposed = false
s.state.mu.Unlock()
return err
}
s.state.mu.Lock()
delete(s.state.sessions, id)
s.state.mu.Unlock()
return nil
}
func (s *Server) snapshotTool(ctx context.Context, name string, raw json.RawMessage) (any, error) {
var args struct {
VM string `json:"vm"`
Name string `json:"name"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
if strings.TrimSpace(args.VM) == "" {
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
}
var out any
method := "host/vm.snapshot.list"
switch name {
case "snapshot_create":
method = "host/vm.snapshot.create"
case "snapshot_restore":
method = "host/vm.snapshot.restore"
}
params := map[string]any{"vm": args.VM}
if args.Name != "" {
params["name"] = args.Name
}
if err := s.host.Call(ctx, method, params, &out); err != nil {
return nil, err
}
return textResult(out), nil
}
func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, error) {
var args struct {
Config json.RawMessage `json:"config"`
Workspace string `json:"workspace"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
var cfg testConfig
if len(args.Config) == 0 || string(args.Config) == "null" {
return nil, fmt.Errorf("%w: config is required", errInvalidParams)
}
if err := json.Unmarshal(args.Config, &cfg); err != nil {
return nil, fmt.Errorf("%w: invalid test config: %v", errInvalidParams, err)
}
if cfg.Workspace == "" {
cfg.Workspace = args.Workspace
}
if strings.TrimSpace(cfg.VM) == "" || len(cfg.Steps) == 0 {
return nil, fmt.Errorf("%w: vm and at least one step are required", errInvalidParams)
}
if cfg.Isolation == "" {
cfg.Isolation = "clone"
}
run := &testRun{ID: newOpaqueID("r"), Status: "queued", VM: cfg.VM, Config: cfg, Done: make(chan struct{})}
ctx, cancel := context.WithCancel(parent)
run.Cancel = cancel
dir := filepath.Join(s.state.root, "runs", run.ID)
if err := os.MkdirAll(dir, 0o700); err != nil {
cancel()
return nil, err
}
run.LogPath = filepath.Join(dir, "run.log")
s.state.mu.Lock()
s.state.runs[run.ID] = run
s.state.mu.Unlock()
go s.executeTestRun(ctx, run)
return textResult(map[string]any{"run_id": run.ID, "status": run.Status}), nil
}
func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
run.mu.Lock()
run.Status, run.Started = "preparing", time.Now()
run.mu.Unlock()
logFile, _ := os.OpenFile(run.LogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if logFile != nil {
defer logFile.Close()
}
logLine := func(line string) {
if logFile != nil {
_, _ = fmt.Fprintln(logFile, time.Now().Format(time.RFC3339)+" "+line)
}
}
session, err := s.createSession(ctx, run.Config.VM, run.Config.BaseSnapshot, run.Config.Isolation)
if err == nil {
run.mu.Lock()
run.Session, _ = session["session_id"].(string)
run.VM, _ = session["vm"].(string)
run.mu.Unlock()
}
if err == nil && run.Config.Isolation == "clone" {
var out map[string]any
err = s.host.Call(ctx, "host/vm.start", map[string]any{"vm": run.VM}, &out)
}
if err == nil {
run.mu.Lock()
run.Status = "running"
run.mu.Unlock()
if result, waitErr := s.waitGuest(ctx, run.VM); waitErr != nil {
err = waitErr
} else {
logLine(fmt.Sprintf("guest ready: %v", result))
}
}
if err == nil {
err = s.syncWorkspace(ctx, run)
}
if err == nil {
for _, step := range run.Config.Steps {
if err = s.executeStep(ctx, run, step, logLine); err != nil {
break
}
}
}
var files testFiles
if err == nil {
files, err = s.collectTestFiles(ctx, run)
}
status := "passed"
if errors.Is(err, context.Canceled) {
status = "cancelled"
} else if err != nil {
status = "failed"
}
result := map[string]any{"run_id": run.ID, "status": status, "vm": run.VM, "duration_s": int(time.Since(run.Started).Seconds())}
if err != nil && !errors.Is(err, context.Canceled) {
result["error"] = err.Error()
}
if len(files.JUnit) > 0 {
result["junit"] = files.JUnit
}
if len(files.Artifacts) > 0 {
result["artifacts"] = files.Artifacts
}
if err == nil || !run.Config.KeepOnFailure {
if run.Session != "" {
_ = s.disposeSession(context.Background(), run.Session)
}
} else {
result["kept_vm"] = run.VM
}
run.mu.Lock()
run.Status, run.Finished, run.Result = status, time.Now(), result
run.mu.Unlock()
close(run.Done)
if run.Cancel != nil {
run.Cancel()
}
}
func (s *Server) waitGuest(ctx context.Context, vm string) (map[string]any, error) {
var out map[string]any
err := s.host.Call(ctx, "host/vm.get", map[string]any{"vm": vm}, &out)
if err != nil {
return nil, err
}
if _, ok := out["ssh_port"]; !ok {
return map[string]any{"ready": true}, nil
}
var result map[string]any
if err := s.invokeGuestWait(ctx, vm, &result); err != nil {
return nil, err
}
return result, nil
}
func (s *Server) invokeGuestWait(ctx context.Context, vm string, out *map[string]any) error {
address, username, err := s.guestAddress(ctx, vm)
if err != nil {
return err
}
result, err := s.guest.WaitReady(ctx, vm, address, username, 30*time.Second)
if err != nil {
return err
}
if ready, _ := result["ready"].(bool); !ready {
return errors.New("ssh_unavailable: guest SSH is not ready")
}
*out = result
return nil
}
func (s *Server) syncWorkspace(ctx context.Context, run *testRun) error {
root := strings.TrimSpace(run.Config.Workspace)
if root == "" {
return nil
}
info, err := os.Stat(root)
if err != nil || !info.IsDir() {
return fmt.Errorf("workspace is unavailable: %s", root)
}
dest := run.Config.Sync.Dest
if dest == "" {
dest = "~/work"
}
return filepath.Walk(root, func(pathName string, info os.FileInfo, walkErr error) error {
if walkErr != nil {
return walkErr
}
if info.IsDir() {
return nil
}
rel, err := filepath.Rel(root, pathName)
if err != nil || excludedPath(rel, run.Config.Sync.Exclude) {
return nil
}
remote := strings.TrimSuffix(dest, "/") + "/" + filepath.ToSlash(rel)
remote = strings.Replace(remote, "~/", "", 1)
var out map[string]any
return s.hostGuestPut(ctx, run.VM, pathName, remote, &out)
})
}
func excludedPath(rel string, patterns []string) bool {
rel = filepath.ToSlash(rel)
for _, pattern := range patterns {
pattern = strings.Trim(strings.ReplaceAll(pattern, "\\", "/"), "/")
if pattern == "" {
continue
}
if ok, _ := filepath.Match(pattern, rel); ok || strings.HasPrefix(rel, strings.TrimSuffix(pattern, "/")+"/") {
return true
}
}
return false
}
func (s *Server) hostGuestPut(ctx context.Context, vm, local, remote string, out *map[string]any) error {
return s.guestPutViaHost(ctx, vm, local, remote, out)
}
func (s *Server) guestPutViaHost(ctx context.Context, vm, local, remote string, out *map[string]any) error {
// guest_put is handled by the MCP plugin itself, so call the same SSH path
// used by the public tool without exposing a second Host API method.
address, username, err := s.guestAddress(ctx, vm)
if err != nil {
return err
}
result, err := s.guest.Put(ctx, vm, address, username, local, remote)
if err != nil {
return err
}
*out = map[string]any{"bytes": result.Bytes}
return nil
}
func (s *Server) executeStep(ctx context.Context, run *testRun, step testStep, logLine func(string)) error {
if strings.TrimSpace(step.Run) == "" {
return errors.New("test step command is empty")
}
timeout := 15 * time.Minute
if step.Timeout != "" {
if parsed, err := time.ParseDuration(step.Timeout); err == nil {
timeout = parsed
}
}
address, username, err := s.guestAddress(ctx, run.VM)
if err != nil {
return err
}
result, err := s.guest.Exec(ctx, run.VM, address, username, step.Run, step.CWD, nil, timeout)
if err != nil {
return err
}
logLine(fmt.Sprintf("step %s exit=%d: %s", step.Name, result.ExitCode, result.Output))
if result.ExitCode != 0 || result.TimedOut || result.Cancelled {
return fmt.Errorf("step %q failed with exit code %d", step.Name, result.ExitCode)
}
return nil
}
func (s *Server) collectTestFiles(ctx context.Context, run *testRun) (testFiles, error) {
var files testFiles
if len(run.Config.JUnit) == 0 && len(run.Config.Artifacts) == 0 {
return files, nil
}
dir := filepath.Dir(run.LogPath)
seen := make(map[string]struct{}, len(run.Config.JUnit)+len(run.Config.Artifacts))
collect := func(remote string, junit bool) error {
remote = strings.TrimSpace(remote)
if remote == "" {
return nil
}
if _, ok := seen[remote]; ok {
return nil
}
seen[remote] = struct{}{}
name := filepath.Base(remote)
if name == "." || name == "" || strings.ContainsAny(name, `/\\`) {
return fmt.Errorf("invalid collected file path %q", remote)
}
local := filepath.Join(dir, name)
address, username, err := s.guestAddress(ctx, run.VM)
if err != nil {
return err
}
if _, err := s.guest.Get(ctx, run.VM, address, username, remote, local); err != nil {
return err
}
entry := map[string]any{"remote_path": remote, "local_path": local}
if junit {
data, readErr := os.ReadFile(local)
if readErr != nil {
return readErr
}
entry["summary"] = parseJUnit(data)
files.JUnit = append(files.JUnit, entry)
} else {
files.Artifacts = append(files.Artifacts, entry)
}
return nil
}
for _, remote := range run.Config.JUnit {
if err := collect(remote, true); err != nil {
return files, err
}
}
for _, remote := range run.Config.Artifacts {
if err := collect(remote, false); err != nil {
return files, err
}
}
run.mu.Lock()
run.Files = files
run.mu.Unlock()
return files, nil
}
func (s *Server) waitTestRun(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
RunID string `json:"run_id"`
Timeout int `json:"timeout_ms"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
run := s.lookupRun(args.RunID)
if run == nil {
return nil, errors.New("run not found")
}
if args.Timeout <= 0 {
args.Timeout = 30000
}
timer := time.NewTimer(time.Duration(args.Timeout) * time.Millisecond)
defer timer.Stop()
select {
case <-run.Done:
case <-timer.C:
return textResult(s.runStatus(run)), nil
case <-ctx.Done():
return nil, ctx.Err()
}
return textResult(s.runStatus(run)), nil
}
func (s *Server) statusTestRun(raw json.RawMessage) (any, error) {
run, err := s.runFromRaw(raw)
if err != nil {
return nil, err
}
return textResult(s.runStatus(run)), nil
}
func (s *Server) logsTestRun(raw json.RawMessage) (any, error) {
var args struct {
RunID string `json:"run_id"`
Offset int64 `json:"offset"`
Limit int `json:"limit"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
run := s.lookupRun(args.RunID)
if run == nil {
return nil, errors.New("run not found")
}
if args.Offset < 0 {
return nil, errors.New("offset must be non-negative")
}
if args.Limit <= 0 || args.Limit > 65536 {
args.Limit = 8192
}
file, err := os.Open(run.LogPath)
if err != nil {
return nil, err
}
defer file.Close()
if _, err := file.Seek(args.Offset, io.SeekStart); err != nil {
return nil, err
}
data, err := io.ReadAll(io.LimitReader(file, int64(args.Limit)))
if err != nil {
return nil, err
}
return textResult(map[string]any{"run_id": run.ID, "offset": args.Offset, "next_offset": args.Offset + int64(len(data)), "text": string(data), "eof": len(data) < args.Limit}), nil
}
func (s *Server) resultTestRun(raw json.RawMessage) (any, error) {
run, err := s.runFromRaw(raw)
if err != nil {
return nil, err
}
run.mu.Lock()
result := run.Result
run.mu.Unlock()
if result == nil {
return textResult(s.runStatus(run)), nil
}
return textResult(result), nil
}
func (s *Server) cancelTestRun(raw json.RawMessage) (any, error) {
run, err := s.runFromRaw(raw)
if err != nil {
return nil, err
}
run.mu.Lock()
cancel := run.Cancel
run.mu.Unlock()
if cancel != nil {
cancel()
}
return textResult(map[string]any{"ok": true}), nil
}
func (s *Server) runFromRaw(raw json.RawMessage) (*testRun, error) {
var args struct {
RunID string `json:"run_id"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
run := s.lookupRun(args.RunID)
if run == nil {
return nil, errors.New("run not found")
}
return run, nil
}
func (s *Server) lookupRun(id string) *testRun {
s.state.mu.Lock()
defer s.state.mu.Unlock()
return s.state.runs[strings.TrimSpace(id)]
}
func (s *Server) runStatus(run *testRun) map[string]any {
run.mu.Lock()
defer run.mu.Unlock()
status := map[string]any{"run_id": run.ID, "status": run.Status, "vm": run.VM}
if !run.Started.IsZero() {
end := run.Finished
if end.IsZero() {
end = time.Now()
}
status["duration_s"] = int(end.Sub(run.Started).Seconds())
}
if run.Session != "" {
status["session_id"] = run.Session
}
if len(run.Files.JUnit) > 0 {
status["junit"] = run.Files.JUnit
}
if len(run.Files.Artifacts) > 0 {
status["artifacts"] = run.Files.Artifacts
}
return status
}
// JUnit reports are commonly either a single <testsuite> or a <testsuites>
// wrapper. Invalid or non-JUnit XML is treated as an empty summary.
type junitSuite struct {
Tests int `xml:"tests,attr"`
Failures int `xml:"failures,attr"`
Skipped int `xml:"skipped,attr"`
}
type junitDocument struct {
Tests int `xml:"tests,attr"`
Failures int `xml:"failures,attr"`
Skipped int `xml:"skipped,attr"`
Suites []junitSuite `xml:"testsuite"`
}
func parseJUnit(data []byte) map[string]any {
var doc junitDocument
if xml.Unmarshal(data, &doc) != nil {
return map[string]any{}
}
tests, failures, skipped := doc.Tests, doc.Failures, doc.Skipped
if len(doc.Suites) > 0 {
tests, failures, skipped = 0, 0, 0
for _, suite := range doc.Suites {
tests += suite.Tests
failures += suite.Failures
skipped += suite.Skipped
}
}
passed := tests - failures - skipped
if passed < 0 {
passed = 0
}
return map[string]any{"tests": tests, "passed": passed, "failed": failures, "skipped": skipped}
}