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

fix(ssh): port #373 ubus-first wireless probe and cache radios (#552)

The server SSH poller still ran the pre-#373 command pair on every
5s tick: CmdIwinfoAssoc for clients and CmdRadios for the radio
summary, both spawning iwinfo (a ucode script) per interface. On
low-end single-core APs (Archer A7 v5) that drove load average to
~20 while the router was polled over SSH.

Port the agent fix (#368/#373) to the SSH path:
- GetWirelessClients: ubus hostapd get_clients first (authoritative
  when hostapd.* objects exist, even with zero clients so an empty
  AP does not fall back to iwinfo); single-pass CmdWirelessCombined
  fallback; legacy pair only as last resort.
- GetRadios: cache the per-band summary for radiosTTL (5 min,
  matching the agent) instead of refreshing iwinfo on every poll.

OpenWrtClient.pool now uses the poolRunner interface so the wireless
path is testable with a fake runner (same pattern as sshRunner).
5 new tests cover ubus-first, empty AP, combined fallback, legacy
fallback and the radios TTL.

Closes #550

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
45236ab057

+ 93 - 12
server-go/internal/adapters/openwrt.go

@@ -27,15 +27,28 @@ import (
 const (
 	ubusHTTPTimeout = 4 * time.Second
 	iwinfoTimeout   = 8 * time.Second
+	// radiosTTL (#368/#373, paridad con el agente): el resumen de radios
+	// (canal/htmode/txpower) apenas cambia; cachearlo evita correr iwinfo en
+	// cada poll de 5 s del server contra APs de bajas prestaciones (p.ej.
+	// Archer A7 v5). El agente usa el mismo TTL desde el PR #373.
+	radiosTTL = 5 * time.Minute
 )
 
+// poolRunner es el subconjunto de *SSHPool que usa OpenWrtClient (Run para
+// los comandos y RunCtx para LLDP). Permite inyectar un runner falso en
+// tests, igual que sshRunner para las funciones live sueltas.
+type poolRunner interface {
+	Run(host, cmd string, timeout time.Duration) (string, error)
+	RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error)
+}
+
 // OpenWrtClient es el cliente de un router (uno por router del config).
 type OpenWrtClient struct {
 	Host     string
 	User     string // para ubus HTTP (default root)
 	Password string
 
-	pool *SSHPool
+	pool poolRunner
 
 	// mu protege el estado mutable del cliente (sid, lastStat, lastNetDev,
 	// lldpDownUntil): los handlers HTTP pueden sondear (p.ej. GetSurvey) en
@@ -51,6 +64,12 @@ type OpenWrtClient struct {
 	// lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
 	// martillear con un comando que no existe. Acceso serializado por mu.
 	lldpDownUntil time.Time
+
+	// radiosMu serializa la caché de radios (radiosCache/radiosAt): el
+	// poller y los handlers HTTP pueden sondear el mismo cliente en paralelo.
+	radiosMu    sync.Mutex
+	radiosCache []Radio // resumen por banda, refrescado cada radiosTTL
+	radiosAt    time.Time
 }
 
 type cpuSample struct{ total, idleAll float64 }
@@ -79,7 +98,7 @@ type (
 )
 
 // NewOpenWrtClient crea el cliente de un router.
-func NewOpenWrtClient(cfg RouterConfig, pool *SSHPool, user, password string) *OpenWrtClient {
+func NewOpenWrtClient(cfg RouterConfig, pool poolRunner, user, password string) *OpenWrtClient {
 	if user == "" {
 		user = "root"
 	}
@@ -386,8 +405,32 @@ func parseDhcpLeasesFile(out string) []DhcpLease {
 	return probe.ParseDhcpLeasesFile(out)
 }
 
-// GetWirelessClients: iwinfo assoclist por radio → mapa MAC → cliente.
+// GetWirelessClients: clientes wifi asociados (MAC → señal/banda). Port del
+// fix #373 (#368) al sondeo SSH: ubus hostapd get_clients primero (una
+// llamada ubus barata por AP, sin ucode/iwinfo), fallback de iwinfo combinado
+// en UNA pasada por interfaz, y como último recurso el par legacy. Vacío si
+// el router no expone ninguna fuente wireless.
 func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
+	// 1. ubus hostapd get_clients (barato; APs con hostapd ubus moderno).
+	// Autoritativo cuando hay objetos hostapd.* (incluso con 0 clientes: un
+	// AP vacío no debe caer al fallback iwinfo en cada poll de 5 s del
+	// server). Solo si ubus no expone objetos se baja al fallback.
+	if out, err := c.pool.Run(c.Host, probe.CmdHostapdClients, iwinfoTimeout); err == nil && strings.Contains(out, "==AP==") {
+		return probe.ParseHostapdClients(out)
+	}
+	// 2. iwinfo combinado en UNA pasada (info + assoclist juntos por interfaz;
+	// emite clientes y radios). Mitad de spawns que el par legacy de abajo.
+	// Las radios se cachean aunque no haya clientes (GetRadios no re-sondea).
+	if out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout); err == nil {
+		clients, radios := probe.ParseWirelessCombined(out)
+		if len(radios) > 0 {
+			c.setRadiosCache(radiosToAdapter(radios))
+		}
+		if len(clients) > 0 {
+			return clients
+		}
+	}
+	// 3. Último recurso: par legacy (equipos donde el combinado no aplica).
 	out, err := c.pool.Run(c.Host, probe.CmdIwinfoAssoc, iwinfoTimeout)
 	if err != nil {
 		return map[string]WirelessClient{}
@@ -400,6 +443,53 @@ func parseWirelessClients(out string) map[string]WirelessClient {
 	return probe.ParseWirelessClients(out)
 }
 
+// GetRadios: radios activas por banda (canal/htmode/txpower + nº clientes).
+// Cacheadas radiosTTL (5 min): el resumen de radios apenas cambia y correr
+// CmdRadios (iwinfo) en CADA poll de 5 s del server quemaba CPU en APs de
+// bajas prestaciones (port #373 al sondeo SSH). Si la caché está fresca se
+// devuelve sin tocar el router; si caducó (o está vacía) se refresca.
+func (c *OpenWrtClient) GetRadios() []Radio {
+	c.radiosMu.Lock()
+	cached := c.radiosCache
+	if len(cached) > 0 && time.Since(c.radiosAt) < radiosTTL {
+		c.radiosMu.Unlock()
+		return cached
+	}
+	c.radiosMu.Unlock()
+
+	// Refresco. Prioridad al combinado (una pasada por interfaz) cuando ubus
+	// no estuvo disponible para clientes: el propio comando emite las radios.
+	out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout)
+	if err == nil {
+		if _, radios := probe.ParseWirelessCombined(out); len(radios) > 0 {
+			rs := radiosToAdapter(radios)
+			c.setRadiosCache(rs)
+			return rs
+		}
+	}
+	out, err = c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
+	if err != nil {
+		return []Radio{}
+	}
+	rs := parseRadios(out)
+	if len(rs) > 0 {
+		c.setRadiosCache(rs)
+	}
+	return rs
+}
+
+// setRadiosCache guarda el resumen de radios con su timestamp (best-effort:
+// no falla si la caché está vacía; el poller reintenta en el próximo ciclo).
+func (c *OpenWrtClient) setRadiosCache(rs []Radio) {
+	if len(rs) == 0 {
+		return
+	}
+	c.radiosMu.Lock()
+	c.radiosCache = rs
+	c.radiosAt = time.Now()
+	c.radiosMu.Unlock()
+}
+
 // GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
 // interfaz STA activa/asociada en `ubus call network.wireless status`).
 // Error si el router no soporta la llamada (sin wifi → el caller omite el
@@ -555,15 +645,6 @@ func (c *OpenWrtClient) GetBridgeVlans() []probe.VlanPort {
 // Radios WiFi
 // ---------------------------------------------------------------------------
 
-// GetRadios: radios activas agregadas por banda (iwinfo info + assoclist).
-func (c *OpenWrtClient) GetRadios() []Radio {
-	out, err := c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
-	if err != nil {
-		return []Radio{}
-	}
-	return parseRadios(out)
-}
-
 // parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
 func parseRadios(out string) []Radio {
 	return radiosToAdapter(probe.ParseRadios(out))

+ 169 - 0
server-go/internal/adapters/openwrt_wireless_test.go

@@ -0,0 +1,169 @@
+package adapters
+
+import (
+	"context"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// fakeWirelessRunner es un poolRunner que responde por comando exacto y
+// registra las llamadas para poder afirmar qué se ejecutó (y qué NO).
+type fakeWirelessRunner struct {
+	calls     []string
+	responses map[string]string
+	errs      map[string]error
+}
+
+func (f *fakeWirelessRunner) Run(host, cmd string, timeout time.Duration) (string, error) {
+	f.calls = append(f.calls, cmd)
+	if err := f.errs[cmd]; err != nil {
+		return "", err
+	}
+	return f.responses[cmd], nil
+}
+
+func (f *fakeWirelessRunner) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
+	return f.Run(host, cmd, timeout)
+}
+
+func (f *fakeWirelessRunner) ran(cmd string) bool {
+	for _, c := range f.calls {
+		if c == cmd {
+			return true
+		}
+	}
+	return false
+}
+
+const hostapdTwoAPOut = `==AP==hostapd.phy0-ap0
+{
+	"freq": 2437,
+	"clients": {
+		"AA:BB:CC:DD:EE:FF": { "auth": true, "assoc": true, "authorized": true, "signal": -55 }
+	}
+}
+==AP==hostapd.phy1-ap0
+{
+	"freq": 5180,
+	"clients": {
+		"AA:BB:CC:DD:EE:01": { "auth": true, "assoc": true, "authorized": true, "signal": -42 }
+	}
+}`
+
+// ubus-first (#373 en SSH): con objetos hostapd ubus, GetWirelessClients
+// devuelve los clientes SIN ejecutar iwinfo (ni combined ni assoclist).
+func TestGetWirelessClientsUbusFirstNoIwinfo(t *testing.T) {
+	r := &fakeWirelessRunner{responses: map[string]string{probe.CmdHostapdClients: hostapdTwoAPOut}}
+	c := &OpenWrtClient{Host: "192.168.1.9", pool: r}
+
+	m := c.GetWirelessClients()
+	if len(m) != 2 {
+		t.Fatalf("clientes: %d (want 2)", len(m))
+	}
+	if r.ran(probe.CmdWirelessCombined) || r.ran(probe.CmdIwinfoAssoc) {
+		t.Fatalf("ubus-first tocó iwinfo: %v", r.calls)
+	}
+}
+
+// AP vacío con hostapd ubus: 0 clientes es un resultado REAL, no debe caer al
+// fallback iwinfo en cada poll de 5 s (el bug de CPUs justas #368).
+func TestGetWirelessClientsUbusEmptyAPNoIwinfo(t *testing.T) {
+	empty := `==AP==hostapd.phy0-ap0
+{
+	"freq": 2437,
+	"clients": {}
+}`
+	r := &fakeWirelessRunner{responses: map[string]string{probe.CmdHostapdClients: empty}}
+	c := &OpenWrtClient{Host: "192.168.1.9", pool: r}
+
+	m := c.GetWirelessClients()
+	if len(m) != 0 {
+		t.Fatalf("clientes: %+v (want 0)", m)
+	}
+	if r.ran(probe.CmdWirelessCombined) || r.ran(probe.CmdIwinfoAssoc) {
+		t.Fatalf("AP vacío con ubus tocó iwinfo: %v", r.calls)
+	}
+}
+
+// Sin objetos hostapd ubus (p.ej. wpad básico): cae al iwinfo combinado en UNA
+// pasada, que además puebla la caché de radios para GetRadios.
+func TestGetWirelessClientsFallbackCombined(t *testing.T) {
+	combined := "R|2.437|6|HE20|22|2\nC|AA:BB:CC:DD:EE:FF|-55|2.437\n"
+	r := &fakeWirelessRunner{responses: map[string]string{
+		probe.CmdHostapdClients:   "",
+		probe.CmdWirelessCombined: combined,
+		probe.CmdIwinfoAssoc:      "AA:BB:CC:DD:EE:FF -55 2.4\n",
+	}}
+	c := &OpenWrtClient{Host: "192.168.1.9", pool: r}
+
+	m := c.GetWirelessClients()
+	if len(m) != 1 {
+		t.Fatalf("clientes: %d (want 1)", len(m))
+	}
+	if r.ran(probe.CmdIwinfoAssoc) {
+		t.Fatalf("el combinado bastó; no debe tocar el par legacy: %v", r.calls)
+	}
+	c.radiosMu.Lock()
+	cached := c.radiosCache
+	c.radiosMu.Unlock()
+	if len(cached) != 1 {
+		t.Fatalf("caché de radios no poblada por el combinado: %+v", cached)
+	}
+}
+
+// Sin ubus ni combined: último recurso legacy (CmdIwinfoAssoc).
+func TestGetWirelessClientsLegacyFallback(t *testing.T) {
+	r := &fakeWirelessRunner{responses: map[string]string{
+		probe.CmdHostapdClients:   "ubus: not found\n",
+		probe.CmdWirelessCombined: "",
+		probe.CmdIwinfoAssoc:      "AA:BB:CC:DD:EE:FF -55 5\n",
+	}}
+	c := &OpenWrtClient{Host: "192.168.1.9", pool: r}
+
+	m := c.GetWirelessClients()
+	if len(m) != 1 {
+		t.Fatalf("clientes: %d (want 1)", len(m))
+	}
+	if !r.ran(probe.CmdIwinfoAssoc) {
+		t.Fatalf("legacy no se usó: %v", r.calls)
+	}
+}
+
+// GetRadios refresca al arranque (caché vacía) y sirve de la caché en las
+// llamadas siguientes SIN volver a tocar el router (radiosTTL).
+func TestGetRadiosCacheTTL(t *testing.T) {
+	combined := "R|5.240|48|HE80|23|1\nC|AA:BB:CC:DD:EE:01|-40|5.240\n"
+	r := &fakeWirelessRunner{responses: map[string]string{
+		probe.CmdHostapdClients:   "",
+		probe.CmdWirelessCombined: combined,
+		probe.CmdRadios:           "5.24|48|HE80|23|1\n",
+	}}
+	c := &OpenWrtClient{Host: "192.168.1.9", pool: r}
+
+	rs1 := c.GetRadios()
+	if len(rs1) != 1 || rs1[0].Channel != 48 {
+		t.Fatalf("primera llamada: %+v", rs1)
+	}
+	n1 := len(r.calls)
+	rs2 := c.GetRadios()
+	if len(rs2) != 1 {
+		t.Fatalf("segunda llamada: %+v", rs2)
+	}
+	if len(r.calls) != n1 {
+		t.Fatalf("la caché fresca no debe re-sondear: %v", r.calls)
+	}
+
+	// Caducada: al envejecer radiosAt, la siguiente llamada refresca.
+	c.radiosMu.Lock()
+	c.radiosAt = time.Now().Add(-radiosTTL - time.Second)
+	c.radiosMu.Unlock()
+	rs3 := c.GetRadios()
+	if len(rs3) != 1 {
+		t.Fatalf("refresco tras TTL: %+v", rs3)
+	}
+	if len(r.calls) <= n1 {
+		t.Fatalf("TTL caducado debe refrescar: %v", r.calls)
+	}
+}