diff --git a/tstest/natlab/vmtest/qemu.go b/tstest/natlab/vmtest/qemu.go index 73b265078..a077cad3f 100644 --- a/tstest/natlab/vmtest/qemu.go +++ b/tstest/natlab/vmtest/qemu.go @@ -6,7 +6,6 @@ package vmtest import ( "bytes" "context" - "encoding/json" "fmt" "net" "os" @@ -117,6 +116,7 @@ func (e *Env) startGokrazyQEMU(n *Node) error { } logPath := filepath.Join(e.tempDir, n.name+".log") + n.qmpSock = filepath.Join(e.sockDir, n.name+"-qmp.sock") args := []string{ "-M", "microvm,isa-serial=off", @@ -130,6 +130,7 @@ func (e *Env) startGokrazyQEMU(n *Node) error { "-device", "virtio-rng-device", "-chardev", "file,id=virtiocon0,path=" + logPath, "-device", "virtconsole,chardev=virtiocon0", + "-qmp", "unix:" + n.qmpSock + ",server,nowait", } // Add network devices — one per NIC. @@ -163,7 +164,7 @@ func (e *Env) startCloudQEMU(n *Node) error { } logPath := filepath.Join(e.tempDir, n.name+".log") - qmpSock := filepath.Join(e.sockDir, n.name+"-qmp.sock") + n.qmpSock = filepath.Join(e.sockDir, n.name+"-qmp.sock") args := []string{ "-machine", "q35", @@ -174,7 +175,7 @@ func (e *Env) startCloudQEMU(n *Node) error { "-drive", fmt.Sprintf("file=%s,if=virtio,media=cdrom,readonly=on", seedISO), "-smbios", "type=1,serial=ds=nocloud", "-serial", "file:" + logPath, - "-qmp", "unix:" + qmpSock + ",server,nowait", + "-qmp", "unix:" + n.qmpSock + ",server,nowait", } // Add network devices — one per NIC. @@ -203,7 +204,7 @@ func (e *Env) startCloudQEMU(n *Node) error { } // Query QMP to find the actual SSH port that QEMU allocated. - port, err := qmpQueryHostFwd(qmpSock) + port, err := qmpQueryHostFwd(n.qmpSock) if err != nil { return fmt.Errorf("querying SSH port via QMP: %w", err) } @@ -377,35 +378,11 @@ var hostFwdRe = regexp.MustCompile(`TCP\[HOST_FORWARD\]\s+\d+\s+127\.0\.0\.1\s+( // qmpQueryHostFwd connects to a QEMU QMP socket and queries the host port // assigned to the first TCP host forward rule (the SSH debug port). func qmpQueryHostFwd(sockPath string) (int, error) { - // Wait for the QMP socket to appear. - var conn net.Conn - for range 50 { - var err error - conn, err = net.Dial("unix", sockPath) - if err == nil { - break - } - time.Sleep(100 * time.Millisecond) - } - if conn == nil { - return 0, fmt.Errorf("QMP socket %s not available", sockPath) - } - defer conn.Close() - conn.SetDeadline(time.Now().Add(20 * time.Second)) - - // Read the QMP greeting. - var greeting json.RawMessage - dec := json.NewDecoder(conn) - if err := dec.Decode(&greeting); err != nil { - return 0, fmt.Errorf("reading QMP greeting: %w", err) - } - - // Send qmp_capabilities to initialize. - fmt.Fprintf(conn, `{"execute":"qmp_capabilities"}`+"\n") - var capsResp json.RawMessage - if err := dec.Decode(&capsResp); err != nil { - return 0, fmt.Errorf("reading qmp_capabilities response: %w", err) + c, err := dialQMP(sockPath, 5*time.Second) + if err != nil { + return 0, err } + defer c.Close() // Poll "info usernet" until the SLIRP host-forward rule appears. // On slow runners (e.g. GitHub Actions) QEMU sometimes returns an @@ -414,15 +391,10 @@ func qmpQueryHostFwd(sockPath string) (int, error) { deadline := time.Now().Add(10 * time.Second) var lastReturn string for { - fmt.Fprintf(conn, `{"execute":"human-monitor-command","arguments":{"command-line":"info usernet"}}`+"\n") - var hmpResp struct { - Return string `json:"return"` + if err := c.command("human-monitor-command", map[string]any{"command-line": "info usernet"}, &lastReturn); err != nil { + return 0, fmt.Errorf("info usernet: %w", err) } - if err := dec.Decode(&hmpResp); err != nil { - return 0, fmt.Errorf("reading info usernet response: %w", err) - } - lastReturn = hmpResp.Return - if m := hostFwdRe.FindStringSubmatch(hmpResp.Return); m != nil { + if m := hostFwdRe.FindStringSubmatch(lastReturn); m != nil { return strconv.Atoi(m[1]) } if time.Now().After(deadline) { diff --git a/tstest/natlab/vmtest/qmp.go b/tstest/natlab/vmtest/qmp.go new file mode 100644 index 000000000..1fd9f5c6b --- /dev/null +++ b/tstest/natlab/vmtest/qmp.go @@ -0,0 +1,204 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package vmtest + +import ( + "encoding/json" + "fmt" + "net" + "time" +) + +// qmpClient is a minimal client for QEMU's QMP (QEMU Machine Protocol) +// monitor socket. It supports just what the harness needs: the capabilities +// handshake plus simple synchronous commands (stop, cont, query-status, +// human-monitor-command). See +// https://www.qemu.org/docs/master/interop/qmp-spec.html. +type qmpClient struct { + conn net.Conn + dec *json.Decoder +} + +// dialQMP connects to the QMP unix socket at sockPath, waiting up to +// dialTimeout for the socket to appear (QEMU creates it asynchronously at +// startup), and performs the protocol handshake (greeting + qmp_capabilities) +// so the returned client is ready to execute commands. The caller must Close +// the client when done; QEMU's QMP chardev accepts one client at a time, so +// holding a client open blocks other dialers. +func dialQMP(sockPath string, dialTimeout time.Duration) (*qmpClient, error) { + var conn net.Conn + deadline := time.Now().Add(dialTimeout) + for { + var err error + conn, err = net.Dial("unix", sockPath) + if err == nil { + break + } + if time.Now().After(deadline) { + return nil, fmt.Errorf("QMP socket %s not available: %w", sockPath, err) + } + time.Sleep(100 * time.Millisecond) + } + // I/O deadline for the handshake below; command() refreshes it + // per command, so a qmpClient may be held open indefinitely. + conn.SetDeadline(time.Now().Add(20 * time.Second)) + c := &qmpClient{conn: conn, dec: json.NewDecoder(conn)} + + // Read the QMP greeting. + var greeting json.RawMessage + if err := c.dec.Decode(&greeting); err != nil { + conn.Close() + return nil, fmt.Errorf("reading QMP greeting: %w", err) + } + // Enter command mode. + if err := c.command("qmp_capabilities", nil, nil); err != nil { + conn.Close() + return nil, err + } + return c, nil +} + +func (c *qmpClient) Close() error { return c.conn.Close() } + +// command executes a single QMP command and decodes its "return" value into +// out (which may be nil to discard it). args, if non-nil, is marshaled as the +// command's "arguments" object. Asynchronous QMP events (such as the STOP and +// RESUME events that the stop/cont commands themselves trigger) are skipped +// while waiting for the command's response. +func (c *qmpClient) command(name string, args, out any) error { + req := map[string]any{"execute": name} + if args != nil { + req["arguments"] = args + } + b, err := json.Marshal(req) + if err != nil { + return err + } + // Refresh the I/O deadline for this command, so a long-lived client + // doesn't inherit a stale deadline from dial time or a prior command. + c.conn.SetDeadline(time.Now().Add(20 * time.Second)) + if _, err := c.conn.Write(append(b, '\n')); err != nil { + return fmt.Errorf("writing %s command: %w", name, err) + } + for { + var resp struct { + Return json.RawMessage `json:"return"` + Error *struct { + Class string `json:"class"` + Desc string `json:"desc"` + } `json:"error"` + Event string `json:"event"` + } + if err := c.dec.Decode(&resp); err != nil { + return fmt.Errorf("reading %s response: %w", name, err) + } + if resp.Event != "" { + continue // async event, not our response + } + if resp.Error != nil { + return fmt.Errorf("%s: %s: %s", name, resp.Error.Class, resp.Error.Desc) + } + if out != nil { + if err := json.Unmarshal(resp.Return, out); err != nil { + return fmt.Errorf("decoding %s return value: %w", name, err) + } + } + return nil + } +} + +// vmStatus returns the VM's run state ("running", "paused", ...) via the +// query-status command. +func (c *qmpClient) vmStatus() (string, error) { + var st struct { + Running bool `json:"running"` + Status string `json:"status"` + } + if err := c.command("query-status", nil, &st); err != nil { + return "", err + } + return st.Status, nil +} + +// qmp dials the node's QMP monitor socket. It returns an error for nodes not +// backed by QEMU: macOS/tailmac VMs (Apple Virtualization.framework) have no +// QMP monitor. +func (n *Node) qmp() (*qmpClient, error) { + if n.qmpSock == "" { + return nil, fmt.Errorf("node %s (%s) is not QEMU-backed; QMP not supported", n.name, n.os.Name) + } + return dialQMP(n.qmpSock, 5*time.Second) +} + +// Suspend pauses n's virtual machine via the QMP "stop" command. As seen from +// the network it models a host suspend (a laptop lid close): the guest's +// vCPUs halt, QEMU stops servicing the VM's network devices so packets sent +// to it while stopped are dropped, and the rest of the world (peers, relays, +// DERP, control) keeps running in real time and may expire state that +// references the suspended node — the ingredient needed to reproduce +// suspend-induced path-death bugs like tailscale/tailscale#20082, where a +// peer relay reaps an idle session while one endpoint sleeps. +// +// Guest time behavior (verified empirically by TestSuspendResume): QEMU's +// virtual clock — which drives the guest's clocksources (kvmclock; the HPET +// that the gokrazy kernel is pinned to via clocksource=hpet) and its timer +// devices — pauses while the VM is stopped, and "cont" does not advance it. +// The guest therefore does not observe the stopped interval at all: on +// Resume its CLOCK_MONOTONIC continues where it left off (just as on a real +// suspend) and its timers simply fire late. Unlike a real laptop wake, +// though, the guest receives no resume notification and does not re-read the +// RTC (under the harness's default -rtc behavior, base=utc clock=host, the +// RTC would report real host time if re-read), so the guest's wall clock +// lags real time by the suspend duration until NTP would step it. The +// suspend-bug-relevant asymmetry is the same in both cases: the guest's +// timers are frozen while everyone else's keep counting, so on resume the +// guest experiences the rest of the world having jumped ahead. +// +// Suspend verifies via QMP query-status that the VM actually entered the +// "paused" run state. It is only supported on QEMU-backed nodes (gokrazy and +// cloud images) and fatals the test for macOS/tailmac nodes. Use [Env.Resume] +// to un-pause. +func (e *Env) Suspend(n *Node) { + e.t.Helper() + c, err := n.qmp() + if err != nil { + e.t.Fatalf("Suspend(%s): %v", n.name, err) + } + defer c.Close() + if err := c.command("stop", nil, nil); err != nil { + e.t.Fatalf("Suspend(%s): %v", n.name, err) + } + st, err := c.vmStatus() + if err != nil { + e.t.Fatalf("Suspend(%s): query-status: %v", n.name, err) + } + if st != "paused" { + e.t.Fatalf("Suspend(%s): VM status = %q, want \"paused\"", n.name, st) + } + e.t.Logf("[%s] VM suspended (QMP stop; status=%s)", n.name, st) +} + +// Resume un-pauses a VM previously paused by [Env.Suspend], via the QMP +// "cont" command, and verifies via query-status that it is running again. +// See [Env.Suspend] for what the guest observes on resume. It fatals the +// test on error, and is only supported on QEMU-backed nodes. +func (e *Env) Resume(n *Node) { + e.t.Helper() + c, err := n.qmp() + if err != nil { + e.t.Fatalf("Resume(%s): %v", n.name, err) + } + defer c.Close() + if err := c.command("cont", nil, nil); err != nil { + e.t.Fatalf("Resume(%s): %v", n.name, err) + } + st, err := c.vmStatus() + if err != nil { + e.t.Fatalf("Resume(%s): query-status: %v", n.name, err) + } + if st != "running" { + e.t.Fatalf("Resume(%s): VM status = %q, want \"running\"", n.name, st) + } + e.t.Logf("[%s] VM resumed (QMP cont; status=%s)", n.name, st) +} diff --git a/tstest/natlab/vmtest/suspend_test.go b/tstest/natlab/vmtest/suspend_test.go new file mode 100644 index 000000000..6786e62f0 --- /dev/null +++ b/tstest/natlab/vmtest/suspend_test.go @@ -0,0 +1,185 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package vmtest_test + +import ( + "context" + "net/http" + "testing" + "time" + + "tailscale.com/client/local" + "tailscale.com/tailcfg" + "tailscale.com/tstest" + "tailscale.com/tstest/natlab/vmtest" +) + +// TestSuspendResume is a smoke test for [vmtest.Env.Suspend] and +// [vmtest.Env.Resume] (QMP stop/cont on a QEMU-backed node). +// +// Topology: two gokrazy nodes a and b on easy NATs. The test establishes a +// WireGuard tunnel between them, suspends b, and asserts three things: +// +// 1. While b is suspended, packets to it black-hole: a single TSMP ping +// from a gets no answer within its 5s budget (QEMU drops packets sent +// to a stopped VM). +// 2. b's guest clock pauses while suspended: the guest's wall clock +// (sampled via the Date header on HTTP responses from its in-guest test +// agent, 1s granularity) advances by roughly suspendDur less than the +// host's clock across the suspend window. This is the "frozen timers" +// property that makes Suspend useful for reproducing suspend-induced +// path-death bugs like tailscale/tailscale#20082. +// 3. Connectivity recovers after Resume, within a bounded budget. +// +// Budgets: +// +// - Initial a→b TSMP ping: 30s, same generous bring-up budget as +// TestDiscoKeyChange (first-time tunnel setup, not what's under test). +// - Suspend window: 15s total. Long enough that the 1s-granularity guest +// clock check has plenty of margin (we require ≥10s of observed guest +// clock lag) and that the in-window ping demonstrably black-holes, while +// staying cheap for CI. Deliberately shorter than any tailscaled/relay +// session timeout: this test only smoke-tests the suspend mechanism, not +// session-expiry recovery. +// - Post-resume recovery ping: 30s. In practice recovery is near-immediate +// (the 15s pause is far shorter than the WireGuard session lifetime and +// both peers' endpoints are unchanged, so the first retried packet gets +// through; observed locally at <1s). The budget mostly absorbs the +// suspended node's own wake-up transient (virtio queue refill, agent +// connection retries) on slow CI hosts. +func TestSuspendResume(t *testing.T) { + env := vmtest.New(t) + a := easy(env) + b := easy(env) + + tunnelStep := env.AddStep("Ping " + a.Name() + " → " + b.Name() + " TSMP (establish tunnel)") + suspendStep := env.AddStep("Suspend " + b.Name()) + blackholeStep := env.AddStep("Verify traffic to suspended " + b.Name() + " black-holes") + resumeStep := env.AddStep("Resume " + b.Name()) + clockStep := env.AddStep("Verify " + b.Name() + "'s guest clock paused while suspended") + recoverStep := env.AddStep("Ping " + a.Name() + " → " + b.Name() + " TSMP (recovery after resume)") + + env.Start() + + tunnelStep.Begin() + if err := env.Ping(a, b, tailcfg.PingTSMP, 30*time.Second); err != nil { + tunnelStep.Fatal(err) + } + tunnelStep.End(nil) + + // Capture b's Tailscale IP now; while b is suspended we can't ask it. + bIP := env.Status(b).Self.TailscaleIPs[0] + + hostBefore := time.Now() + guestBefore := guestWallClock(t, b) + + const suspendDur = 15 * time.Second + suspendStep.Begin() + env.Suspend(b) + suspendedAt := time.Now() + suspendStep.End(nil) + + // While b is stopped, a's TSMP pings to it must go unanswered. A single + // non-retried ping with a 5s budget: far longer than the <100ms a direct + // LAN-speed TSMP round trip takes once a tunnel is up, so a success here + // would mean the VM wasn't really paused. The failure must also be a + // genuine timeout — the request running essentially the full budget while + // a's tailscaled waits for a reply that never comes — and not some instant + // error from a broken ping path (a's agent unreachable, bad IP, etc.), + // which would pass a mere "any error" check without proving packet drop. + blackholeStep.Begin() + pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + pingStart := time.Now() + pr, err := a.Agent().PingWithOpts(pingCtx, bIP, tailcfg.PingTSMP, local.PingOpts{}) + pingElapsed := time.Since(pingStart) + cancel() + if err == nil && pr.Err == "" { + blackholeStep.Fatalf("TSMP ping from %s to suspended %s unexpectedly succeeded", a.Name(), b.Name()) + } + prErr := "" + if err == nil { + prErr = pr.Err + } + if pingElapsed < 4*time.Second { + blackholeStep.Fatalf("TSMP ping from %s to suspended %s failed after only %v (err=%v, pr.Err=%q), want a ≥4s timeout of the 5s budget; ping path looks broken rather than black-holed", + a.Name(), b.Name(), pingElapsed.Round(time.Millisecond), err, prErr) + } + t.Logf("ping to suspended %s timed out as expected after %v (err=%v, pr.Err=%q)", + b.Name(), pingElapsed.Round(time.Millisecond), err, prErr) + blackholeStep.End(nil) + + // Keep b suspended for suspendDur total. + if d := time.Until(suspendedAt.Add(suspendDur)); d > 0 { + time.Sleep(d) + } + + resumeStep.Begin() + env.Resume(b) + resumeStep.End(nil) + + // The guest's clocks pause across QMP stop/cont (see [vmtest.Env.Suspend]), + // so b's wall clock should now lag the host's by ≈suspendDur — bounded on + // both sides. Too little lag means the guest clock never paused (or QEMU + // advanced it on cont); too much means it stopped permanently or stepped + // backward. Both clocks run at the same rate outside the suspend window, + // so extra latency in sampling guestAfter doesn't change the measured lag. + // + // clockSlack absorbs the measurement noise: the Date header has 1s + // granularity, and two samples bracket the window, so up to ~2s of + // quantization error; plus sub-second QMP command latency and goroutine + // scheduling skew around the stop/cont edges. 5s is comfortably above all + // of that while still far below suspendDur (15s), so the window cleanly + // separates "paused for the suspend window" from both "never paused" + // (lag ≈ 0) and "still frozen/stepped backward" (lag ≫ suspendDur). + const clockSlack = 5 * time.Second + clockStep.Begin() + guestAfter := guestWallClock(t, b) + hostElapsed := time.Since(hostBefore) + guestElapsed := guestAfter.Sub(guestBefore) + lag := hostElapsed - guestElapsed + t.Logf("clock check: host elapsed %v, guest elapsed %v, guest clock lag %v (suspended for %v)", + hostElapsed.Round(time.Millisecond), guestElapsed, lag.Round(time.Millisecond), suspendDur) + if lag < suspendDur-clockSlack { + clockStep.Fatalf("guest clock lag = %v, want ≥ %v; guest clock doesn't appear to have paused during suspend", + lag.Round(time.Millisecond), suspendDur-clockSlack) + } + if lag > suspendDur+clockSlack { + clockStep.Fatalf("guest clock lag = %v, want ≤ %v; guest clock appears to have stopped permanently or stepped backward", + lag.Round(time.Millisecond), suspendDur+clockSlack) + } + clockStep.End(nil) + + recoverStep.Begin() + if err := env.Ping(a, b, tailcfg.PingTSMP, 30*time.Second); err != nil { + recoverStep.Fatal(err) + } + recoverStep.End(nil) +} + +// guestWallClock returns n's current wall-clock time as reported by the Date +// header (1s granularity) on an HTTP response from its in-guest test agent. +// It retries for up to 30s — right after a resume, the agent's connection to +// the test harness may need a moment to recover — and fatals on failure. +func guestWallClock(t *testing.T, n *vmtest.Node) time.Time { + t.Helper() + var got time.Time + if err := tstest.WaitFor(30*time.Second, func() error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, "GET", "http://unused/ip", nil) + if err != nil { + return err + } + res, err := n.Agent().HTTPClient.Do(req) + if err != nil { + return err + } + res.Body.Close() + got, err = http.ParseTime(res.Header.Get("Date")) + return err + }); err != nil { + t.Fatalf("guestWallClock(%s): %v", n.Name(), err) + } + return got +} diff --git a/tstest/natlab/vmtest/vmtest.go b/tstest/natlab/vmtest/vmtest.go index fdf4d4245..847369ba2 100644 --- a/tstest/natlab/vmtest/vmtest.go +++ b/tstest/natlab/vmtest/vmtest.go @@ -430,7 +430,8 @@ type Node struct { advertiseRoutes string snatSubnetRoutes *bool // nil means default (true) webServerPort int - sshPort int // host port for SSH debug access (cloud VMs only) + sshPort int // host port for SSH debug access (cloud VMs only) + qmpSock string // path to QMP monitor unix socket (QEMU VMs only) } // AddNode creates a new VM node. The name is used for identification and as the