Explorar el Código

feat(channels): agent-side survey feeds the Now lens on agent-only units (#1270)

Agent pushes raw survey text; server caches and merges. Agent 3.0.12. #1214
Nacho hace 2 meses
padre
commit
4b0718cb29

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.11
+3.0.12

+ 43 - 0
agent/probe/local.go

@@ -100,8 +100,17 @@ type Prober struct {
 	lastScanAt   time.Time
 	scanForced   bool
 	scanInterval time.Duration
+
+	// Survey en vivo (#1214): throttle propio de 5 min. No saca la radio
+	// del canal, pero el texto crudo engorda el push: no va en cada ciclo.
+	surveyMu     sync.Mutex
+	surveyForced bool
+	surveyAt     time.Time
 }
 
+// surveyInterval: mínimo entre `iw survey dump` si no hay force (#1214).
+const surveyInterval = 5 * time.Minute
+
 const radiosTTL = 5 * time.Minute
 
 const (
@@ -143,6 +152,32 @@ func (p *Prober) ForceScan() {
 	p.scanMu.Unlock()
 }
 
+// ForceSurvey pide un survey en el próximo Build (#1214): el runtime lo
+// llama cuando el server envía "refresh" por SSE.
+func (p *Prober) ForceSurvey() {
+	p.surveyMu.Lock()
+	p.surveyForced = true
+	p.surveyMu.Unlock()
+}
+
+// surveyDue decide si toca lanzar CmdSurvey en este sondeo completo: true si
+// hay force pendiente o si pasó surveyInterval desde el último intento. Al
+// devolver true registra el intento para no repetirlo.
+func (p *Prober) surveyDue() bool {
+	p.surveyMu.Lock()
+	defer p.surveyMu.Unlock()
+	if p.surveyForced {
+		p.surveyForced = false
+		p.surveyAt = time.Now()
+		return true
+	}
+	if p.surveyAt.IsZero() || time.Since(p.surveyAt) >= surveyInterval {
+		p.surveyAt = time.Now()
+		return true
+	}
+	return false
+}
+
 // scanDue decide si toca lanzar CmdScan en este sondeo completo: true si hay
 // un force pendiente (refresh del server) o si pasó scanInterval desde el
 // último intento. Con ScanDisabled los periódicos no corren nunca (solo
@@ -421,6 +456,14 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 		if out := p.runBest(ctx, CmdIwDev, 5*time.Second); out != "" {
 			wd.OwnBssids = ParseIwDev(out)
 		}
+		// Survey en vivo (#1214): ocupación por canal para la lente "Ahora"
+		// del server en unidades agent-only (sin SSH). Texto crudo: el
+		// parser vive en el server y así no se duplica.
+		if p.surveyDue() {
+			if out := p.runBest(ctx, CmdSurvey, 10*time.Second); out != "" {
+				wd.SurveyRaw = out
+			}
+		}
 	} else {
 		p.radiosMu.Lock()
 		cached := p.radiosCache

+ 5 - 0
agent/probe/payload.go

@@ -118,6 +118,11 @@ type WirelessData struct {
 	// propias redes como vecinas (casos con MAC aleatorizada o guest cuya
 	// MAC no casa con routers.mac). nil con agentes antiguos.
 	OwnBssids []OwnBSSID `json:"ownBssids,omitempty"`
+	// SurveyRaw (#1214): salida cruda de `iw dev <iface> survey dump` con
+	// marcadores "==IFACE==" por interfaz. El server la parsea con su
+	// parser (adapters.ParseIwSurvey) para la lente "Ahora" en unidades
+	// agent-only sin SSH. Vacío = sin survey fresco (throttle 5 min).
+	SurveyRaw string `json:"surveyRaw,omitempty"`
 }
 
 // OwnBSSID: una interfaz AP local con su BSSID y SSID (#1087).

+ 6 - 0
agent/probe/probe.go

@@ -90,6 +90,12 @@ const (
 	// emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
 	// Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
 	CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
+	// CmdSurvey (#1214): `iw dev <iface> survey dump` por interfaz, con el
+	// mismo marcador "==IFACE==" que CmdScan. El server parsea el texto
+	// crudo con su parser existente: alimenta la lente "Ahora" (ocupación
+	// por canal en vivo) en unidades agent-only sin SSH. Barato: no saca
+	// la radio del canal.
+	CmdSurvey = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" survey dump 2>/dev/null; done`
 	// CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con
 	// su MAC y SSID: fuente de los BSSIDs propios para el análisis de
 	// canales. Barato (no saca la radio del canal).

+ 3 - 0
agent/runtime/runtime.go

@@ -260,6 +260,9 @@ func Run(ctx context.Context, opts Options) error {
 			// forzamos el scan pasivo (no esperar al throttle #591): el
 			// usuario está mirando datos frescos de canales.
 			prober.ForceScan()
+			// Y el survey en vivo (#1214): la lente "Ahora" quiere datos
+			// frescos de ocupación.
+			prober.ForceSurvey()
 		case <-time.After(client.Delay(opts.Interval)):
 		}
 	}

+ 72 - 4
server-go/internal/adapters/live.go

@@ -240,6 +240,8 @@ type Live struct {
 	pool *SSHPool
 
 	mu         sync.Mutex
+	surveyMu   sync.Mutex
+	surveyRaw  map[string]surveyEntry
 	routers    []RouterConfig
 	gatewayCfg *RouterConfig
 	clients    map[string]*OpenWrtClient
@@ -4373,7 +4375,10 @@ func freqToBand(freq int) string {
 //
 // Cada bloque empieza con "Survey data from <dev>". Los valores están
 // tabulados y separados por ":". El "[in use]" marca el canal operativo.
-func parseIwSurvey(out string) map[string][]SurveyChannel {
+// ParseIwSurvey parsea la salida de `iw dev wlanX survey dump` (#1214):
+// exportada para que el httpapi pueda parsear el survey crudo que empuja el
+// agente en unidades agent-only.
+func ParseIwSurvey(out string) map[string][]SurveyChannel {
 	type rawChannel struct {
 		freq     int
 		inUse    bool
@@ -4452,6 +4457,59 @@ func parseIwSurvey(out string) map[string][]SurveyChannel {
 	return result
 }
 
+// surveyEntry: survey crudo del agente con su marca de tiempo (#1214).
+type surveyEntry struct {
+	raw string
+	at  time.Time
+}
+
+const agentSurveyTTL = 15 * time.Minute
+
+// StoreAgentSurvey guarda el texto crudo de `iw survey dump` que empuja un
+// agente (#1214): fuente de la lente "Ahora" en unidades agent-only sin SSH.
+// El httpapi lo llama en cada push que traiga surveyRaw.
+func (l *Live) StoreAgentSurvey(routerID, raw string) {
+	if raw == "" {
+		return
+	}
+	l.surveyMu.Lock()
+	if l.surveyRaw == nil {
+		l.surveyRaw = map[string]surveyEntry{}
+	}
+	l.surveyRaw[routerID] = surveyEntry{raw: raw, at: time.Now()}
+	l.surveyMu.Unlock()
+}
+
+// agentSurveyRadios parsea el survey crudo del agente si está fresco
+// (agentSurveyTTL); nil si no hay datos o caducaron.
+func (l *Live) agentSurveyRadios(routerID string) []SurveyRadio {
+	l.surveyMu.Lock()
+	e, ok := l.surveyRaw[routerID]
+	l.surveyMu.Unlock()
+	if !ok || time.Since(e.at) > agentSurveyTTL {
+		return nil
+	}
+	per := ParseIwSurvey(e.raw)
+	radios := []SurveyRadio{}
+	for dev, channels := range per {
+		if len(channels) == 0 {
+			continue
+		}
+		band := ""
+		for _, c := range channels {
+			if c.InUse {
+				band = freqToBand(c.Freq)
+				break
+			}
+		}
+		if band == "" {
+			band = freqToBand(channels[0].Freq)
+		}
+		radios = append(radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
+	}
+	return radios
+}
+
 // GetSurvey: utilización por canal wifi (iw survey dump) por router y radio.
 // Recorre los routers (saltando agent-only, que no tienen wifi) y hace SSH
 // `iw dev` para listar interfaces, luego `iw dev wlanX survey dump` por cada
@@ -4486,8 +4544,18 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 			name = cfg.ID
 		}
 		r := SurveyRouter{RouterID: cfg.ID, Name: name, Radios: []SurveyRadio{}}
-		// Agent-only y SNMP (#1026): unidades sin SSH; se listan sin radios.
-		if cfg.AgentOnly || cfg.SnmpEnabled {
+		// Agent-only y SNMP (#1026): unidades sin SSH. Las agent-only pueden
+		// traer survey vía push del agente (#1214); SNMP se lista sin radios.
+		if cfg.AgentOnly {
+			if radios := l.agentSurveyRadios(cfg.ID); len(radios) > 0 {
+				r.Available = true
+				r.Radios = radios
+				any = true
+			}
+			out.Routers = append(out.Routers, r)
+			continue
+		}
+		if cfg.SnmpEnabled {
 			out.Routers = append(out.Routers, r)
 			continue
 		}
@@ -4519,7 +4587,7 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 			if err != nil {
 				continue
 			}
-			channels := parseIwSurvey(surveyOut)[dev]
+			channels := ParseIwSurvey(surveyOut)[dev]
 			if len(channels) == 0 {
 				continue
 			}

+ 3 - 3
server-go/internal/adapters/survey_test.go

@@ -78,7 +78,7 @@ Survey data from wlan1
 	channel receive time:		0 ms
 	channel transmit time:		0 ms
 `
-	result := parseIwSurvey(out)
+	result := ParseIwSurvey(out)
 
 	if len(result) != 2 {
 		t.Fatalf("expected 2 devices, got %d: %v", len(result), result)
@@ -128,7 +128,7 @@ func TestParseIwSurveyEdge(t *testing.T) {
 	}
 	for name, in := range cases {
 		t.Run(name, func(t *testing.T) {
-			got := parseIwSurvey(in)
+			got := ParseIwSurvey(in)
 			if name == "only-header" {
 				// 1 device con 0 channels (no se hace flush sin campos).
 				if len(got["wlan0"]) != 0 {
@@ -150,7 +150,7 @@ func TestParseIwSurveyChannelNoActive(t *testing.T) {
 	frequency:			2412 MHz
 	noise:				-85 dBm
 `
-	result := parseIwSurvey(out)
+	result := ParseIwSurvey(out)
 	if len(result["wlan0"]) != 1 {
 		t.Fatalf("expected 1 channel, got %d", len(result["wlan0"]))
 	}

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

@@ -270,6 +270,14 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 			log.Printf("[netpulse] error guardando scans 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.
+	if p.Data.Wireless != nil && p.Data.Wireless.SurveyRaw != "" {
+		if st, ok := s.adapter.(interface{ StoreAgentSurvey(string, string) }); ok {
+			st.StoreAgentSurvey(p.Router, p.Data.Wireless.SurveyRaw)
+		}
+	}
 	// #401: si hay un upgrade en marcha y este push ya reporta la versión
 	// objetivo, el ciclo se cierra con el paso terminal "done" en vez de
 	// dejar el estado en "restarting" hasta el TTL.