diff --git a/derp/derpserver/derpserver_test.go b/derp/derpserver/derpserver_test.go index 2a584f3c5c..d216a088c4 100644 --- a/derp/derpserver/derpserver_test.go +++ b/derp/derpserver/derpserver_test.go @@ -2710,9 +2710,9 @@ func TestPacketBufPool(t *testing.T) { // frameCountConn is a derp.Conn that parses the DERP frames written to // it, counting packet frames and recording how many preceded the first -// pong. +// pong. It is not safe for concurrent use. type frameCountConn struct { - mu sync.Mutex + onWrite func() // if non-nil, called at the start of each Write partial []byte // bytes of a frame not yet fully written packets int // packet frames written pongs int // pong frames written @@ -2720,8 +2720,9 @@ type frameCountConn struct { } func (c *frameCountConn) Write(p []byte) (int, error) { - c.mu.Lock() - defer c.mu.Unlock() + if c.onWrite != nil { + c.onWrite() + } c.partial = append(c.partial, p...) for len(c.partial) >= derp.FrameHeaderLen { ft := derp.FrameType(c.partial[0]) @@ -2743,12 +2744,6 @@ func (c *frameCountConn) Write(p []byte) (int, error) { return len(p), nil } -func (c *frameCountConn) stats() (packets, pongs, packetsAtPong int) { - c.mu.Lock() - defer c.mu.Unlock() - return c.packets, c.pongs, c.packetsAtPong -} - func (c *frameCountConn) Close() error { return nil } func (c *frameCountConn) LocalAddr() net.Addr { return &net.TCPAddr{} } func (c *frameCountConn) SetDeadline(time.Time) error { return nil } @@ -2759,11 +2754,46 @@ func (c *frameCountConn) SetWriteDeadline(time.Time) error { return nil } // keeping a client's send queue topped up can't hold the writer in its // packet drain forever: a pong queued during the flood is written // after at most a queue's depth worth of further packets. +// +// The test is single-threaded so that it is deterministic: it runs the +// writer inline, as [sclient.onKeepAliveTimer] does, and floods the +// queue and queues the pong from the fake connection's Write, which +// the writer calls in the middle of its drain. Earlier versions raced +// a flooding goroutine against a writer goroutine and were flaky under +// CPU load; see https://github.com/tailscale/tailscale/issues/22347 +// and https://github.com/tailscale/tailscale/issues/22614. func TestWriterFloodDoesNotStarveControlFrames(t *testing.T) { s := New(key.NewNode(), t.Logf) defer s.Close() depth := s.perClientSendQueueDepth + // Queue the pong at every point in a window of depth+1 packets, + // once the flood is a full pass in. Whatever a pass's budget is, if + // it is more than depth then one of these points is far enough + // from the end of its pass for the pong to be late. + for offset := range depth + 1 { + pongAt := depth + offset + got := floodWriterAndQueuePong(t, s, pongAt) + if t.Failed() { + return + } + // The pass in progress may finish its budget of depth + // packets first, and then the pong goes out before the next + // pass's packets, so at most depth more packets precede it. + if got > depth { + t.Fatalf("pong queued after %d packets was written after %d more; want at most %d (the queue depth)", pongAt, got, depth) + } + } +} + +// floodWriterAndQueuePong runs the writer of a new client of s while +// keeping the client's send queue full, queues a pong once the writer +// has sent pongAt packets, and returns how many more packets the +// writer sent before the pong. It marks t failed if the writer did not +// behave as a flooded writer should. +func floodWriterAndQueuePong(t *testing.T, s *Server, pongAt int) (packetsBeforePong int) { + t.Helper() + depth := s.perClientSendQueueDepth conn := &frameCountConn{} c := &sclient{ s: s, @@ -2772,66 +2802,71 @@ func TestWriterFloodDoesNotStarveControlFrames(t *testing.T) { bw: &lazyBufioWriter{w: conn}, logf: t.Logf, } - c.runWriterFunc = c.runWriter + // The test runs the writer itself, below, once the queue is full, + // so the goroutine the first sendPkt starts for it does nothing. + c.runWriterFunc = func() {} - // Flood the queue from another goroutine, faster than the writer - // drains it, so dequeue always reports more packets behind. - stop := make(chan struct{}) - var wg sync.WaitGroup + // Each packet is as big as the writer's buffer, so that writing one + // always reaches conn.Write and so calls the onWrite hook at least + // once between any two dequeues. src := key.NewNode().Public() - wg.Go(func() { - for { - select { - case <-stop: - return - default: - } - if err := c.sendPkt(c, pkt{bs: []byte("data"), src: src}); err != nil { + payload := make([]byte, bufioWriterSize) + // fill tops the send queue back up to full. Enqueueing a whole + // depth's worth does that however many packets the queue holds, + // dropping the excess at the queue's head as a real flood would. + fill := func() { + for range depth { + if err := c.sendPkt(c, pkt{bs: payload, src: src}); err != nil { t.Errorf("sendPkt: %v", err) - return } } - }) - defer func() { - close(stop) - wg.Wait() - c.stopWriter() - }() + } - waitFor := func(what string, ok func() bool) { - t.Helper() - deadline := time.Now().Add(10 * time.Second) - for !ok() { - if time.Now().After(deadline) { - t.Fatalf("timeout waiting for %s", what) + // maxSent bounds the flood so that a writer that starves the pong + // fails the test rather than hanging it. + maxSent := pongAt + 8*depth + pongsBefore := s.sentPong.Value() + pongQueued := false + conn.onWrite = func() { + sent := int(c.packetsSent.Load()) + if s.sentPong.Value() > pongsBefore || sent >= maxSent { + // Stop flooding, so the writer catches up and parks. + return + } + fill() // the queue is never empty when the writer dequeues + if !pongQueued && sent >= pongAt { + if sent != pongAt { + t.Errorf("conn.Write not called between sending %d and %d packets", pongAt, sent) } - time.Sleep(time.Millisecond) + pongQueued = true + c.queuePong([8]byte{'p', 'o', 'n', 'g'}) } } - // Let the flood get well past one queue's depth so the writer is - // surely in its drain loop. - waitFor("the flood to get going", func() bool { - packets, _, _ := conn.stats() - return packets >= 4*int(depth) - }) - c.queuePong([8]byte{'p', 'o', 'n', 'g'}) - // Count packets, not sequence numbers: the queue drops at its head - // when full, so the packets written after the pong can be far - // newer than those queued with it. This is read after queuePong so - // a preemption here can only loosen the bound. - sentAtQueue := int(c.packetsSent.Load()) - waitFor("the pong to be written", func() bool { - _, pongs, _ := conn.stats() - return pongs > 0 - }) - // The pass in progress may finish its budget of depth packets - // first, and then the pong goes out before the next pass's packets, - // so at most depth more packets precede it. - _, _, packetsAtPong := conn.stats() - if got := packetsAtPong - sentAtQueue; got > depth { - t.Errorf("pong written after %d more packets; want at most %d (the queue depth)", got, depth) + fill() + if ph := c.writerState.Load().phase(); ph != writerRunning { + t.Errorf("writer phase after filling the queue = %v; want writerRunning", ph) + return 0 } + // The first sendPkt claimed the writer for us; run it until it + // catches up and parks, which it does once the flood stops. + c.runWriter() + if ph := c.writerState.Load().phase(); ph != writerParked { + t.Errorf("writer phase after runWriter = %v; want writerParked", ph) + return 0 + } + c.stopWriter() + + if !pongQueued { + t.Errorf("pong never queued; writer parked after sending %d packets, before %d", c.packetsSent.Load(), pongAt) + } + if conn.pongs != 1 { + t.Errorf("conn saw %d pongs; want 1", conn.pongs) + } + if sent := int(c.packetsSent.Load()); conn.packets != sent { + t.Errorf("conn saw %d packets; writer sent %d", conn.packets, sent) + } + return conn.packetsAtPong - pongAt } // writerTestClient is a DERP client connected over TCP loopback to an