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

feat(channelplan): explain why a radio has no neighbour scan (#1848) (#1849)

Nacho 1 месяц назад
Родитель
Сommit
db1056eb8b

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- A radio with no neighbour scan now says why (#1848). A scan can end in three ways and the plan used to show the same empty table for all of them: the radio answered and found nothing, the radio refused the scan, or the agent never ran it. The agent already knew the reason, since `iw` writes it to standard error and the shell runner used to drop it, so it now keeps the last line and sends one outcome per radio with the interface it ended up using and the number of BSSes it saw. The server stores the last outcome per interface and the channel plan shows it under the radio, which turns an empty table into a sentence that names the errno.
 - A managed Netgear switch reports its chip again (#1835). The FastPath family publishes the model, the chip and the firmware in its private subtree, and nothing in the SNMP path read it, so the detail row stayed blank on a unit that has no agent to read `/proc/cpuinfo`. The identity is polled only when `sysObjectID` sits in the Netgear enterprise subtree, so no other vendor pays for a private query, and a unit that does not answer keeps whatever the generic readers found. Firmware and short model are used as fallbacks only, because ENTITY-MIB already answers those two. Memory is deliberately left empty: the subtree has `MemFree` and `MemAvailable` but no total, and a percentage built from those two measures the reclaimable part, not the used one.
 - The agent push interval is a per-unit setting (#1476). Units differ in how often they should report: a busy access point wants a short cadence, a modem on a metered link does not. The reinstall now writes the value into `/etc/config/netpulse-agent` through `uci`, next to the server and the token, so it lands in the conffile that survives a sysupgrade. Leaving it empty removes the key and the agent falls back to its own default of 30 seconds, so nothing changes for a unit that never sets it.
 - The ASU exclusion list can be written on the router from the firmware card (#1769). When `owut check` reports packages missing in the target version, the card offers to append them to `attendedsysupgrade.owut.remove` with `uci` and commit, after a confirmation. That makes `owut download`, `owut install` and `owut upgrade` behave exactly like running them by hand on the unit, instead of keeping a second list in the browser. Package names are validated before they reach a shell line, and packages already in the list are not duplicated.

+ 1 - 0
app/public/locales/en/translation.json

@@ -2379,6 +2379,7 @@
     "noScans": "No recent scans for this router. Routers running NetGrip (gateway and managed APs) do not scan neighbors; routers with the NetPulse agent do. Try rt2 or rt4.",
     "noRadios": "This router does not report WiFi radios.",
     "noBandScans": "This radio sees no networks on this band.",
+    "scanRefused": "This radio refused the scan: {{reason}}",
     "noNeighborsBlock": "No neighbor networks in the whole block.",
     "neighborsBlock": "{{count}} neighbor networks · strongest at {{dbm}} dBm.",
     "alreadyOptimal": "Already the one you use.",

+ 1 - 0
app/public/locales/es/translation.json

@@ -2379,6 +2379,7 @@
     "noScans": "Sin escaneos recientes para este equipo. Los que corren NetGrip (puerta de enlace y APs gestionados) no escanean vecinos; los que llevan agente NetPulse sí. Prueba con rt2 o rt4.",
     "noRadios": "Este equipo no reporta radios WiFi.",
     "noBandScans": "Esta radio no ve redes en esta banda.",
+    "scanRefused": "Esta radio rechazó el escaneo: {{reason}}",
     "noNeighborsBlock": "Sin redes vecinas en todo el bloque.",
     "neighborsBlock": "{{count}} redes vecinas · la más fuerte a {{dbm}} dBm.",
     "alreadyOptimal": "Es el que ya estás usando.",

+ 5 - 0
app/src/pages/ChannelPlan.tsx

@@ -56,6 +56,8 @@ interface RadioRec {
   currentScore: number
   bestScore: number
   scores?: Score[]
+  // #1848: motivo por el que el agente no pudo escanear esta radio.
+  scanError?: string
 }
 
 interface ChannelPlanData {
@@ -753,6 +755,9 @@ export default function ChannelPlan() {
                   if (cur) {
                     return cur.neighbors === 0 ? t('channelPlan.noOverlap') : t('channelPlan.neighborsInBlock', { count: cur.neighbors })
                   }
+                  if (!currentScoreValid && active?.scanError) {
+                    return t('channelPlan.scanRefused', { reason: active.scanError })
+                  }
                   return currentScoreValid ? t('channelPlan.noOverlap') : t('channelPlan.noBandScans')
                 })()}
               </p>

+ 101 - 0
server-go/internal/channelplan/scan_outcomes_1848_test.go

@@ -0,0 +1,101 @@
+package channelplan_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/channelplan"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// #1848: el motivo de un scan rechazado tiene que sobrevivir al push y salir
+// tal cual, porque es lo unico que distingue "el driver lo rechazo" de "no
+// habia vecinos".
+func TestScanOutcomesRoundTrip(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	out := []probe.ScanOutcome{
+		{Iface: "eth6", Phy: 1, BSS: 0, Error: "command failed: Operation not supported (-95)"},
+		{Iface: "eth5", Phy: 0, BSS: 16, Error: ""},
+	}
+	if err := st.SaveScanOutcomes("rt1", 1000, out); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+
+	got, err := st.ScanOutcomes("rt1")
+	if err != nil {
+		t.Fatalf("read: %v", err)
+	}
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 outcomes, got %d", len(got))
+	}
+	byIface := map[string]channelplan.ScanOutcomeRow{}
+	for _, oc := range got {
+		byIface[oc.Iface] = oc
+	}
+	if oc := byIface["eth6"]; oc.Phy != 1 || oc.BSS != 0 || oc.Error == "" || oc.Ts != 1000 {
+		t.Fatalf("outcome del rechazo mal guardado: %+v", oc)
+	}
+	if oc := byIface["eth5"]; oc.Phy != 0 || oc.BSS != 16 || oc.Error != "" {
+		t.Fatalf("outcome del scan correcto mal guardado: %+v", oc)
+	}
+}
+
+// El ultimo estado manda: dos ciclos del mismo radio no dejan dos filas.
+func TestScanOutcomesUpsert(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	if err := st.SaveScanOutcomes("rt1", 1000, []probe.ScanOutcome{
+		{Iface: "eth6", Phy: 1, BSS: 0, Error: "Resource temporarily unavailable (-11)"},
+	}); err != nil {
+		t.Fatalf("save 1: %v", err)
+	}
+	if err := st.SaveScanOutcomes("rt1", 2000, []probe.ScanOutcome{
+		{Iface: "eth6", Phy: 1, BSS: 9, Error: ""},
+	}); err != nil {
+		t.Fatalf("save 2: %v", err)
+	}
+
+	got, err := st.ScanOutcomes("rt1")
+	if err != nil {
+		t.Fatalf("read: %v", err)
+	}
+	if len(got) != 1 {
+		t.Fatalf("esperaba 1 fila por interfaz, got %d", len(got))
+	}
+	if got[0].BSS != 9 || got[0].Error != "" || got[0].Ts != 2000 {
+		t.Fatalf("el segundo ciclo no sustituyo al primero: %+v", got[0])
+	}
+}
+
+// Un agente anterior a 3.0.34 no manda el campo: la tabla queda vacia y la
+// vista no debe romperse por eso.
+func TestScanOutcomesVacio(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	if err := st.SaveScanOutcomes("rt1", 1000, []probe.ScanOutcome{{Iface: ""}}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got, err := st.ScanOutcomes("rt1")
+	if err != nil {
+		t.Fatalf("read: %v", err)
+	}
+	if len(got) != 0 {
+		t.Fatalf("una interfaz vacia no debe guardarse: %+v", got)
+	}
+}

+ 76 - 5
server-go/internal/channelplan/store.go

@@ -55,6 +55,74 @@ func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) er
 	return tx.Commit()
 }
 
+// ScanOutcomeRow es el ultimo resultado del scan de una interfaz (#1848).
+// Error vacio con BSS 0 significa "escaneo y no habia nada"; Error con el
+// texto del driver significa que el scan se rechazo.
+type ScanOutcomeRow struct {
+	Iface string `json:"iface"`
+	Phy   int    `json:"phy"`
+	BSS   int    `json:"bss"`
+	Error string `json:"error,omitempty"`
+	Ts    int64  `json:"ts"`
+}
+
+// SaveScanOutcomes guarda el resultado del ultimo scan por interfaz. Se llama
+// en cada push que escanea, haya o no vecinos: un rechazo del driver tambien
+// es informacion (#1848). El payload lo manda el agente desde 3.0.34.
+func (s *Store) SaveScanOutcomes(routerID string, ts int64, outcomes []probe.ScanOutcome) error {
+	if len(outcomes) == 0 {
+		return nil
+	}
+	tx, err := s.db.Begin()
+	if err != nil {
+		return err
+	}
+	defer tx.Rollback()
+
+	stmt, err := tx.Prepare(`
+		INSERT INTO wifi_scan_outcomes (router_id, iface, phy, bss, err, ts)
+		VALUES (?, ?, ?, ?, ?, ?)
+		ON CONFLICT(router_id, iface) DO UPDATE SET
+			phy = excluded.phy, bss = excluded.bss, err = excluded.err, ts = excluded.ts
+	`)
+	if err != nil {
+		return err
+	}
+	defer stmt.Close()
+
+	for _, oc := range outcomes {
+		if oc.Iface == "" {
+			continue
+		}
+		if _, err := stmt.Exec(routerID, oc.Iface, oc.Phy, oc.BSS, oc.Error, ts); err != nil {
+			return err
+		}
+	}
+	return tx.Commit()
+}
+
+// ScanOutcomes devuelve el ultimo resultado por interfaz, el mas reciente
+// primero. Un agente anterior a 3.0.34 no manda el campo y esto sale vacio.
+func (s *Store) ScanOutcomes(routerID string) ([]ScanOutcomeRow, error) {
+	rows, err := s.db.Query(`
+		SELECT iface, phy, bss, err, ts FROM wifi_scan_outcomes
+		WHERE router_id = ? ORDER BY ts DESC, iface`, routerID)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+
+	out := []ScanOutcomeRow{}
+	for rows.Next() {
+		var oc ScanOutcomeRow
+		if err := rows.Scan(&oc.Iface, &oc.Phy, &oc.BSS, &oc.Error, &oc.Ts); err != nil {
+			return nil, err
+		}
+		out = append(out, oc)
+	}
+	return out, rows.Err()
+}
+
 // ScanRow es un vecino persistido (forma plana para la UI/API).
 type ScanRow struct {
 	Iface   string `json:"iface"`
@@ -161,11 +229,14 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 
 // Radio es un resumen de una radio propia con su canal actual y recomendación.
 type Radio struct {
-	Iface        string `json:"iface"`
-	Name         string `json:"name"`    // "2.4 GHz" | "5 GHz" | "6 GHz"
-	Channel      int    `json:"channel"` // canal actual
-	WidthMhz     int    `json:"widthMhz"`
-	Recommended  int    `json:"recommended"` // canal recomendado; 0 = sin datos
+	Iface       string `json:"iface"`
+	Name        string `json:"name"`    // "2.4 GHz" | "5 GHz" | "6 GHz"
+	Channel     int    `json:"channel"` // canal actual
+	WidthMhz    int    `json:"widthMhz"`
+	Recommended int    `json:"recommended"` // canal recomendado; 0 = sin datos
+	// ScanError (#1848) lleva el motivo del ultimo intento cuando el driver
+	// rechazo el scan. Vacio con medidas o cuando la banda estaba vacia.
+	ScanError    string `json:"scanError,omitempty"`
 	CurrentScore int    `json:"currentScore"`
 	BestScore    int    `json:"bestScore"`
 	// Scores puntúa TODOS los canales/bloques de la banda (no solo los

+ 14 - 0
server-go/internal/db/db.go

@@ -363,6 +363,20 @@ CREATE TABLE IF NOT EXISTS wifi_scans (
 CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
 CREATE INDEX IF NOT EXISTS idx_wifi_scans_channel ON wifi_scans(channel, freq);
 
+-- wifi_scan_outcomes (#1848): ultimo resultado del scan de vecinos por
+-- interfaz. Guarda el motivo cuando el driver lo rechaza, para que la vista
+-- de canales no muestre una banda vacia sin explicacion. Es el ultimo estado
+-- conocido, no un historico: una fila por router e interfaz.
+CREATE TABLE IF NOT EXISTS wifi_scan_outcomes (
+  router_id TEXT NOT NULL,
+  iface     TEXT NOT NULL,
+  phy       INTEGER NOT NULL DEFAULT -1,
+  bss       INTEGER NOT NULL DEFAULT 0,
+  err       TEXT NOT NULL DEFAULT '',
+  ts        INTEGER NOT NULL,
+  PRIMARY KEY (router_id, iface)
+);
+
 -- Firmware upgrades de routers OpenWrt (#453).
 -- firmware_targets: información de firmware soportado por router.
 CREATE TABLE IF NOT EXISTS firmware_targets (

+ 9 - 0
server-go/internal/httpapi/agent.go

@@ -312,6 +312,15 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 			ev.EvalNewNeighborSsids()
 		}
 	}
+	// #1848: el resultado del scan tambien llega en los pushes que escanean
+	// sin encontrar nada, asi que se guarda aparte de los vecinos. Sin esto la
+	// vista de canales no puede distinguir "el driver lo rechazo" de "banda
+	// vacia".
+	if s.channelPlan != nil && p.Data.Wireless != nil && len(p.Data.Wireless.ScanOutcomes) > 0 {
+		if err := s.channelPlan.SaveScanOutcomes(p.Router, p.Ts, p.Data.Wireless.ScanOutcomes); err != nil {
+			log.Printf("[netpulse] error guardando scanOutcomes de %s: %v", p.Router, err)
+		}
+	}
 	// #1214: survey crudo del agente para la lente "Ahora" en unidades
 	// agent-only. El adaptador Live lo cachea en memoria con TTL; los
 	// adaptadores sin survey (demo) no implementan la interfaz y se omiten.

+ 24 - 3
server-go/internal/httpapi/wifi_channelplan.go

@@ -127,10 +127,31 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 			return
 		}
 
+		// #1848: motivo del ultimo scan por interfaz. Va en la respuesta y,
+		// cuando la interfaz coincide, pegado al radio: es lo que explica una
+		// banda a cero sin inventar datos.
+		outcomes, err := s.channelPlan.ScanOutcomes(slug)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "channel_plan_error")
+			return
+		}
+		reasonByIface := map[string]string{}
+		for _, oc := range outcomes {
+			if oc.Error != "" {
+				reasonByIface[oc.Iface] = oc.Error
+			}
+		}
+		for i := range recommendations {
+			if reason := reasonByIface[recommendations[i].Iface]; reason != "" {
+				recommendations[i].ScanError = reason
+			}
+		}
+
 		writeJSON(w, http.StatusOK, map[string]any{
-			"routerId": routerID,
-			"radios":   recommendations,
-			"scans":    scans,
+			"routerId":     routerID,
+			"radios":       recommendations,
+			"scans":        scans,
+			"scanOutcomes": outcomes,
 		})
 	})))
 

+ 82 - 0
server-go/internal/httpapi/wifi_channelplan_scanerror_1848_test.go

@@ -0,0 +1,82 @@
+// wifi_channelplan_scanerror_1848_test.go — #1848: el plan de canales debe
+// decir por que un radio no tiene medidas, no solo que no las tiene.
+package httpapi_test
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestChannelPlanSurfacesScanError(t *testing.T) {
+	ts := makeTestServer(t)
+	token, cookie := createAgentAndLogin(t, ts)
+
+	const motivo = "command failed: Operation not supported (-95)"
+	payload := probe.Payload{
+		Router:  "rt1",
+		Ts:      time.Now().Unix(),
+		Version: "test",
+		Data: probe.PayloadData{
+			Wireless: &probe.WirelessData{
+				Clients: map[string]probe.WirelessClient{},
+				Radios: []probe.Radio{
+					{Name: "5 GHz", Channel: 48, WidthMhz: 80, Section: "eth6"},
+				},
+				ScanOutcomes: []probe.ScanOutcome{
+					{Iface: "eth6", Phy: 1, BSS: 0, Error: motivo},
+				},
+			},
+		},
+	}
+	res := pushPayload(t, ts, token, "10.0.9.2", payload)
+	if res.StatusCode != http.StatusAccepted {
+		b, _ := io.ReadAll(res.Body)
+		res.Body.Close()
+		t.Fatalf("ingest: %d %s", res.StatusCode, string(b))
+	}
+	res.Body.Close()
+
+	req, _ := http.NewRequest("GET", ts.URL+"/api/wifi/channel-plan?routerId=rt1", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("channel-plan: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		b, _ := io.ReadAll(res.Body)
+		t.Fatalf("channel-plan: %d %s", res.StatusCode, string(b))
+	}
+
+	var body struct {
+		Radios []struct {
+			Iface     string `json:"iface"`
+			ScanError string `json:"scanError"`
+		} `json:"radios"`
+		ScanOutcomes []struct {
+			Iface string `json:"iface"`
+			BSS   int    `json:"bss"`
+			Error string `json:"error"`
+		} `json:"scanOutcomes"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("decode: %v", err)
+	}
+	if len(body.Radios) != 1 {
+		t.Fatalf("esperaba 1 radio, got %d", len(body.Radios))
+	}
+	if body.Radios[0].ScanError != motivo {
+		t.Errorf("el radio debe llevar el motivo del rechazo: %q", body.Radios[0].ScanError)
+	}
+	if len(body.ScanOutcomes) != 1 {
+		t.Fatalf("esperaba 1 outcome, got %d", len(body.ScanOutcomes))
+	}
+	if body.ScanOutcomes[0].Iface != "eth6" || body.ScanOutcomes[0].Error != motivo {
+		t.Errorf("outcome inesperado: %+v", body.ScanOutcomes[0])
+	}
+}