Răsfoiți Sursa

feat(roaming): feed /api/usteer from agent payloads on agent-only fleets (#1431)

Agent-only fleets (routers managed by the embedded agent, e.g. NetGrip) got an empty Roaming page with "failed to load usteer state": GetUsteer only probed by SSH and skipped agent-only routers, so with every router agent-only the endpoint returned 503 even though usteer was running and every agent pushed its full state.

For agent-only routers the view now builds from the freshest agent payload in the registry: local APs only (remote mesh APs already show up as locals of their own router; old agents without the Local flag assume all local), Iface resolved via wireless.ownBssids, band from freq, clients attached to their band's AP with station signal preferred and usteer signal as fallback. SNMP routers keep being skipped; SSH-managed routers keep the SSH probe as primary.

Verified against a real two-AP agent-only fleet: 4 APs with all clients and per-router mesh state.

Closes #1431
Nacho 1 lună în urmă
părinte
comite
3071f82e9c

+ 19 - 1
server-go/internal/adapters/live.go

@@ -4145,6 +4145,11 @@ type usteerClientRaw struct {
 func (l *Live) GetUsteer(context.Context) (*Usteer, error) {
 func (l *Live) GetUsteer(context.Context) (*Usteer, error) {
 	l.mu.Lock()
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	routers := append([]RouterConfig(nil), l.routers...)
+	reg := l.agents
+	macs := make(map[string]string, len(l.routerMacs))
+	for k, v := range l.routerMacs {
+		macs[k] = v
+	}
 	l.mu.Unlock()
 	l.mu.Unlock()
 
 
 	aps := []UsteerAP{}
 	aps := []UsteerAP{}
@@ -4154,10 +4159,23 @@ func (l *Live) GetUsteer(context.Context) (*Usteer, error) {
 		if name == "" {
 		if name == "" {
 			name = cfg.ID
 			name = cfg.ID
 		}
 		}
-		if cfg.AgentOnly || cfg.SnmpEnabled {
+		if cfg.SnmpEnabled {
 			mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
 			mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
 			continue
 			continue
 		}
 		}
+		if cfg.AgentOnly {
+			// #1431: en flotas agent-only no hay sondeo SSH; la vista se
+			// alimenta del payload que el agente empuja (usteer + wireless).
+			apsR, seen := []UsteerAP{}, 0
+			if reg != nil {
+				if _, p, fresh := reg.MatchRouter(cfg, macs); fresh && p != nil {
+					apsR, seen = usteerAPsFromPayload(name, p)
+				}
+			}
+			mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: seen > 0, ApsSeen: seen})
+			aps = append(aps, apsR...)
+			continue
+		}
 		localOut, err := l.pool.Run(cfg.SSHAddr(), "ubus call usteer local_info", 0)
 		localOut, err := l.pool.Run(cfg.SSHAddr(), "ubus call usteer local_info", 0)
 		if err != nil {
 		if err != nil {
 			mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
 			mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})

+ 124 - 0
server-go/internal/adapters/usteer_agent.go

@@ -0,0 +1,124 @@
+// usteer_agent.go - vista usteer alimentada por el payload del agente
+// (#1431). En flotas agent-only (router.AgentOnly, el patrón NetGrip con el
+// agente embebido) no hay sondeo SSH y la vista de itinerancia se servía
+// vacía (503) aunque usteer corriera y el agente empujara su estado completo.
+// Este módulo construye el mismo shape Usteer/AP desde el payload: los APs
+// LOCALES del router (los remotos ya salen como locales de su propio
+// equipo), con iface resuelto por wireless.ownBssids y clientes colgados del
+// AP de su banda (wireless.clients trae la banda por MAC asociada).
+package adapters
+
+import (
+	"sort"
+	"strings"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// usteerAPsFromPayload devuelve los APs locales de usteer del payload y
+// cuántos vio (para mesh.apsSeen). (nil, 0) si el payload no trae sección
+// usteer o no hay APs locales que pintar.
+func usteerAPsFromPayload(name string, p *probe.Payload) ([]UsteerAP, int) {
+	if p == nil || p.Data.Usteer == nil {
+		return nil, 0
+	}
+	var ifaceByBSSID map[string]string
+	var clientBand map[string]string
+	var clientSignal map[string]int
+	if wd := p.Data.Wireless; wd != nil {
+		ifaceByBSSID = make(map[string]string, len(wd.OwnBssids))
+		for _, ob := range wd.OwnBssids {
+			ifaceByBSSID[strings.ToUpper(ob.BSSID)] = ob.Iface
+		}
+		clientBand = make(map[string]string, len(wd.Clients))
+		clientSignal = make(map[string]int, len(wd.Clients))
+		for mac, c := range wd.Clients {
+			clientBand[strings.ToUpper(mac)] = c.Band
+			clientSignal[strings.ToUpper(mac)] = c.SignalDbm
+		}
+	}
+
+	aps := []UsteerAP{}
+	for ssid, ssidData := range p.Data.Usteer.SSIDs {
+		// Los agentes con el flag Local solo emiten sus APs locales: los
+		// remotos del mesh ya se listan como locales de su propio router
+		// (mismo criterio que el sondeo SSH, que solo lee local_info). Sin
+		// flag (agentes anteriores a #417) se asume todo local.
+		hasLocalFlag := false
+		for _, ap := range ssidData.APs {
+			if ap.Local {
+				hasLocalFlag = true
+				break
+			}
+		}
+		byBand := map[string][]int{}
+		for _, ap := range ssidData.APs {
+			if hasLocalFlag && !ap.Local {
+				continue
+			}
+			band := "2.4 GHz"
+			if ap.Freq >= 5000 {
+				band = "5 GHz"
+			}
+			byBand[band] = append(byBand[band], len(aps))
+			aps = append(aps, UsteerAP{
+				SSID:           ssid,
+				BSSID:          strings.ToUpper(ap.BSSID),
+				Hostname:       name,
+				Band:           band,
+				Freq:           ap.Freq,
+				UtilizationPct: ap.Load,
+				ClientCount:    ap.Clients,
+				Local:          true,
+				Iface:          ifaceByBSSID[strings.ToUpper(ap.BSSID)],
+			})
+		}
+		attachUsteerClients(aps, byBand, ssidData.Clients, clientBand, clientSignal)
+	}
+
+	// Orden determinista: los mapas del payload iteran en orden aleatorio.
+	sort.Slice(aps, func(i, j int) bool {
+		if aps[i].SSID != aps[j].SSID {
+			return aps[i].SSID < aps[j].SSID
+		}
+		return aps[i].BSSID < aps[j].BSSID
+	})
+	return aps, len(aps)
+}
+
+// attachUsteerClients cuelga cada cliente usteer del SSID de su AP local: la
+// banda de la estación (wireless.clients) decide el AP; sin dato de banda se
+// usa el AP único del SSID. Señal: la de la estación si existe, si no la del
+// cliente usteer; señal 0/positiva = sin datos, se ignora (mismo criterio
+// que el sondeo SSH).
+func attachUsteerClients(aps []UsteerAP, byBand map[string][]int, clients map[string]probe.UsteerClient, clientBand map[string]string, clientSig map[string]int) {
+	attached := map[string]bool{}
+	for mac, uc := range clients {
+		macU := strings.ToUpper(mac)
+		if attached[macU] {
+			continue
+		}
+		signal := clientSig[macU]
+		if signal == 0 {
+			signal = uc.Signal
+		}
+		if signal >= 0 {
+			continue
+		}
+		band := clientBand[macU]
+		idxs := byBand[band]
+		if len(idxs) == 0 {
+			if band != "" || len(byBand) != 1 {
+				continue // banda desconocida con varios APs: no se adivina
+			}
+			for _, v := range byBand {
+				idxs = v
+			}
+		}
+		aps[idxs[0]].Clients = append(aps[idxs[0]].Clients, UsteerClient{MAC: macU, Signal: signal})
+		attached[macU] = true
+	}
+	for i := range aps {
+		sort.Slice(aps[i].Clients, func(x, y int) bool { return aps[i].Clients[x].MAC < aps[i].Clients[y].MAC })
+	}
+}

+ 158 - 0
server-go/internal/adapters/usteer_agent_test.go

@@ -0,0 +1,158 @@
+package adapters
+
+import (
+	"context"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// fixtureUsteerPayload: router agent-only con un SSID, 2 APs locales
+// (2.4/5 GHz) y 1 remoto del mesh, 6 clientes con distintos grados de
+// información (banda conocida, sin estación, sin señal, banda desconocida).
+func fixtureUsteerPayload() *probe.Payload {
+	return &probe.Payload{
+		Router: "rt2",
+		Data: probe.PayloadData{
+			Usteer: &probe.UsteerData{
+				SSIDs: map[string]probe.UsteerSSID{
+					"domatix": {
+						APs: []probe.UsteerAP{
+							{BSSID: "cc:d8:43:b1:e5:96", Freq: 2412, Load: 30, Clients: 3, Local: true},
+							{BSSID: "cc:d8:43:b1:e5:97", Freq: 5180, Load: 8, Clients: 1, Local: true},
+							{BSSID: "be:dc:e3:b2:d3:db", Freq: 2437, Load: 12, Clients: 5, Local: false},
+						},
+						Clients: map[string]probe.UsteerClient{
+							"aa:aa:aa:aa:aa:01": {Signal: -45},
+							"aa:aa:aa:aa:aa:02": {Signal: -70},
+							"aa:aa:aa:aa:aa:03": {Signal: -60},
+							"aa:aa:aa:aa:aa:04": {Signal: 0},   // sin señal: se ignora
+							"aa:aa:aa:aa:aa:05": {Signal: -50}, // banda desconocida con 2 APs: no se adivina
+							"aa:aa:aa:aa:aa:06": {Signal: -75}, // estación sin señal: manda la de usteer
+						},
+					},
+				},
+			},
+			Wireless: &probe.WirelessData{
+				OwnBssids: []probe.OwnBSSID{
+					{Iface: "phy0-ap0", BSSID: "CC:D8:43:B1:E5:96", SSID: "domatix"},
+					{Iface: "phy1-ap0", BSSID: "CC:D8:43:B1:E5:97", SSID: "domatix"},
+				},
+				Clients: map[string]probe.WirelessClient{
+					"aa:aa:aa:aa:aa:01": {SignalDbm: -52, Band: "2.4 GHz"},
+					"aa:aa:aa:aa:aa:02": {SignalDbm: -68, Band: "2.4 GHz"},
+					"aa:aa:aa:aa:aa:03": {SignalDbm: -61, Band: "5 GHz"},
+					"aa:aa:aa:aa:aa:06": {SignalDbm: 0, Band: "2.4 GHz"},
+				},
+			},
+		},
+	}
+}
+
+func TestUsteerAPsFromPayload(t *testing.T) {
+	aps, seen := usteerAPsFromPayload("rt2", fixtureUsteerPayload())
+	if seen != 2 || len(aps) != 2 {
+		t.Fatalf("esperaba 2 APs locales, got %d (seen=%d)", len(aps), seen)
+	}
+	// Orden determinista: 2.4 GHz primero (BSSID ...:96 < ...:97).
+	ap24, ap5 := aps[0], aps[1]
+	if ap24.BSSID != "CC:D8:43:B1:E5:96" || ap24.Iface != "phy0-ap0" {
+		t.Errorf("ap 2.4 = %+v", ap24)
+	}
+	if ap24.Band != "2.4 GHz" || ap24.Freq != 2412 || ap24.UtilizationPct != 30 || ap24.ClientCount != 3 {
+		t.Errorf("ap 2.4 band/freq/load/count = %q/%d/%d/%d", ap24.Band, ap24.Freq, ap24.UtilizationPct, ap24.ClientCount)
+	}
+	if !ap24.Local || ap24.Hostname != "rt2" || ap24.SSID != "domatix" {
+		t.Errorf("ap 2.4 local/hostname/ssid = %v/%q/%q", ap24.Local, ap24.Hostname, ap24.SSID)
+	}
+	// Clientes del 2.4: 01 (-52 de la estación, no -45 de usteer), 02 (-68)
+	// y 06 (-75 de usteer, la estación no trae señal). 04 sin señal fuera,
+	// 05 con banda desconocida y 2 APs candidatos fuera (no se adivina).
+	want24 := []UsteerClient{
+		{MAC: "AA:AA:AA:AA:AA:01", Signal: -52},
+		{MAC: "AA:AA:AA:AA:AA:02", Signal: -68},
+		{MAC: "AA:AA:AA:AA:AA:06", Signal: -75},
+	}
+	if len(ap24.Clients) != len(want24) {
+		t.Fatalf("clientes 2.4 = %+v, want %+v", ap24.Clients, want24)
+	}
+	for i, c := range want24 {
+		if ap24.Clients[i] != c {
+			t.Errorf("cliente 2.4[%d] = %+v, want %+v", i, ap24.Clients[i], c)
+		}
+	}
+	// Cliente del 5 GHz.
+	if len(ap5.Clients) != 1 || ap5.Clients[0] != (UsteerClient{MAC: "AA:AA:AA:AA:AA:03", Signal: -61}) {
+		t.Errorf("clientes 5 = %+v", ap5.Clients)
+	}
+	if ap5.Iface != "phy1-ap0" || ap5.Band != "5 GHz" {
+		t.Errorf("ap 5 = %+v", ap5)
+	}
+}
+
+// TestUsteerAPsFromPayloadOldAgent: agentes anteriores a #417 no llevan el
+// flag Local en los APs; se asume todo local (no se descarta nada).
+func TestUsteerAPsFromPayloadOldAgent(t *testing.T) {
+	p := fixtureUsteerPayload()
+	for ssid, sd := range p.Data.Usteer.SSIDs {
+		for i := range sd.APs {
+			sd.APs[i].Local = false
+		}
+		p.Data.Usteer.SSIDs[ssid] = sd
+	}
+	aps, seen := usteerAPsFromPayload("rt2", p)
+	if seen != 3 || len(aps) != 3 {
+		t.Fatalf("agente viejo: esperaba 3 APs (todo local), got %d (seen=%d)", len(aps), seen)
+	}
+}
+
+func TestUsteerAPsFromPayloadNoUsteer(t *testing.T) {
+	p := &probe.Payload{Router: "rt2", Data: probe.PayloadData{}}
+	if aps, seen := usteerAPsFromPayload("rt2", p); aps != nil || seen != 0 {
+		t.Fatalf("sin sección usteer = %+v/%d, want nil/0", aps, seen)
+	}
+	if aps, seen := usteerAPsFromPayload("rt2", nil); aps != nil || seen != 0 {
+		t.Fatalf("payload nil = %+v/%d, want nil/0", aps, seen)
+	}
+}
+
+// TestGetUsteerAgentOnlyFromPayload (#1431): un router agent-only con el
+// agente empujando alimenta /api/usteer sin sondeo SSH. Pool nil como
+// tripwire: si la guarda agent-only se rompe y toca SSH, paniquea.
+func TestGetUsteerAgentOnlyFromPayload(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "rt2", Name: "rt2", Host: "192.168.1.2", AgentOnly: true},
+	}, nil)
+	reg := NewAgentRegistry(time.Hour)
+	reg.Ingest(fixtureUsteerPayload())
+	l.SetAgents(reg)
+
+	u, err := l.GetUsteer(context.Background())
+	if err != nil {
+		t.Fatalf("unexpected error: %v", err)
+	}
+	if u == nil || len(u.APs) != 2 {
+		t.Fatalf("esperaba 2 APs, got %+v", u)
+	}
+	if len(u.Mesh) != 1 || !u.Mesh[0].Usteer || u.Mesh[0].ApsSeen != 2 || u.Mesh[0].RouterID != "rt2" {
+		t.Errorf("mesh = %+v", u.Mesh)
+	}
+}
+
+// TestGetUsteerAgentOnlyNoAgent: agent-only SIN agente asociado sigue sin
+// aportar APs (503 global si es el único router), sin paniquear por pool nil.
+func TestGetUsteerAgentOnlyNoAgent(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "rt2", Name: "rt2", Host: "192.168.1.2", AgentOnly: true},
+	}, nil)
+	l.SetAgents(NewAgentRegistry(time.Hour))
+
+	u, err := l.GetUsteer(context.Background())
+	if err != nil {
+		t.Fatalf("unexpected error: %v", err)
+	}
+	if u != nil {
+		t.Fatalf("expected nil Usteer sin agente, got %+v", u)
+	}
+}