Lightweight server monitoring with historical data, docker stats, and alerts.
fix(hub): ping a slow agent so its connection survives between polls (#2435)
Mario Mohar7305eda972cb
diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.goindex 0a292668d..57d0f1995 100644--- a/internal/hub/systems/system.go+++ b/internal/hub/systems/system.go@@ -174,6 +174,26 @@ func (sys *System) update() error {data, err := sys.fetchDataFromAgent(options)if err != nil {+ // Keep the WebSocket alive even though this fetch failed.+ //+ // Only a message from the agent resets the read deadline, and an agent+ // still collecting sends nothing. Without this ping the deadline expires+ // between polls, the hub closes the connection, the agent reconnects,+ // collects slowly again, and the cycle repeats. Pinging here is the same+ // move handlePaused already makes for a paused system, and Ping() pushes+ // the deadline out as it sends, so it works without an answer, which+ // matters because a collecting agent cannot answer.+ //+ // This is why the deadline has to exceed interval + wsDataRequestTimeout:+ // the ping only happens once the fetch gives up. See ws.deadline.+ //+ // The system is still reported down: that comes from the error we+ // return. Only the connection survives, so recovery costs no reconnect.+ // A failed ping needs no handling either, since a connection that+ // cannot be pinged runs into its deadline anyway.+ if sys.WsConn != nil && sys.WsConn.IsConnected() {+ _ = sys.WsConn.Ping()+ }return err}diff --git a/internal/hub/systems/ws_data_timeout_test.go b/internal/hub/systems/ws_data_timeout_test.goindex ae6720fd2..a8a019c47 100644--- a/internal/hub/systems/ws_data_timeout_test.go+++ b/internal/hub/systems/ws_data_timeout_test.go@@ -7,6 +7,7 @@ import ("net/http""net/http/httptest""strings"+ "sync/atomic""testing""time"@@ -80,3 +81,180 @@ func TestFetchDataTimeoutKeepsWebSocketOpen(t *testing.T) {_, err = sys.fetchDataFromAgent(common.DataRequestOptions{})require.NoError(t, err)}++// pingCountingClient never answers GetData and records the pings it receives,+// standing in for an agent whose collection outlasts the request timeout.+type pingCountingClient struct {+ gws.BuiltinEventHandler+ pings chan struct{}+}++func (c *pingCountingClient) OnPing(conn *gws.Conn, payload []byte) {+ _ = conn.WritePong(payload)+ select {+ case c.pings <- struct{}{}:+ default:+ }+}++func (c *pingCountingClient) OnMessage(conn *gws.Conn, message *gws.Message) {+ // Swallow the request: this agent is still collecting.+ message.Close()+}++// A slow agent used to be disconnected between polls. The fetch gives up after+// wsDataRequestTimeout, but the hub's read deadline is longer and only traffic+// from the agent resets it, so nothing kept the connection alive in between.+// update() now pings on a failed fetch, which is what breaks the reconnect+// loop reported in #2294.+func TestUpdatePingsAgentAfterFailedFetch(t *testing.T) {+ originalTimeout := wsDataRequestTimeout+ wsDataRequestTimeout = 50 * time.Millisecond+ t.Cleanup(func() { wsDataRequestTimeout = originalTimeout })++ connections := make(chan *ws.WsConn, 1)+ upgrader := gws.NewUpgrader(&monitorSyncServer{}, nil)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := upgrader.Upgrade(w, r)+ if err != nil {+ t.Error(err)+ return+ }+ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0"))+ conn.Session().Store("wsConn", wsConn)+ connections <- wsConn+ conn.ReadLoop()+ }))+ t.Cleanup(server.Close)++ client := &pingCountingClient{pings: make(chan struct{}, 4)}+ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")})+ require.NoError(t, err)+ t.Cleanup(func() { _ = conn.NetConn().Close() })+ go conn.ReadLoop()++ var sys *System+ select {+ case wsConn := <-connections:+ sys = &System{WsConn: wsConn}+ case <-time.After(3 * time.Second):+ t.Fatal("websocket connection was not established")+ }++ err = sys.update()+ require.ErrorIs(t, err, context.DeadlineExceeded, "the fetch is expected to time out")++ select {+ case <-client.pings:+ case <-time.After(3 * time.Second):+ t.Fatal("a failed fetch must ping the agent to keep the connection alive")+ }++ require.True(t, sys.WsConn.IsConnected(), "the connection must survive a failed fetch")+}++// silentAfterFirstPollAgent answers the first GetData and then goes quiet,+// modelling an agent whose collection outlasts the request timeout. It never+// answers a ping, because a real agent serves hub requests on its read loop and+// cannot reply while it is collecting. The fix therefore has to work without an+// answer, which it does: Ping() pushes the deadline out as it sends.+type silentAfterFirstPollAgent struct {+ gws.BuiltinEventHandler+ answered atomic.Bool+}++func (c *silentAfterFirstPollAgent) OnPing(*gws.Conn, []byte) {}++func (c *silentAfterFirstPollAgent) OnMessage(conn *gws.Conn, message *gws.Message) {+ defer message.Close()+ var req common.HubRequest[cbor.RawMessage]+ if err := cbor.Unmarshal(message.Bytes(), &req); err != nil || req.Action != common.GetData {+ return+ }+ if c.answered.CompareAndSwap(false, true) {+ response, _ := cbor.Marshal(common.AgentResponse{Id: req.Id, SystemData: &esystem.CombinedData{}})+ _ = conn.WriteMessage(gws.OpcodeBinary, response)+ }+}++// timelineScale shrinks the poll schedule so the test stays fast while keeping+// the production ratio between poll interval, request timeout and read deadline.+const timelineScale = 100++// A slow agent must survive repeated failed polls. The ping in update() only+// happens once the fetch gives up, which is interval + wsDataRequestTimeout into+// the cycle, so the read deadline has to outlast that. With a deadline below+// that sum the connection is already closed when the ping would go out, which is+// the reconnect loop from #2294.+func TestSlowAgentKeepsConnectionAcrossPolls(t *testing.T) {+ tick := time.Duration(interval) * time.Millisecond / timelineScale++ tests := []struct {+ name string+ deadline time.Duration+ wantConnected bool+ }{+ {"production deadline outlasts a failed poll", ws.Deadline() / timelineScale, true},+ // 70s was the old value and sits below the 90s a failed poll needs.+ {"deadline below interval plus request timeout", 70 * time.Second / timelineScale, false},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ previousDeadline := ws.SetDeadline(tc.deadline)+ t.Cleanup(func() { ws.SetDeadline(previousDeadline) })+ previousTimeout := wsDataRequestTimeout+ wsDataRequestTimeout = 30 * time.Second / timelineScale+ t.Cleanup(func() { wsDataRequestTimeout = previousTimeout })++ connections := make(chan *ws.WsConn, 1)+ // The real handler: OnClose has to run, or a dropped connection+ // would still look connected.+ upgrader := gws.NewUpgrader(&ws.Handler{}, &gws.ServerOption{})+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := upgrader.Upgrade(w, r)+ if err != nil {+ t.Error(err)+ return+ }+ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0"))+ conn.Session().Store("wsConn", wsConn)+ connections <- wsConn+ conn.ReadLoop()+ }))+ t.Cleanup(server.Close)++ client := &silentAfterFirstPollAgent{}+ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")})+ require.NoError(t, err)+ t.Cleanup(func() { _ = conn.NetConn().Close() })+ go conn.ReadLoop()++ var sys *System+ select {+ case wsConn := <-connections:+ sys = &System{WsConn: wsConn}+ case <-time.After(3 * time.Second):+ t.Fatal("websocket connection was not established")+ }++ // A healthy poll. Its response is what last resets the deadline, so+ // it is the point the schedule below is measured from.+ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{})+ require.NoError(t, err, "the first poll must succeed")+ pollZero := time.Now()++ // Two failed polls: the first shows the ping lands, the second shows+ // the ping keeps re-arming the deadline.+ for poll := 1; poll <= 2; poll++ {+ time.Sleep(time.Until(pollZero.Add(time.Duration(poll) * tick)))+ if !sys.WsConn.IsConnected() {+ break+ }+ require.Error(t, sys.update(), "a silent agent must fail the poll")+ }++ require.Equal(t, tc.wantConnected, sys.WsConn.IsConnected())+ })+ }+}diff --git a/internal/hub/ws/ws.go b/internal/hub/ws/ws.goindex 7d61e596c..6b268a3ba 100644--- a/internal/hub/ws/ws.go+++ b/internal/hub/ws/ws.go@@ -16,9 +16,14 @@ import ("github.com/lxzan/gws")-const (- deadline = 70 * time.Second-)+// deadline bounds how long a connection may go without traffic from the agent.+//+// It has to outlast a whole failed poll: the updater polls every interval (60s)+// and a fetch gives up after wsDataRequestTimeout (30s), so nothing can reset+// the deadline before 90s into a stalled cycle. A shorter deadline expires+// mid-collection, and by the time the failed fetch pings, the connection is+// already closed. 100s keeps the same 10s margin the poll interval used to have.+var deadline = 100 * time.Second// Handler implements the WebSocket event handler for agent connections.type Handler struct {diff --git a/internal/hub/ws/ws_test.go b/internal/hub/ws/ws_test.goindex 9970cf47b..caa53b342 100644--- a/internal/hub/ws/ws_test.go+++ b/internal/hub/ws/ws_test.go@@ -170,9 +170,15 @@ func TestFingerprintRecord(t *testing.T) {assert.Equal(t, "test-token", record.Token)}-// TestDeadlineConstant tests that the deadline constant is reasonable+// TestDeadlineConstant tests that the deadline is reasonable.+//+// It has to stay above the 90s a failed poll takes in the systems package (a+// 60s poll interval plus a 30s request timeout), because the keepalive ping+// only goes out once that fetch gives up. Lowering this reopens the reconnect+// loop from #2294; TestSlowAgentKeepsConnectionAcrossPolls covers the effect.func TestDeadlineConstant(t *testing.T) {- assert.Equal(t, 70*time.Second, deadline, "Deadline should be 70 seconds")+ assert.Equal(t, 100*time.Second, deadline, "Deadline should be 100 seconds")+ assert.Greater(t, deadline, 90*time.Second, "Deadline must outlast a failed poll")}// TestCommonActions tests that the common actions are properly defineddiff --git a/internal/hub/ws/ws_test_helpers.go b/internal/hub/ws/ws_test_helpers.goindex ac52c779d..aaf49dc96 100644--- a/internal/hub/ws/ws_test_helpers.go+++ b/internal/hub/ws/ws_test_helpers.go@@ -2,9 +2,22 @@package ws+import "time"+// GetPendingCount returns the number of pending requests (for monitoring)func (rm *RequestManager) GetPendingCount() int {rm.RLock()defer rm.RUnlock()return len(rm.pendingReqs)}++// TESTING ONLY: Deadline reports the connection read deadline.+func Deadline() time.Duration { return deadline }++// TESTING ONLY: SetDeadline overrides the connection read deadline so tests can+// drive the poll schedule at a reduced scale. It returns the previous value.+func SetDeadline(d time.Duration) time.Duration {+ previous := deadline+ deadline = d+ return previous+}