Explorar o código

fix(agent): reset the SSE backoff after a stream that worked (#1859) (#1860)

Nacho hai 1 mes
pai
achega
688c7ee0dc

+ 1 - 0
CHANGELOG.md

@@ -42,6 +42,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- An agent whose SSE stream is cut by a server restart reconnects in seconds instead of minutes. The reconnect delay only went back to its minimum when the stream ended cleanly, and a restart, a dropped connection or a proxy timeout all end it with a read error, so every deployment doubled the wait until it reached five minutes. During that window the server reported no agent on SSE while the agents kept pushing over plain HTTP (#1859). Agent 3.0.35.
 - The init written by the installer no longer registers a service whose binary is missing. After a sysupgrade, when the self-heal could not fetch the agent (no environment file, unreachable server, digest mismatch), the init still handed procd a path it could not execute: the service reported as started, procd retried and gave up, and the agent never ran. It now says why and leaves the service alone, so the failure shows instead of hiding behind a started unit (#1857).
 - A reinstall that cannot finish its setup now says so and still brings the agent back. After the binary was swapped the service was still stopped, and any failing step of the remaining setup (writing the environment file, installing the init script, clearing the old watchdog, enabling the service) aborted the script with `set -e`, leaving the new binary installed and nothing running. Those steps now report on stderr and carry on, the environment file and the init script are written to a temporary file and moved into place so a failure cannot truncate the one in use, and the restart is attempted even when a step fails, exiting with a distinct code if the agent does not come up (#1855).
 - A reinstall that fails no longer leaves the agent down. The installer stopped the service before it had anything to install, so a download that could not reach the server or a binary whose digest did not match exited with the previous agent already stopped and nothing to start it again. The download and the digest check now happen first, the service stops only to swap the binary, and a failed swap restarts the previous agent and says so. The three diagnostics that still went to stdout (unknown architecture, endianness, digest mismatch) now go to stderr, which is what the server reads to explain a failed reinstall (#1853).

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.34
+3.0.35

+ 16 - 7
agent/internal/sseclient/sseclient.go

@@ -58,14 +58,14 @@ func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
 func (c *Client) Run(ctx context.Context) {
 	retry := c.minRetry
 	for {
-		err := c.connect(ctx)
+		established, err := c.connect(ctx)
 		if ctx.Err() != nil {
 			return
 		}
 		if err != nil {
 			c.logf("[netpulse-agent] SSE desconectado (%v), reintentando en %s", err, retry)
 		}
-		delay, next := c.retryDelay(retry, err == nil)
+		delay, next := c.retryDelay(retry, established)
 		retry = next
 		select {
 		case <-ctx.Done():
@@ -80,6 +80,10 @@ func (c *Client) Run(ctx context.Context) {
 // reinicia el backoff (#284); solo los fallos consecutivos lo hacen crecer
 // hasta maxRetry (#1563: el `retry *= 2` anterior también corría tras una
 // conexión limpia, así que el reinicio no servía de nada).
+// #1859: "establecerse" lo decide connect(), que devuelve si el stream llegó
+// a traer datos, no si terminó sin error. Un reinicio del servidor corta la
+// lectura con EOF inesperado, y antes eso contaba como fallo: cada despliegue
+// doblaba la espera hasta los cinco minutos.
 func (c *Client) retryDelay(current time.Duration, established bool) (delay, next time.Duration) {
 	if established {
 		return c.minRetry, c.minRetry
@@ -91,10 +95,13 @@ func (c *Client) retryDelay(current time.Duration, established bool) (delay, nex
 	return current, next
 }
 
-func (c *Client) connect(ctx context.Context) error {
+// connect abre el stream y lo consume hasta que se corta. Devuelve si llegó a
+// establecerse (respuesta 200 y al menos una línea leída) junto al error de
+// lectura, que es nil cuando el corte fue limpio.
+func (c *Client) connect(ctx context.Context) (bool, error) {
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
 	if err != nil {
-		return err
+		return false, err
 	}
 	req.Header.Set("Authorization", "Bearer "+c.token)
 	req.Header.Set("Accept", "text/event-stream")
@@ -102,19 +109,21 @@ func (c *Client) connect(ctx context.Context) error {
 
 	res, err := c.hc.Do(req)
 	if err != nil {
-		return err
+		return false, err
 	}
 	defer res.Body.Close()
 
 	if res.StatusCode != http.StatusOK {
-		return &httpError{res.StatusCode}
+		return false, &httpError{res.StatusCode}
 	}
 
 	scanner := bufio.NewScanner(res.Body)
 	scanner.Buffer(nil, 64<<10)
 
 	var ev Event
+	established := false
 	for scanner.Scan() {
+		established = true
 		line := scanner.Text()
 
 		// Comentario (heartbeat) — ignorar
@@ -140,7 +149,7 @@ func (c *Client) connect(ctx context.Context) error {
 			continue
 		}
 	}
-	return scanner.Err()
+	return established, scanner.Err()
 }
 
 type httpError struct{ code int }

+ 93 - 0
agent/internal/sseclient/sseclient_test.go

@@ -1,10 +1,103 @@
 package sseclient
 
 import (
+	"context"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
 	"testing"
 	"time"
 )
 
+// #1859: un stream que llegó a traer datos reinicia el backoff aunque el corte
+// sea sucio (reinicio del servidor = EOF inesperado). Antes solo lo reiniciaba
+// un cierre limpio, así que cada despliegue doblaba la espera hasta 5 minutos.
+func TestConnectMarksEstablishedWhenTheStreamCarriesData(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "text/event-stream")
+		w.WriteHeader(http.StatusOK)
+		fmt.Fprint(w, "event: connected\ndata: {}\n\n")
+		w.(http.Flusher).Flush()
+		panic(http.ErrAbortHandler) // corta la conexión como un reinicio
+	}))
+	defer srv.Close()
+
+	c := &Client{
+		url:      srv.URL + "/api/agents/rt1/stream",
+		token:    "t",
+		hc:       srv.Client(),
+		onEvent:  func(Event) {},
+		minRetry: 5 * time.Second,
+		maxRetry: 5 * time.Minute,
+		logf:     func(string, ...any) {},
+	}
+
+	established, err := c.connect(context.Background())
+	if !established {
+		t.Fatal("un stream que trajo datos debe contar como establecido")
+	}
+	if err == nil {
+		t.Fatal("un corte sucio debe devolver error de lectura")
+	}
+	if delay, next := c.retryDelay(5*time.Minute, established); delay != c.minRetry || next != c.minRetry {
+		t.Fatalf("tras un stream establecido el backoff debe volver a %s, salió delay=%s next=%s",
+			c.minRetry, delay, next)
+	}
+}
+
+// Un cierre limpio también cuenta como establecido, y no hay error.
+func TestConnectMarksEstablishedOnCleanClose(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "text/event-stream")
+		w.WriteHeader(http.StatusOK)
+		fmt.Fprint(w, "event: connected\ndata: {}\n\n")
+	}))
+	defer srv.Close()
+
+	c := &Client{
+		url:      srv.URL + "/api/agents/rt1/stream",
+		token:    "t",
+		hc:       srv.Client(),
+		onEvent:  func(Event) {},
+		minRetry: 5 * time.Second,
+		maxRetry: 5 * time.Minute,
+		logf:     func(string, ...any) {},
+	}
+
+	established, err := c.connect(context.Background())
+	if !established || err != nil {
+		t.Fatalf("cierre limpio: established=%v err=%v, quería true/nil", established, err)
+	}
+}
+
+// Si el servidor no responde no hubo stream: el backoff debe seguir creciendo.
+func TestConnectNotEstablishedWhenTheServerIsDown(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
+	url := srv.URL
+	srv.Close()
+
+	c := &Client{
+		url:      url + "/api/agents/rt1/stream",
+		token:    "t",
+		hc:       &http.Client{Timeout: time.Second},
+		onEvent:  func(Event) {},
+		minRetry: 5 * time.Second,
+		maxRetry: 5 * time.Minute,
+		logf:     func(string, ...any) {},
+	}
+
+	established, err := c.connect(context.Background())
+	if established {
+		t.Fatal("sin servidor no hay stream establecido")
+	}
+	if err == nil {
+		t.Fatal("sin servidor debe devolver error")
+	}
+	if delay, _ := c.retryDelay(10*time.Second, established); delay != 10*time.Second {
+		t.Fatalf("un fallo debe mantener la espera actual, salió %s", delay)
+	}
+}
+
 // #1563: una conexión que llegó a establecerse reinicia el backoff, sin
 // importar cuántos cortes limpios hubiera antes.
 func TestRetryDelayResetsAfterCleanDisconnect(t *testing.T) {