lima icon indicating copy to clipboard operation
lima copied to clipboard

gRPC port forwarder wedges half-open: guest agent's gRPC writer exits, requests still reach the guest but no response ever returns

Open aiagelab1 opened this issue 2 months ago • 2 comments

Description

Lima 2.0.3 (Homebrew) on macOS 15.4.1, Apple silicon (M4 Pro), vmType: vz, default gRPC port forwarder (LIMA_SSH_PORT_FORWARDER unset). Guest: Ubuntu 24.04 running Docker (~35 containers, ~20 forwarded TCP ports, plus frequent short-lived UDP forwards from the guest's DNS forwarder). The instance was created by colima 0.10.1 and is started with limactl start.

Twice in three days, a long-running instance (after ~7 days and ~2.75 days of uptime) got into a state where every forwarded port broke at once and stayed broken until manual intervention (44 and 13 minutes):

  • A host-side client connects to 127.0.0.1:<port> instantly, and its request reaches the guest service (the guest-side access logs show every request, answered in milliseconds), but no response byte ever comes back to the host (curl waited 150 s).
  • The same request made inside the guest answers in a few ms.
  • Guest-agent port events stop at the same moment: in ha.stderr.log the guest agent event: … lines (normally several per minute here because of the UDP churn) stop completely. The only lines that continue are tcp proxy for guestAddr: … closed / closing GrpcClientRW … as host clients give up.
  • limactl hostagent is idle (~0.2% CPU, ~80 fds), with no warnings or errors in ha.stderr.log. The guest agent is idle too, and its journal is empty.
  • The guest agent's vsock connection has nothing queued in either direction:
    $ sudo ss -A vsock -anp
    Netid State  Recv-Q Send-Q Local Address:Port Peer Address:Port Process
    v_str LISTEN 0      0                  3:2222            *:*    users:(("lima-guestagent",...))
    v_str ESTAB  0      0                  3:2222            2:...  users:(("lima-guestagent",...))
    

Restarting only the guest agent inside the VM (sudo kill -QUIT $(pidof lima-guestagent); systemd restarts it) restored every forward within ~4 s. The hostagent logged guest agent events closed unexpectedly … EOF, then Guest agent is running ~10 s later. No VM restart was needed.

Goroutine dump of the wedged lima-guestagent (second occurrence)

The SIGQUIT dump (712 goroutines) shows that the gRPC server transport has lost its writer while its reader is still alive:

  1. There is no transport.(*loopyWriter).run goroutine at all, but the transport's reader is still running, blocked reading the vsock:
    goroutine 38 [IO wait, 2 minutes]:
    github.com/mdlayher/vsock.(*Conn).Read(...)                 mdlayher/[email protected]/vsock.go:230
    golang.org/x/net/http2.(*Framer).ReadFrameHeader(...)       golang.org/x/[email protected]/http2/frame.go:505
    google.golang.org/grpc/internal/transport.(*http2Server).HandleStreams(...)
                                                                [email protected]/internal/transport/http2_server.go:673
    google.golang.org/grpc.(*Server).serveStreams(...)          [email protected]/server.go:1057
    created by google.golang.org/grpc.(*Server).handleRawConn   [email protected]/server.go:990
    
  2. The GetEvents handler goroutine is gone, and the event producer is blocked forever on the unbuffered channel that handler used to drain (the ticker goroutines are stuck behind it):
    goroutine 13 [chan send, 10 minutes]:
    github.com/lima-vm/lima/v2/pkg/guestagent.(*agent).Events(...)
        pkg/guestagent/guestagent_linux.go:134
    created by github.com/lima-vm/lima/v2/pkg/guestagent/api/server.(*GuestServer).GetEvents in goroutine 12
        pkg/guestagent/api/server/server.go:58
    
  3. There is one leaked goroutine per tunnel opened after the onset (641 after ~13 minutes), each waiting for a stream context that is never cancelled:
    goroutine … [chan receive, 6 minutes]:
    github.com/lima-vm/lima/v2/pkg/portfwdserver.(*TunnelServer).Start.func1()
        pkg/portfwdserver/server.go:44
    
  4. 39 tunnel copy goroutines (created by tcpproxy.(*DialProxy).HandleConn) are parked in transport.(*recvBufferReader).readMessageHeader, so host→guest reads keep working.

Analysis

This matches what grpc-go does when the server's loopy writer exits with an I/O error. From NewServerTransport in grpc v1.78.0:

err := t.loopy.run()
close(t.loopyWriterDone)
if !isIOError(err) {
    // Close the connection if a non-I/O error occurs (for I/O errors
    // the reader will also encounter the error and close). ...
    t.conn.Close()
}

loopyWriter.run also finishes the control buffer on exit (l.cbuf.finish()), so every later write fails with ErrConnClosing. On this vsock connection the write side failed but the read side kept working, so the reader never saw an error and the transport stayed half-open indefinitely:

  • host→guest frames are still read, so new tunnel streams are accepted and requests are delivered to guest services;
  • every guest→host write (tunnel data, status/trailers, GetEvents) fails internally, so nothing is ever sent back;
  • the server-side stream contexts are never cancelled, so TunnelServer.Start.func1 goroutines leak;
  • the hostagent sees a healthy but silent connection and never re-dials.

We don't know what the underlying write error was. The guest agent runs without gRPC logging, and loopyWriter exiting with error: … is only logged at verbosity 2.

Suggested fixes

  • Hostagent: enable client keepalive on the guest-agent gRPC client (pkg/guestagent/api/client/client.go), e.g. grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 10 * time.Second, Timeout: 5 * time.Second, PermitWithoutStream: true}), together with a matching grpc.KeepaliveEnforcementPolicy on the guest-agent server so the pings aren't rejected. The client only pings after Time passes without reading anything, so a dead return path would be detected and the connection closed and re-dialed within seconds. As far as I can see, current master still sets no client keepalive and the server uses the default keepalive parameters, so nothing detects a connection that is dead in one direction only.
  • Guest agent: make a write failure tear down the whole connection, e.g. wrap the accepted vsock net.Conn so that the first failed Write closes it. The reader then fails too, and the hostagent reconnects.

Notes

  • This is on 2.0.3, which predates #5043 and the half-close fixes (#5329 / #5401). Those address different symptoms: #5042 exhausts MaxConcurrentStreams so new tunnels can't open, whereas here new tunnels kept opening and requests kept reaching the guest, with far fewer than 2048 streams open. The missing keepalive looks the same on master.
  • Workaround: when host-side requests to forwarded ports hang while the same request inside the guest succeeds, restart lima-guestagent inside the guest.
  • I can share the full goroutine dump if that helps.

aiagelab1 avatar Sep 26 '26 14:09 aiagelab1

Update: the underlying write error is ENOMEM from the guest kernel's vsock transmit path.

I enabled gRPC logging for the guest agent (GRPC_GO_LOG_SEVERITY_LEVEL=info, GRPC_GO_LOG_VERBOSITY_LEVEL=2, via a systemd drop-in). The next occurrence logged:

INFO: [transport] [server-transport 0x…] loopyWriter exiting with error: write vsock vm(3):2222->host(2):…: cannot allocate memory

The guest kernel is Ubuntu 24.04 6.8.0-100-generic (arm64, 4 KiB pages). As far as I can tell, before Linux 6.17 the virtio-vsock transmit path allocates each packet (up to 64 KiB of payload) as a linear skb. That is a physically contiguous buffer of just over 64 KiB, which is an order-5 allocation with 4 KiB pages, and the allocation fails silently (nothing like "page allocation failure" appears in dmesg). So sendmsg() returns ENOMEM whenever memory is fragmented, even with gigabytes free. Linux 6.17 changed this in 6693731487a8 ("vsock/virtio: Allocate nonlinear SKBs for handling large transmit buffers").

Evidence at the time of the failure (the guest had ~6.5 GiB available):

  • /proc/buddyinfo, Normal zone, free blocks at order 4 / 5 / 6 / ≥7: 133 / 24 / 1 / 0
  • /proc/vmstat since boot (~3.7 days): compact_stall 33992, compact_fail 33155, compact_success 837
  • after sysctl vm.drop_caches=3 and sysctl vm.compact_memory=1, orders 4–10 went to 13008 7025 3211 1269 444 107 12. About 40 minutes later, order 5 was back in single digits under our workload.

This also explains why the intervals between occurrences shrank from days to minutes: restarting lima-guestagent doesn't reset fragmentation, only a VM restart does.

So the trigger is a transient ENOMEM on a single vsock write, and the half-open transport described above turns it into a permanent outage. On top of the keepalive and close-on-write-error ideas, the guest agent could treat ENOMEM (and probably ENOBUFS) from a vsock write as retryable, e.g. with a net.Conn wrapper that retries the write after a short backoff instead of surfacing the error to grpc-go.

Meanwhile we're mitigating by raising vm.min_free_kbytes in the guest (44 MiB → 256 MiB), running a one-off compaction when it happens, and restarting lima-guestagent. Longer term we plan to move the guest to a kernel ≥ 6.17 (e.g. the Ubuntu 24.04 HWE kernel).

aiagelab1 avatar Sep 27 '26 13:09 aiagelab1

I wrap the guest agent's accepted connections so that the first failed write closes the whole connection. The read side then fails too, and the host agent reconnects instead of staying half-open. (PR: #5546)

Sarthak-Shreshtha01 avatar Sep 29 '26 17:09 Sarthak-Shreshtha01