Просмотр исходного кода

fix(agents): keep the agent-router association on wireless-only pushes (#1875)

Nacho 4 недель назад
Родитель
Сommit
de6df7faad

+ 15 - 0
server-go/internal/adapters/agent.go

@@ -122,6 +122,21 @@ func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version, kind str
 	return st.LastSeen, st.Version, st.Kind, st.Interval, true
 }
 
+// Identity devuelve la identidad retenida del agente: hostname del board y
+// MAC del bridge, aunque el último push sea event-driven y no traiga sección
+// system (#852 los conserva en AgentState). La usa GET /api/agents para
+// asociar el agente con su router cuando el payload actual no lleva identidad
+// (#1874).
+func (r *AgentRegistry) Identity(slug string) (host, bridgeMAC string, ok bool) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, found := r.states[slug]
+	if !found {
+		return "", "", false
+	}
+	return st.Host, st.BridgeMAC, true
+}
+
 // SelfExpose informa de si el router se expone él mismo a Home Assistant por
 // MQTT (#832), leyéndolo de la última muestra del agente. ok=false = el
 // agente no lo informa (standalone o embedder que no lo reporta).

+ 45 - 17
server-go/internal/httpapi/agent.go

@@ -867,10 +867,27 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				if payload != nil {
 					item.PanelPort = payload.PanelPort
 				}
-				item.RouterID = resolveAgentRouter(slug, payload, routerByID)
-				if payload != nil && payload.Data.System != nil && payload.Data.System.Board != nil {
-					item.Hostname = strings.ToLower(strings.TrimSpace(payload.Data.System.Board.Hostname))
+				// #1874: un push event-driven (wireless-only) no trae sección
+				// system, y resolver la asociación con el payload actual dejaba
+				// el router sin id: la UI pintaba "agente no instalado" con el
+				// agente vivo. La identidad retenida por el registry (#852) es
+				// la que sobrevive a esos pushes.
+				host, bridgeMAC := "", ""
+				if s.agents != nil {
+					host, bridgeMAC, _ = s.agents.Identity(slug)
+				}
+				if payload != nil && payload.Data.System != nil {
+					if b := payload.Data.System.Board; b != nil {
+						if h := strings.TrimSpace(b.Hostname); h != "" {
+							host = h
+						}
+					}
+					if bridgeMAC == "" {
+						bridgeMAC = payload.Data.System.BridgeMAC
+					}
 				}
+				item.RouterID = resolveAgentRouterIdentity(slug, host, bridgeMAC, routerByID)
+				item.Hostname = strings.ToLower(strings.TrimSpace(host))
 				// Fase 6.3 (issue #243): upgrade disponible si el agente
 				// reporta una versión distinta del binario embebido y el router
 				// asociado es actualizable (nativo OpenWrt/GL.iNet).
@@ -919,32 +936,43 @@ type routerIdentity struct {
 	Mac  string
 }
 
-// resolveAgentRouter devuelve el id del router asociado a un agente. Primero
-// intenta slug == router.id; si no, empareja por bridge MAC persistida y solo
-// usa un hostname de board cuando es único (#1334): el hostname suele estar
-// duplicado en APs puente idénticos y un match ambiguo no debe inventar una
-// asociación. La MAC es la identidad física autoritativa.
+// resolveAgentRouter devuelve el id del router asociado a un agente a partir
+// de un payload suelto (sin acceso al registry). Es la variante que usan los
+// llamadores que no tienen la identidad retenida; handleAgentsList y el plan
+// de canales usan resolveAgentRouterIdentity con la identidad del registry.
 func resolveAgentRouter(slug string, payload *probe.Payload, routers map[string]routerIdentity) string {
+	host, bridgeMAC := "", ""
+	if payload != nil && payload.Data.System != nil {
+		bridgeMAC = payload.Data.System.BridgeMAC
+		if payload.Data.System.Board != nil {
+			host = payload.Data.System.Board.Hostname
+		}
+	}
+	return resolveAgentRouterIdentity(slug, host, bridgeMAC, routers)
+}
+
+// resolveAgentRouterIdentity devuelve el id del router asociado a un agente.
+// Primero intenta slug == router.id; si no, empareja por bridge MAC y solo usa
+// un hostname de board cuando es único (#1334): el hostname suele estar
+// duplicado en APs puente idénticos y un match ambiguo no debe inventar una
+// asociación. La MAC es la identidad física autoritativa. Recibe host y MAC
+// por separado porque el último push puede ser event-driven y no traerlos
+// (#1874): ahí se pasan los retenidos por el registry (#852).
+func resolveAgentRouterIdentity(slug, host, bridgeMAC string, routers map[string]routerIdentity) string {
 	if slug != "" {
 		if _, ok := routers[slug]; ok {
 			return slug
 		}
 	}
-	if payload == nil || payload.Data.System == nil {
-		return ""
-	}
-	if payload.Data.System.BridgeMAC != "" {
+	if bridgeMAC != "" {
 		for _, r := range routers {
-			if r.Mac != "" && strings.EqualFold(payload.Data.System.BridgeMAC, r.Mac) {
+			if r.Mac != "" && strings.EqualFold(bridgeMAC, r.Mac) {
 				return r.ID
 			}
 		}
 	}
-	if payload.Data.System.Board == nil {
-		return ""
-	}
 	norm := func(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
-	hostname := norm(payload.Data.System.Board.Hostname)
+	hostname := norm(host)
 	if hostname == "" {
 		return ""
 	}

+ 104 - 0
server-go/internal/httpapi/agent_association_test.go

@@ -0,0 +1,104 @@
+// agent_association_test.go — #1874: un push event-driven (wireless-only, sin
+// sección system) no debe perder la asociación agente↔router. El registry
+// retiene la identidad (#852) y GET /api/agents tiene que usarla; sin eso el
+// router se quedaba sin routerId y la UI pintaba "agente no instalado" con el
+// agente vivo.
+package httpapi_test
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"testing"
+	"time"
+)
+
+type agentListEntry struct {
+	Slug     string `json:"slug"`
+	RouterID string `json:"routerId"`
+	Hostname string `json:"hostname"`
+	Fresh    bool   `json:"fresh"`
+}
+
+func getAgents(t *testing.T, ts *agentTestServer) []agentListEntry {
+	t.Helper()
+	req, _ := http.NewRequest("GET", ts.URL+"/api/agents", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET /api/agents: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET /api/agents: %d", res.StatusCode)
+	}
+	var body struct {
+		Agents []agentListEntry `json:"agents"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("decode /api/agents: %v", err)
+	}
+	return body.Agents
+}
+
+func findAgentEntry(list []agentListEntry, slug string) *agentListEntry {
+	for i := range list {
+		if list[i].Slug == slug {
+			return &list[i]
+		}
+	}
+	return nil
+}
+
+func TestAgentAssociationSurvivesWirelessOnlyPush(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	now := time.Now().Unix()
+	// Router cuyo id NO coincide con el slug del agente, como en la flota
+	// real (id gl-inet-gl-mt6000, agente flint2): la asociación solo puede
+	// salir de la MAC del bridge o del hostname del board.
+	if _, err := ts.db.Exec(
+		`INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?,?,?,?,?,?)`,
+		"gl-inet-gl-mt6000", "GL.iNet GL-MT6000", "192.168.10.1", "glinet", 1, now*1000,
+	); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+	if _, err := ts.db.Exec(
+		`UPDATE routers SET agent_only = 1, mac = ? WHERE id = ?`,
+		"94:83:C4:A4:FB:71", "gl-inet-gl-mt6000",
+	); err != nil {
+		t.Fatalf("update router: %v", err)
+	}
+	_, token, _ := createAgentToken(t, ts, "flint2")
+
+	full := fmt.Sprintf(`{"router":"flint2","ts":%d,"version":"0.1.0","data":{"system":{"bridgeMac":"94:83:C4:A4:FB:71","board":{"hostname":"Flint2","model":"GL.iNet GL-MT6000"},"cpu":7},"wireless":{"clients":{}}}}`, now)
+	res := ingest(t, ts, token, "10.0.9.1", full)
+	res.Body.Close()
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest full: %d", res.StatusCode)
+	}
+	entry := findAgentEntry(getAgents(t, ts), "flint2")
+	if entry == nil || entry.RouterID != "gl-inet-gl-mt6000" || entry.Hostname != "flint2" {
+		t.Fatalf("asociación tras push completo: %+v", entry)
+	}
+
+	// Push de evento nl80211: mismo contrato que en producción, sin system.
+	wireless := fmt.Sprintf(`{"router":"flint2","ts":%d,"version":"0.1.0","data":{"arp":{},"dhcp":{"leases":[]},"wireless":{"clients":{}}}}`, now+1)
+	res = ingest(t, ts, token, "10.0.9.1", wireless)
+	res.Body.Close()
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest wireless: %d", res.StatusCode)
+	}
+	entry = findAgentEntry(getAgents(t, ts), "flint2")
+	if entry == nil {
+		t.Fatal("el agente desapareció del listado")
+	}
+	if entry.RouterID != "gl-inet-gl-mt6000" {
+		t.Fatalf("el push wireless-only perdió la asociación: routerId=%q", entry.RouterID)
+	}
+	if entry.Hostname != "flint2" {
+		t.Fatalf("hostname retenido = %q, esperaba flint2", entry.Hostname)
+	}
+	if !entry.Fresh {
+		t.Fatalf("el agente debería seguir fresco: %+v", entry)
+	}
+}

+ 16 - 4
server-go/internal/httpapi/wifi_channelplan.go

@@ -53,17 +53,29 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 				return slug
 			}
 			var payload *probe.Payload
+			host, bridgeMAC := "", ""
 			if s.agents != nil {
 				if st := s.agents.Snapshot(slug); st != nil {
 					payload = st.Payload
 				}
+				// #1874: un push event-driven (wireless-only) no trae board ni
+				// bridge MAC; la identidad retenida mantiene la asociación.
+				host, bridgeMAC, _ = s.agents.Identity(slug)
 			}
-			if payload != nil && payload.Data.System != nil && payload.Data.System.Board != nil {
-				if norm(payload.Data.System.Board.Hostname) == want {
-					return slug
+			if payload != nil && payload.Data.System != nil {
+				if b := payload.Data.System.Board; b != nil {
+					if h := strings.TrimSpace(b.Hostname); h != "" {
+						host = h
+					}
+				}
+				if bridgeMAC == "" {
+					bridgeMAC = payload.Data.System.BridgeMAC
 				}
 			}
-			if id := resolveAgentRouter(slug, payload, routerByID); id != "" {
+			if norm(host) == want {
+				return slug
+			}
+			if id := resolveAgentRouterIdentity(slug, host, bridgeMAC, routerByID); id != "" {
 				if id == routerID || norm(routerByID[id].Name) == want || norm(routerByID[id].Host) == want {
 					return slug
 				}