Răsfoiți Sursa

fix(agents): let upgrade-all count a live agent stream as eligible (#1883)

upgrade-all asked the router row whether the unit could upgrade, and that
row says external for anything that is not OpenWrt or GL.iNet. A unit with
a native agent that was migrated to external in 2.49.x therefore got
not_openwrt and had to be upgraded by hand.

The registry cannot answer this: pushers POST to the same endpoint, so
Info() is also true for a scraper. What the command actually needs is an
SSE stream, which is what the hub holds. A stream now counts as eligible
and the type stays as the fallback for units without an agent.

rotateTokenHot keeps using routerUpgradeable, since that one really is
about reaching the router over SSH.
Nacho 4 săptămâni în urmă
părinte
comite
55825c5d82

+ 17 - 3
server-go/internal/httpapi/upgrade.go

@@ -253,6 +253,18 @@ func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "status": status})
 }
 
+// upgradeAllEligible decide si upgrade-all puede mandar el comando a la
+// unidad. El tipo de la fila routers basta para descartar un scraper sin
+// agente, pero no para descartar una unidad con agente nativo: desde la
+// migración a external (2.49.x) esas filas conservan su agente y el hub
+// sabe quién tiene el stream abierto (#1872).
+func (s *server) upgradeAllEligible(slug string) bool {
+	if s.routerUpgradeable(slug) {
+		return true
+	}
+	return s.agentHub != nil && s.agentHub.Connected(slug)
+}
+
 // sendOrQueueUpgrade envía el comando upgrade por SSE; si el agente no está
 // conectado, lo encola para el flush on-connect del hub. Devuelve el estado.
 // Registra la versión objetivo del upgrade para cerrar el ciclo en cuanto el
@@ -450,9 +462,11 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 					} else {
 						item.Status = "up_to_date"
 					}
-				// Solo agentes nativos OpenWrt: los de type managed-switch/
-				// external son scrapers que no entienden el comando "upgrade".
-				case !s.routerUpgradeable(slug):
+				// El comando "upgrade" solo lo entiende un agente nativo. El tipo
+				// de la fila decide para un scraper, pero una unidad con agente
+				// nativo y fila external (migración 2.49.x) sí puede actualizarse:
+				// ahí manda el stream SSE abierto (#1872).
+				case !s.upgradeAllEligible(slug):
 					item.Status = "not_openwrt"
 				// #447: solo hay novedad si el agente es MÁS VIEJO que el
 				// binario embebido (build incluido); un agente más nuevo no

+ 90 - 0
server-go/internal/httpapi/upgrade_all_1872_test.go

@@ -0,0 +1,90 @@
+package httpapi_test
+
+import (
+	"testing"
+	"time"
+)
+
+// TestAgentsUpgradeAllExternalWithLiveAgent — #1872: el gate de upgrade-all
+// miraba routers.type y devolvía not_openwrt a una unidad con agente nativo y
+// fila external. Con el stream SSE abierto el comando sí puede salir; sin
+// stream, un scraper sigue dando not_openwrt.
+func TestAgentsUpgradeAllExternalWithLiveAgent(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+
+	// Tres filas external: una con agente conectado, otra sin conectar y una
+	// tercera con tipo openwrt sin conectar (control: sigue encolando).
+	for _, slug := range []string{"asus-live", "asus-dark", "owrt-dark"} {
+		typ := "external"
+		if slug == "owrt-dark" {
+			typ = "openwrt"
+		}
+		if _, err := ts.db.Exec(
+			`INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?,?,?,?,?,?)`,
+			slug, slug, "10.0.0.9", typ, 0, time.Now().UnixMilli(),
+		); err != nil {
+			t.Fatalf("insert %s: %v", slug, err)
+		}
+	}
+
+	// asus-live: agente nativo desactualizado, conectado por SSE → sent.
+	st, tok := createUpgradeToken(t, ts, "asus-live")
+	if st != 201 {
+		t.Fatalf("create asus-live: %d", st)
+	}
+	upgradeIngest(t, ts, tok, upgradePayloadFor("asus-live", "0.0.9"))
+	cancel, done := openStream(t, ts, "asus-live", tok)
+	defer func() { cancel(); <-done }()
+
+	// asus-dark: el mismo tipo external pero sin stream → not_openwrt.
+	if st, tokD := createUpgradeToken(t, ts, "asus-dark"); st != 201 {
+		t.Fatalf("create asus-dark: %d", st)
+	} else {
+		upgradeIngest(t, ts, tokD, upgradePayloadFor("asus-dark", "0.0.9"))
+	}
+
+	// owrt-dark: tipo aceptado sin conexión → queued (sin regresión).
+	if st, tokO := createUpgradeToken(t, ts, "owrt-dark"); st != 201 {
+		t.Fatalf("create owrt-dark: %d", st)
+	} else {
+		upgradeIngest(t, ts, tokO, upgradePayloadFor("owrt-dark", "0.0.9"))
+	}
+
+	res := doReq(t, "POST", ts.URL+"/api/agents/upgrade-all", ts.cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("upgrade-all: got %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	bySlug := map[string]string{}
+	for _, a := range body["agents"].([]any) {
+		m := a.(map[string]any)
+		bySlug[m["slug"].(string)] = m["status"].(string)
+	}
+	if bySlug["asus-live"] != "sent" {
+		t.Fatalf("external con agente conectado debería ser sent: %v", bySlug)
+	}
+	if bySlug["asus-dark"] != "not_openwrt" {
+		t.Fatalf("external sin agente debería seguir en not_openwrt: %v", bySlug)
+	}
+	if bySlug["owrt-dark"] != "queued" {
+		t.Fatalf("openwrt sin agente debería seguir en queued: %v", bySlug)
+	}
+}
+
+// TestAgentHubConnected — el helper del hub que sostiene el gate de #1872.
+func TestAgentHubConnected(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "hub-check")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	if ts.hub.Connected("hub-check") {
+		t.Fatal("sin stream no debería estar conectado")
+	}
+	cancel, done := openStream(t, ts, "hub-check", tok)
+	if !ts.hub.Connected("hub-check") {
+		t.Fatal("con stream debería estar conectado")
+	}
+	cancel()
+	<-done
+}

+ 8 - 0
server-go/internal/sse/agenthub.go

@@ -80,6 +80,14 @@ func (h *AgentHub) fireOnConnect(slug string) {
 	}
 }
 
+// Connected indica si el slug tiene un agente con el stream SSE abierto.
+func (h *AgentHub) Connected(slug string) bool {
+	h.mu.Lock()
+	defer h.mu.Unlock()
+	_, ok := h.conns[slug]
+	return ok
+}
+
 // ConnectedSlugs devuelve los slugs con agente conectado vía SSE.
 func (h *AgentHub) ConnectedSlugs() []string {
 	h.mu.Lock()