Explorar o código

feat(agent): lldpd physical-port binding at install + bridge-only hint (#1369) (#1392)

On OpenWrt (verified qualcommax/ipq807x nss-dp; DSA likely affected too)
an lldpd bound to the bridge (the stock br-lan config) reports zero
neighbors forever: LLDP frames never reach a listener on the bridge
master, and topology silently falls back to FDB inference.

- install-agent.sh: when lldpd is already installed, ensure it listens on
  physical ports (lan*,wan via UCI) and restart it. Idempotent: a binding
  with physical ports is left untouched; lldpd itself is never installed
  by the script (installing packages stays the admin's call).
- Agent probe: with an honest zero-neighbor round plus a bridge-only UCI
  binding, the payload carries lldp.hint=lldpd-bridge-only. UCI is only
  queried on empty rounds (no extra fork when neighbors exist).
- Server propagates it as router.lldpHint; RouterDetail shows a warning
  banner with the exact fix (i18n es/en).
- Docs: binding requirement next to the agent LLDP section.

Closes #1369
Nacho hai 1 mes
pai
achega
53b001b110

+ 33 - 0
agent/probe/lldp.go

@@ -23,6 +23,18 @@ const CmdLldpCheck = "command -v lldpcli"
 // CmdLldpNeighbors: vecinos LLDP en JSON (lldpd). Igual que la sonda SSH.
 const CmdLldpNeighbors = "lldpcli -f json show neighbors"
 
+// CmdLldpdIfaces: binding de lldpd en OpenWrt (UCI). Vacío si no hay UCI
+// (Linux genérico) o la opción no existe (lldpd escucha en todas las
+// físicas por defecto). Solo se consulta cuando hay 0 vecinos (#1369).
+const CmdLldpdIfaces = "uci -q get lldpd.config.interface 2>/dev/null || true"
+
+// HintLldpdBridgeOnly: valor de LldpData.Hint cuando lldpd está instalado,
+// reporta 0 vecinos y su binding UCI es SOLO a interfaces bridge (br-*):
+// en varios targets (qualcommax nss-dp verificado; DSA probable) los frames
+// LLDP nunca suben al listener del bridge master y lldpd no ve a nadie sin
+// avisar (#1369). La UI lo traduce a "configura lldpd en puertos físicos".
+const HintLldpdBridgeOnly = "lldpd-bridge-only"
+
 // LldpData: sección lldp del payload del agente (#489).
 type LldpData struct {
 	// Available: false cuando lldpd no está instalado en el equipo.
@@ -32,6 +44,27 @@ type LldpData struct {
 	// SIN omitempty a propósito: hay que distinguir nil de vacío en el
 	// wire format.
 	Neighbors []LldpNeighbor `json:"neighbors"`
+	// Hint: aviso de configuración subóptima detectada (p. ej.
+	// HintLldpdBridgeOnly). Código estable, la UI lo traduce (i18n).
+	Hint string `json:"hint,omitempty"`
+}
+
+// LldpdBridgeOnly: true si el binding UCI de lldpd (CSV de patrones, p. ej.
+// "br-lan" o "lan*,wan") nombra SOLO interfaces bridge. Vacío (sin opción:
+// lldpd escucha en todas las físicas) o cualquier patrón físico → false.
+func LldpdBridgeOnly(ifaces string) bool {
+	any := false
+	for _, tok := range strings.Split(ifaces, ",") {
+		tok = strings.TrimSpace(tok)
+		if tok == "" {
+			continue
+		}
+		any = true
+		if !strings.HasPrefix(tok, "br-") {
+			return false
+		}
+	}
+	return any
 }
 
 // LldpNeighbor: un vecino LLDP anunciado en un puerto local. Todos los

+ 23 - 0
agent/probe/lldp_test.go

@@ -289,3 +289,26 @@ func TestPayloadLldpWire(t *testing.T) {
 		t.Fatalf("wire vacío honesto: %s", s)
 	}
 }
+
+// #1369: el hint bridge-only sale solo cuando el binding UCI es SOLO bridge.
+func TestLldpdBridgeOnly(t *testing.T) {
+	cases := []struct {
+		ifaces string
+		want   bool
+	}{
+		{"", false},                    // sin opción UCI: lldpd escucha en físicas
+		{"br-lan", true},               // el caso del issue (stock qualcommax)
+		{"br-lan,br-guest", true},      // varios bridges: igual de ciego
+		{"lan*,wan", false},            // el fix aplicado en la flota
+		{"lan1", false},                // puerto físico suelto
+		{"br-lan,lan1", false},         // mixto: ya escucha en físicas
+		{" lan1 , wan ", false},        // espacios tolerados
+		{"eth0", false},                // Linux genérico con nombre eth
+		{",,,", false},                 // tokens vacíos: sin binding efectivo
+	}
+	for _, c := range cases {
+		if got := LldpdBridgeOnly(c.ifaces); got != c.want {
+			t.Errorf("LldpdBridgeOnly(%q) = %v, want %v", c.ifaces, got, c.want)
+		}
+	}
+}

+ 9 - 1
agent/probe/local.go

@@ -630,7 +630,15 @@ func (p *Prober) probeLldp(ctx context.Context) *LldpData {
 	if err != nil {
 		return &LldpData{Available: true}
 	}
-	return &LldpData{Available: true, Neighbors: neighbors}
+	d := &LldpData{Available: true, Neighbors: neighbors}
+	// #1369: 0 vecinos honestos + binding SOLO a bridge (br-lan) = el caso
+	// silencioso de OpenWrt (los frames LLDP no suben al bridge master en
+	// nss-dp/DSA). Solo entonces consultamos UCI (un fork extra por ronda
+	// cuando sí hay vecinos sería desperdicio).
+	if len(neighbors) == 0 && LldpdBridgeOnly(p.runBest(ctx, CmdLldpdIfaces, 0)) {
+		d.Hint = HintLldpdBridgeOnly
+	}
+	return d
 }
 
 // probeClientBw: contadores por MAC de nlbwmon (#551). Contrato: Available=

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

@@ -861,6 +861,8 @@
     "hostKeyConfirm": "Confirm new key",
     "hostKeyBusy": "Confirming…",
     "hostKeyDone": "Key accepted: reconnecting…",
+    "lldpBridgeOnlyTitle": "lldpd sees no neighbors: it listens on the bridge only",
+    "lldpBridgeOnlyBody": "lldpd is installed but bound to br-lan, and on this hardware LLDP frames never reach the bridge master: topology loses its direct evidence silently. Fix it with: uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart",
     "perf": {
       "chartAria": "{{label}} of {{name}}, range {{range}}. Current value {{value}} {{unit}}.",
       "maxTemp": "max {{temp}}",

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

@@ -861,6 +861,8 @@
     "hostKeyConfirm": "Confirmar nueva clave",
     "hostKeyBusy": "Confirmando…",
     "hostKeyDone": "Clave aceptada: reconectando…",
+    "lldpBridgeOnlyTitle": "lldpd no ve vecinos: escucha solo en el bridge",
+    "lldpBridgeOnlyBody": "lldpd está instalado pero configurado para escuchar en br-lan, y en este hardware los mensajes LLDP no llegan al bridge: la topología se queda sin evidencia directa. Arréglalo con: uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart",
     "perf": {
       "chartAria": "{{label}} de {{name}}, rango {{range}}. Valor actual {{value}} {{unit}}.",
       "maxTemp": "máx {{temp}}",

+ 6 - 0
app/src/data/types.ts

@@ -91,6 +91,12 @@ export interface Router {
    * sondea (agent-only/external/SNMP): la tabla de enlaces pinta "—".
    */
   latencyMs?: number
+  /**
+   * #1369: aviso de config subóptima del lldpd del router, reportado por el
+   * agente. Código estable ("lldpd-bridge-only"); se traduce en la UI.
+   * Ausente = sin aviso.
+   */
+  lldpHint?: string
 }
 
 export interface WanInfo {

+ 19 - 0
app/src/pages/RouterDetail.tsx

@@ -147,6 +147,25 @@ export default function RouterDetail() {
         </motion.div>
       )}
 
+      {/* #1369: lldpd escuchando solo en el bridge (br-lan) → 0 vecinos LLDP
+          silencioso en nss-dp/DSA. El agente lo detecta y avisa aquí. */}
+      {router.lldpHint === 'lldpd-bridge-only' && (
+        <motion.div
+          initial={reduce ? false : { opacity: 0, y: -8 }}
+          animate={{ opacity: 1, y: 0 }}
+          transition={{ duration: 0.3, ease: 'easeOut', delay: 0.38 }}
+          className="lg:col-span-12"
+        >
+          <div role="alert" className="flex items-start gap-3 rounded-2xl border border-warn/50 bg-warn/10 px-5 py-4">
+            <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-warn" strokeWidth={1.75} />
+            <div className="min-w-0 flex-1">
+              <div className="text-sm font-semibold text-warn">{t('routerDetail.lldpBridgeOnlyTitle')}</div>
+              <p className="mt-0.5 text-sm text-text-secondary">{t('routerDetail.lldpBridgeOnlyBody')}</p>
+            </div>
+          </div>
+        </motion.div>
+      )}
+
       {/* Banner contextual (Patio) */}
       {router.status === 'warn' && router.hotMetric === 'temp' && (
         <motion.div

+ 24 - 0
docs/AGENTE-OPENWRT.md

@@ -117,6 +117,30 @@ push, escalado y resultado), para poder seguir la recuperación sin mirar
 código. Los agentes NetGrip embebidos y los rearmes manuales desde la UI
 siguen el mismo camino y también quedan registrados.
 
+## lldpd en puertos físicos (#1369)
+
+La sonda LLDP del agente lee vecinos de `lldpd`. OJO con el binding: en
+varios targets (qualcommax nss-dp verificado; DSA probable) un lldpd bound
+al bridge (`lldpd.config.interface='br-lan'`, config típica tras un
+`opkg install lldpd` stock) reporta CERO vecinos para siempre - los frames
+LLDP (01:80:c2:00:00:0e) no llegan al listener del bridge master y no hay
+aviso en ningún sitio. La topología cae a inferencia FDB en silencio.
+
+Fix: escuchar en los puertos físicos:
+
+```sh
+uci set lldpd.config.interface='lan*,wan'
+uci commit lldpd
+/etc/init.d/lldpd restart
+```
+
+`install-agent.sh` lo deja así automáticamente cuando lldpd ya está
+instalado (idempotente: un binding con puertos físicos no se toca; no
+instala lldpd por sí solo). Cuando el agente detecta el caso (0 vecinos
+honestos + binding solo bridge) lo reporta en el payload como
+`lldp.hint="lldpd-bridge-only"` y la UI muestra un aviso en la ficha del
+router. TX (anunciarse) funciona en ambas configs; solo RX está afectado.
+
 ## Qué NO es el agente
 
 - No es obligatorio: NetPulse sigue funcionando 100% en Tier 0 (SSH) +

+ 22 - 0
install-agent.sh

@@ -465,6 +465,28 @@ fi
 ssh $SSH_IDENT_ARGS "$SSH" "chmod 0755 $INIT_DST && $INIT_DST enable && $INIT_DST restart"
 ok "servicio $INIT_NAME habilitado y arrancado"
 
+# ------------------------------------------------- lldpd en puertos físicos (#1369) --
+# lldpd bound al bridge (br-lan) no recibe vecinos en varios targets
+# (qualcommax nss-dp verificado; DSA probable): los frames LLDP nunca suben
+# al listener del bridge master y la topología queda sin evidencia directa
+# sin avisar. Si lldpd está instalado y su binding es SOLO bridge, lo pasamos
+# a los puertos físicos (patrón OpenWrt estándar). Idempotente: un binding
+# que ya incluye puertos físicos (lan*/wan/eth*) no se toca. NO instalamos
+# lldpd aquí: instalar paquetes es decisión del usuario (el agente detecta
+# lldpd solo si ya está).
+if ssh $SSH_IDENT_ARGS "$SSH" "command -v lldpcli >/dev/null 2>&1"; then
+    LLDP_IF=$(ssh $SSH_IDENT_ARGS "$SSH" "uci -q get lldpd.config.interface 2>/dev/null")
+    if printf '%s' "$LLDP_IF" | grep -qE '(^|,)[[:space:]]*(lan|wan|eth)'; then
+        ok "lldpd ya escucha en puertos físicos (${LLDP_IF:-auto})"
+    else
+        ssh $SSH_IDENT_ARGS "$SSH" "uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart >/dev/null 2>&1" \
+            && ok "lldpd reconfigurado: escucha en puertos físicos (lan*,wan)${LLDP_IF:+ - antes: $LLDP_IF}" \
+            || warn "no se pudo reconfigurar lldpd; a mano: uci set lldpd.config.interface='lan*,wan' && uci commit lldpd && /etc/init.d/lldpd restart"
+    fi
+else
+    info "lldpd no instalado: sin evidencia LLDP directa (con 'opkg install lldpd' la activas; reejecuta este instalador y lo deja en puertos físicos)"
+fi
+
 # Watchdog cron: NO se instala (#851). Si el agente crashea en bucle, un
 # reinicio a ciegas cada 2 min no lo arregla y ensucia el log; la detección
 # efectiva es el dead-man del servidor (alerta) y el crash puntual lo cubre

+ 5 - 5
server-go/internal/adapters/agent.go

@@ -735,7 +735,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	// fallida (Available=true con Neighbors nil) o ausente (push
 	// event-driven) recicla la última cacheada. Available=false explícito =
 	// lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
-	resolveLldp := func() (nbs []LldpNeighbor, unavailable bool) {
+	resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
 		ld := p.Data.Lldp
 		if ld == nil || (ld.Available && ld.Neighbors == nil) {
 			ld = nil
@@ -744,14 +744,14 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 			}
 		}
 		if ld == nil {
-			return nil, false
+			return nil, false, ""
 		}
 		if !ld.Available {
-			return nil, true
+			return nil, true, ""
 		}
-		return lldpFromProbe(ld.Neighbors), false
+		return lldpFromProbe(ld.Neighbors), false, ld.Hint
 	}
-	out.lldp, out.lldpUnavailable = resolveLldp()
+	out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
 	// ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
 	// LLDP: la sección buena del payload manda; una sección fallida
 	// (Available=true con Hosts nil) o ausente (push event-driven) recicla

+ 7 - 0
server-go/internal/adapters/live.go

@@ -141,6 +141,10 @@ type routerPolled struct {
 	// lldpUnavailable: lldpd no está instalado en este router (issue #247) →
 	// el view-model expone `lldpAvailable:false` para el hint de instalación.
 	lldpUnavailable bool
+	// lldpHint: aviso de config subóptima reportado por el agente (#1369,
+	// p. ej. probe.HintLldpdBridgeOnly). Se recicla con la cache igual que
+	// los vecinos; vacío = sin aviso.
+	lldpHint string
 	// clientBw (#551): contadores nlbwmon por MAC del último payload del
 	// agente. nil = nlbwmon no instalado o sonda no disponible (→ la fuente
 	// de tráfico por cliente cae a hostapd bytes de wireless).
@@ -1381,6 +1385,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.lldpUnavailable {
 		r.LldpAvailable = bptr(false)
 	}
+	if p.lldpHint != "" {
+		r.LldpHint = p.lldpHint
+	}
 	if p.board != nil {
 		r.Firmware = p.board.Release.Description
 	}

+ 4 - 0
server-go/internal/adapters/types.go

@@ -226,6 +226,10 @@ type Router struct {
 	// UI muestra el hint "instala lldpd" para identificar switches gestionados
 	// (issue #247). Nunca emite true (ausente = OK).
 	LldpAvailable *bool `json:"lldpAvailable,omitempty"`
+	// LldpHint: aviso de config subóptima del lldpd del router, reportado por
+	// el agente (#1369). Código estable (p. ej. "lldpd-bridge-only"); la UI
+	// lo traduce. Ausente = sin aviso.
+	LldpHint string `json:"lldpHint,omitempty"`
 }
 
 // DeviceTotals del overview (quirk: NewToday=0 en live).