diff --git a/internal/mcp/test_runs.go b/internal/mcp/test_runs.go index c7e25c6..482db49 100644 --- a/internal/mcp/test_runs.go +++ b/internal/mcp/test_runs.go @@ -57,6 +57,7 @@ type testConfig struct { VM string `json:"vm"` Isolation string `json:"isolation"` BaseSnapshot string `json:"base_snapshot"` + BootTimeout string `json:"boot_timeout,omitempty"` Workspace string `json:"workspace"` Sync syncConfig `json:"sync"` Steps []testStep `json:"steps"` @@ -65,6 +66,31 @@ type testConfig struct { KeepOnFailure bool `json:"keep_on_failure"` } +const ( + defaultGuestWaitTimeout = 240 * time.Second + maxGuestWaitTimeout = 600 * time.Second +) + +var ( + guestWaitChunkTimeout = 30 * time.Second + guestWaitRetryDelay = 500 * time.Millisecond + waitGuestReadyFn = func(s *Server, ctx context.Context, vm, address, username string, timeout time.Duration) (map[string]any, error) { + return s.guest.WaitReady(ctx, vm, address, username, timeout) + } +) + +func resolveGuestWaitTimeout(raw string) (time.Duration, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return defaultGuestWaitTimeout, nil + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 || d > maxGuestWaitTimeout { + return 0, fmt.Errorf("%w: boot_timeout must be a valid duration between 1ms and %s", errInvalidParams, maxGuestWaitTimeout) + } + return d, nil +} + type syncConfig struct { Dest string `json:"dest"` Exclude []string `json:"exclude"` @@ -213,6 +239,9 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, if strings.TrimSpace(cfg.VM) == "" || len(cfg.Steps) == 0 { return nil, fmt.Errorf("%w: vm and at least one step are required", errInvalidParams) } + if _, err := resolveGuestWaitTimeout(cfg.BootTimeout); err != nil { + return nil, err + } if _, err := s.vmInfo(parent, cfg.VM); err != nil { return nil, err } @@ -265,7 +294,10 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) { run.mu.Lock() run.Status = "running" run.mu.Unlock() - if result, waitErr := s.waitGuest(ctx, run.VM); waitErr != nil { + waitTimeout, timeoutErr := resolveGuestWaitTimeout(run.Config.BootTimeout) + if timeoutErr != nil { + err = timeoutErr + } else if result, waitErr := s.waitGuest(ctx, run.VM, waitTimeout); waitErr != nil { err = waitErr } else { logLine(fmt.Sprintf("guest ready: %v", result)) @@ -334,7 +366,7 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) { } } -func (s *Server) waitGuest(ctx context.Context, vm string) (map[string]any, error) { +func (s *Server) waitGuest(ctx context.Context, vm string, totalTimeout time.Duration) (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 { @@ -344,26 +376,85 @@ func (s *Server) waitGuest(ctx context.Context, vm string) (map[string]any, erro return map[string]any{"ready": true}, nil } var result map[string]any - if err := s.invokeGuestWait(ctx, vm, &result); err != nil { + if err := s.invokeGuestWait(ctx, vm, totalTimeout, &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 +func (s *Server) invokeGuestWait(ctx context.Context, vm string, totalTimeout time.Duration, out *map[string]any) error { + if totalTimeout <= 0 { + totalTimeout = defaultGuestWaitTimeout } - result, err := s.guest.WaitReady(ctx, vm, address, username, 30*time.Second) - if err != nil { - return err + deadline := time.Now().Add(totalTimeout) + var lastMsg string + + for { + if err := ctx.Err(); err != nil { + return err + } + var vmState map[string]any + if err := s.host.Call(ctx, "host/vm.get", map[string]any{"vm": vm}, &vmState); err == nil { + if st, _ := vmState["state"].(string); st != "" { + switch strings.ToLower(strings.TrimSpace(st)) { + case "stopped", "broken", "error", "suspended": + return fmt.Errorf("ssh_unavailable: VM %s entered state %q before guest SSH became ready", vm, st) + } + } + } + + remaining := time.Until(deadline) + if remaining < time.Millisecond { + break + } + chunk := guestWaitChunkTimeout + if chunk <= 0 || chunk > 30*time.Second { + chunk = 30 * time.Second + } + if remaining < chunk { + chunk = remaining + } + + address, username, err := s.guestAddress(ctx, vm) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + lastMsg = err.Error() + } else { + result, err := waitGuestReadyFn(s, ctx, vm, address, username, chunk) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + lastMsg = err.Error() + } else if ready, _ := result["ready"].(bool); ready { + *out = result + return nil + } else if msg, _ := result["message"].(string); strings.TrimSpace(msg) != "" { + lastMsg = strings.TrimSpace(msg) + } + } + + if time.Until(deadline) < time.Millisecond { + break + } + retryDelay := min(guestWaitRetryDelay, time.Until(deadline)) + if retryDelay > 0 { + timer := time.NewTimer(retryDelay) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } } - if ready, _ := result["ready"].(bool); !ready { - return errors.New("ssh_unavailable: guest SSH is not ready") + + if lastMsg != "" { + return fmt.Errorf("ssh_unavailable: guest SSH is not ready after %s (%s); ensure Remote Login is persisted in guest (launchctl enable system/com.openssh.sshd)", totalTimeout, lastMsg) } - *out = result - return nil + return fmt.Errorf("ssh_unavailable: guest SSH is not ready after %s; ensure Remote Login is persisted in guest (launchctl enable system/com.openssh.sshd)", totalTimeout) } func (s *Server) syncWorkspace(ctx context.Context, run *testRun) error { diff --git a/internal/mcp/test_runs_wait_test.go b/internal/mcp/test_runs_wait_test.go new file mode 100644 index 0000000..d6d9021 --- /dev/null +++ b/internal/mcp/test_runs_wait_test.go @@ -0,0 +1,145 @@ +package mcp + +import ( + "context" + "strings" + "testing" + "time" +) + +type waitTestHost struct { + state string + sshPort int +} + +func (h *waitTestHost) Call(_ context.Context, method string, _ any, out any) error { + if method == "host/vm.get" { + m := out.(*map[string]any) + *m = map[string]any{ + "name": "clone-1", + "state": h.state, + "ssh_port": float64(h.sshPort), + "phase": "normal", + } + return nil + } + if method == "host/secret.get" { + m := out.(*map[string]any) + *m = map[string]any{"value": "reims"} + return nil + } + return nil +} + +func TestInvokeGuestWaitRetriesUntilReady(t *testing.T) { + origChunk := guestWaitChunkTimeout + origDelay := guestWaitRetryDelay + origFn := waitGuestReadyFn + t.Cleanup(func() { + guestWaitChunkTimeout = origChunk + guestWaitRetryDelay = origDelay + waitGuestReadyFn = origFn + }) + guestWaitChunkTimeout = 20 * time.Millisecond + guestWaitRetryDelay = 5 * time.Millisecond + + calls := 0 + waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, timeout time.Duration) (map[string]any, error) { + calls++ + if timeout > 20*time.Millisecond { + t.Fatalf("chunk timeout = %v, want <= 20ms", timeout) + } + if calls < 3 { + return map[string]any{"ready": false, "message": "connection refused"}, nil + } + return map[string]any{"ready": true}, nil + } + + srv := New() + srv.BindHost(&waitTestHost{state: "running", sshPort: 2222}) + + var out map[string]any + if err := srv.invokeGuestWait(context.Background(), "clone-1", 500*time.Millisecond, &out); err != nil { + t.Fatalf("invokeGuestWait failed: %v", err) + } + if calls != 3 { + t.Fatalf("calls = %d, want 3", calls) + } + if ready, _ := out["ready"].(bool); !ready { + t.Fatalf("out = %+v, want ready=true", out) + } +} + +func TestInvokeGuestWaitFailsFastWhenVMStops(t *testing.T) { + origChunk := guestWaitChunkTimeout + origDelay := guestWaitRetryDelay + origFn := waitGuestReadyFn + t.Cleanup(func() { + guestWaitChunkTimeout = origChunk + guestWaitRetryDelay = origDelay + waitGuestReadyFn = origFn + }) + guestWaitChunkTimeout = 20 * time.Millisecond + guestWaitRetryDelay = 5 * time.Millisecond + + host := &waitTestHost{state: "running", sshPort: 2222} + calls := 0 + waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, _ time.Duration) (map[string]any, error) { + calls++ + host.state = "stopped" + return map[string]any{"ready": false, "message": "eof"}, nil + } + + srv := New() + srv.BindHost(host) + + var out map[string]any + err := srv.invokeGuestWait(context.Background(), "clone-1", 2*time.Second, &out) + if err == nil || !strings.Contains(err.Error(), `entered state "stopped"`) { + t.Fatalf("err = %v, want stopped fail-fast error", err) + } + if calls != 1 { + t.Fatalf("calls = %d, want 1", calls) + } +} + +func TestInvokeGuestWaitTimesOutWithActionableHint(t *testing.T) { + origChunk := guestWaitChunkTimeout + origDelay := guestWaitRetryDelay + origFn := waitGuestReadyFn + t.Cleanup(func() { + guestWaitChunkTimeout = origChunk + guestWaitRetryDelay = origDelay + waitGuestReadyFn = origFn + }) + guestWaitChunkTimeout = 15 * time.Millisecond + guestWaitRetryDelay = 5 * time.Millisecond + + waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, _ time.Duration) (map[string]any, error) { + return map[string]any{"ready": false, "message": "connection refused"}, nil + } + + srv := New() + srv.BindHost(&waitTestHost{state: "running", sshPort: 2222}) + + var out map[string]any + err := srv.invokeGuestWait(context.Background(), "clone-1", 40*time.Millisecond, &out) + if err == nil || !strings.Contains(err.Error(), "ssh_unavailable") || !strings.Contains(err.Error(), "launchctl enable system/com.openssh.sshd") { + t.Fatalf("err = %v, want actionable ssh_unavailable timeout", err) + } +} + +func TestResolveGuestWaitTimeout(t *testing.T) { + if d, err := resolveGuestWaitTimeout(""); err != nil || d != defaultGuestWaitTimeout { + t.Fatalf("empty = (%v, %v), want (%v, nil)", d, err, defaultGuestWaitTimeout) + } + if d, err := resolveGuestWaitTimeout("3m"); err != nil || d != 3*time.Minute { + t.Fatalf("3m = (%v, %v)", d, err) + } + if _, err := resolveGuestWaitTimeout("0s"); err == nil { + t.Fatal("0s must fail") + } + if _, err := resolveGuestWaitTimeout("15m"); err == nil { + t.Fatal("15m above max must fail") + } +}