Bladeren bron

feat(beacon): accept an optional LLDP neighbour section (#2184) (#2228)

Nacho 5 dagen geleden
bovenliggende
commit
e30ba8af17

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- A switch fed only by the Realtek beacon can report the LLDP neighbours it receives, as an optional `lldp` section in the datagram, so the topology gets the chassis name, the local port and the management address from the unit that really sees those frames. The section is bounded (64 neighbours, 128 characters per text field), an old build keeps working unchanged, and an absent section keeps the last known neighbours (#2184).
 - A rejected push says why. The server answered `unauthorized`, `invalid_signature` or `stale_payload` and kept only a timestamp, so the panel showed the same "token rejected" badge for a stale token, an agent older than the server and a unit whose clock is minutes off. The reason is stored next to the timestamp, returned by `/api/agents` as `rejectedReason`, shown in the badge tooltip with what to check, and quoted in the auto-rearm alert, which no longer says "restarted but did not come back" when the pushes never got in (#2211).
 
 ### Changed

+ 3 - 1
docs/AGENTE-RTL-SWITCH.md

@@ -16,7 +16,9 @@ Con un build reciente del beacon, NetPulse puede mostrar:
 - Tabla de reenvío MAC cada 300 segundos.
 - Versión de firmware, MAC de gestión y uptime cuando el build los incluye.
 
-El beacon no aporta CPU, RAM ni temperatura del switch. Tampoco transporta una tabla de vecinos LLDP. La emisión LLDP y el tratamiento RMA son funciones de configuración del switch documentadas en la guía del firmware.
+El beacon no aporta CPU, RAM ni temperatura del switch. La emisión LLDP y el tratamiento RMA son funciones de configuración del switch documentadas en la guía del firmware.
+
+Un build que recibe LLDP puede enviar además los vecinos aprendidos, como sección opcional `lldp` (#2184). Cada entrada lleva el número de boca local, el id de chasis o el nombre del sistema remoto, la primera dirección de gestión, las capacidades activas y la descripción del puerto remoto. La sección es opcional y acotada: 64 vecinos como máximo y 128 caracteres por campo de texto, así que cuesta unos 80 a 120 bytes por vecino en el datagrama. Un build sin la sección simplemente no la envía, y el servidor conserva entonces los últimos vecinos conocidos; una lista vacía significa que el switch no recibió nada, que no es lo mismo que no saberlo.
 
 Hoy un dispositivo alimentado por beacon no puede usar SNMP como segunda fuente en NetPulse. El SNMP opcional del firmware puede utilizarse de forma independiente, pero no añade otra fuente al mismo dispositivo de NetPulse.
 

+ 3 - 1
docs/RTL-SWITCH-BEACON.md

@@ -16,7 +16,9 @@ With a current beacon build, NetPulse can show:
 - The MAC forwarding table every 300 seconds.
 - Firmware version, management MAC and uptime when included by the build.
 
-The beacon does not provide CPU, RAM or switch temperature. It also does not carry an LLDP neighbour table. LLDP transmission and RMA handling are switch configuration features documented in the firmware guide.
+The beacon does not provide CPU, RAM or switch temperature. LLDP transmission and RMA handling are switch configuration features documented in the firmware guide.
+
+A build that receives LLDP can also send the neighbours it learned, as an optional `lldp` section (#2184). Each entry carries the local port number, the remote chassis id or system name, the first management address, the enabled capabilities and the remote port description. The section is optional and bounded: 64 neighbours at most and 128 characters per text field, so it costs roughly 80 to 120 bytes per neighbour in the datagram. A build without the section simply does not send it, and the server then keeps the last known neighbours; an empty list means the switch received nothing, which is a different thing from not knowing.
 
 A beacon-fed device cannot currently use SNMP as a second NetPulse source. Optional SNMP support in the firmware can be used independently, but it does not add another source to the same NetPulse device.
 

+ 90 - 0
server-go/internal/httpapi/beacon.go

@@ -23,6 +23,7 @@ import (
 	"log"
 	"net"
 	"sort"
+	"strings"
 	"time"
 
 	"github.com/gnacho/netpulse/agent/macaddr"
@@ -66,6 +67,85 @@ type beaconSFP struct {
 	TxP  float64 `json:"txp"`
 }
 
+// beaconLldp: un vecino LLDP recibido por el switch (#2184). El firmware lo
+// manda como lista opcional porque el 8051 paga cada byte: claves cortas y
+// campos que no se anuncian se omiten. El servidor lo traduce al contrato que
+// ya consumen el agente (`probe.LldpNeighbor`) y el adaptador SNMP, así que no
+// añade reglas nuevas a la topología.
+type beaconLldp struct {
+	P     int      `json:"p"`              // puerto local 1..32
+	Cmac  string   `json:"cmac,omitempty"` // id del chasis tipo MAC
+	Cname string   `json:"cn,omitempty"`   // system name del chasis
+	Mgmt  string   `json:"mgmt,omitempty"` // primera dirección de gestión
+	Caps  []string `json:"caps,omitempty"` // capacidades enabled
+	PD    string   `json:"pd,omitempty"`   // descripción del puerto remoto
+}
+
+// Límites de la sección LLDP: un datagrama llega de la red y el vecino es un
+// tercero, así que nada de lo que traiga puede crecer sin tope.
+const (
+	maxBeaconLldpNeighbors = 64
+	maxBeaconLldpRunes     = 128
+	maxBeaconLldpCaps      = 8
+)
+
+// beaconLldpData traduce la sección opcional al contrato compartido. nil =
+// sección ausente, y entonces el servidor conserva la última buena (mismo
+// anti-parpadeo que el resto de extras). Una entrada sin identidad (ni chasis
+// ni MAC) o con puerto imposible se descarta sin tirar el resto.
+func beaconLldpData(entries *[]beaconLldp) *probe.LldpData {
+	if entries == nil {
+		return nil
+	}
+	out := &probe.LldpData{Available: true, Neighbors: []probe.LldpNeighbor{}}
+	for _, e := range *entries {
+		if len(out.Neighbors) >= maxBeaconLldpNeighbors {
+			break
+		}
+		if e.P < 1 || e.P > 32 {
+			continue
+		}
+		n := probe.LldpNeighbor{
+			Port:       fmt.Sprintf("lan%d", e.P),
+			ChassisMac: macaddr.Normalize(e.Cmac),
+			Chassis:    beaconLldpText(e.Cname),
+			PortDesc:   beaconLldpText(e.PD),
+		}
+		if mgmt := beaconLldpText(e.Mgmt); net.ParseIP(mgmt) != nil {
+			n.Mgmt = mgmt
+		}
+		for _, c := range e.Caps {
+			if len(n.Caps) >= maxBeaconLldpCaps {
+				break
+			}
+			if c := beaconLldpText(c); c != "" {
+				n.Caps = append(n.Caps, c)
+			}
+		}
+		if n.Chassis == "" && n.ChassisMac == "" {
+			continue
+		}
+		out.Neighbors = append(out.Neighbors, n)
+	}
+	return out
+}
+
+// beaconLldpText limpia un texto del anuncio: sin caracteres de control, sin
+// espacios sobrantes y acotado en runas para no cortar un UTF-8 a la mitad.
+func beaconLldpText(s string) string {
+	s = strings.Map(func(r rune) rune {
+		if r < 0x20 || r == 0x7f {
+			return -1
+		}
+		return r
+	}, s)
+	s = strings.TrimSpace(s)
+	if r := []rune(s); len(r) > maxBeaconLldpRunes {
+		s = string(r[:maxBeaconLldpRunes])
+	}
+	return s
+}
+
 // beaconPacket: spec v1 del datagrama (una línea JSON ASCII, ~400 B).
 // Dev/Fw son opcionales: los lleva el ANUNCIO de descubrimiento (broadcast,
 // sin token) para que el switch pueda encontrarse antes del pareado.
@@ -95,6 +175,10 @@ type beaconPacket struct {
 	// SFP (#313): diagnóstico digital de bocas ópticas con DOM. Opcional;
 	// solo si el switch tiene módulos SFP. Por puerto (n = número de boca).
 	SFP []beaconSFP `json:"sfp,omitempty"`
+	// LLDP (#2184): vecinos recibidos por el switch. Puntero a propósito:
+	// ausente = build sin tabla LLDP (se conserva la última buena), [] =
+	// cero vecinos, que sí es un dato.
+	Lldp *[]beaconLldp `json:"lldp,omitempty"`
 }
 
 // beaconCandidate: un switch embebido anunciándose por broadcast SIN parar
@@ -277,6 +361,12 @@ func (s *server) ingestBeacon(src string, raw []byte) {
 		Interval: beaconIntervalSec,
 		Data:     probe.PayloadData{FDB: &probe.FDBData{MACs: macs, Ports: ports}},
 	}
+	// #2184: vecinos LLDP recibidos por el switch. Solo los lleva el
+	// datagrama de estado; el de FDB no los repite y el anti-parpadeo del
+	// consumidor conserva la última sección buena.
+	if ld := beaconLldpData(p.Lldp); ld != nil {
+		pl.Data.Lldp = ld
+	}
 	// #865: si el beacon trae fw/up/mac (spec 2026-09), son más frescos que
 	// el sondeo de consola y no necesitan login web, que con la sesión única
 	// del firmware le roba la sesión a quien esté usando la UI (#863).

+ 131 - 0
server-go/internal/httpapi/beacon_lldp_2184_test.go

@@ -0,0 +1,131 @@
+// beacon_lldp_2184_test.go — #2184: sección opcional de vecinos LLDP en el
+// beacon. Un switch alimentado por beacon es el único receptor de esos frames,
+// así que sin esta sección la topología pierde la única evidencia disponible.
+package httpapi
+
+import (
+	"fmt"
+	"strings"
+	"testing"
+)
+
+// La sección se traduce al contrato compartido: puerto local con prefijo lan,
+// chasis MAC en forma canónica, nombre recortado y capacidades acotadas.
+func TestBeaconLldpSectionFeedsPayload(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(`{"v":1,"seq":11,"slug":"switch16","token":"%s",`+
+		`"ports":[{"n":1,"l":3}],`+
+		`"lldp":[`+
+		`{"p":1,"cmac":"aa:bb:cc:dd:ee:01","cn":"pve-01","mgmt":"192.168.1.100","caps":["Bridge","Router"],"pd":"eth0"},`+
+		`{"p":3,"cmac":"AA-BB-CC-DD-EE-03","cn":" pve 03 ","caps":["Bridge"],"pd":"enp1s0"}]}`,
+		token))
+
+	p := waitFresh(t, s, "switch16")
+	if p.Data.Lldp == nil || !p.Data.Lldp.Available {
+		t.Fatalf("sección LLDP: %+v", p.Data.Lldp)
+	}
+	nbs := p.Data.Lldp.Neighbors
+	if len(nbs) != 2 {
+		t.Fatalf("vecinos: %d (%+v)", len(nbs), nbs)
+	}
+	if nbs[0].Port != "lan1" || nbs[0].ChassisMac != "AA:BB:CC:DD:EE:01" ||
+		nbs[0].Chassis != "pve-01" || nbs[0].Mgmt != "192.168.1.100" ||
+		nbs[0].PortDesc != "eth0" || len(nbs[0].Caps) != 2 {
+		t.Fatalf("vecino 1: %+v", nbs[0])
+	}
+	if nbs[1].Port != "lan3" || nbs[1].ChassisMac != "AA:BB:CC:DD:EE:03" || nbs[1].Chassis != "pve 03" {
+		t.Fatalf("vecino 2: %+v", nbs[1])
+	}
+}
+
+// Sin la sección el payload queda como hoy: el servidor conserva la última
+// sección buena en vez de inventar cero vecinos.
+func TestBeaconWithoutLldpSectionKeepsPayloadShape(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":12,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3}]}`, token))
+
+	p := waitFresh(t, s, "switch16")
+	if p.Data.Lldp != nil {
+		t.Fatalf("un beacon sin sección no puede inventar LLDP: %+v", p.Data.Lldp)
+	}
+}
+
+// Una lista vacía sí es un dato: cero vecinos, distinto de "no lo sé".
+func TestBeaconEmptyLldpSectionIsHonestZero(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":13,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3}],"lldp":[]}`, token))
+
+	p := waitFresh(t, s, "switch16")
+	if p.Data.Lldp == nil || !p.Data.Lldp.Available {
+		t.Fatalf("sección vacía: %+v", p.Data.Lldp)
+	}
+	if p.Data.Lldp.Neighbors == nil || len(p.Data.Lldp.Neighbors) != 0 {
+		t.Fatalf("vecinos de una sección vacía: %+v", p.Data.Lldp.Neighbors)
+	}
+}
+
+// Entradas imposibles o sin identidad se descartan una a una sin tirar el
+// resto del datagrama, y los textos se acotan.
+func TestBeaconLldpSkipsBadEntriesKeepsGoodOnes(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	long := strings.Repeat("x", 300)
+	sendUDP(t, addr, fmt.Sprintf(`{"v":1,"seq":14,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3}],`+
+		`"lldp":[`+
+		`{"p":0,"cn":"puerto cero"},`+
+		`{"p":99,"cn":"puerto fuera"},`+
+		`{"p":2},`+
+		`{"p":2,"cmac":"no-es-mac","cn":""},`+
+		`{"p":2,"cmac":"AA:BB:CC:DD:EE:02","cn":"switch\u0001central","mgmt":"no-ip"},`+
+		`{"p":4,"cmac":"AA:BB:CC:DD:EE:04","cn":"%s"}]}`, token, long))
+
+	p := waitFresh(t, s, "switch16")
+	nbs := p.Data.Lldp.Neighbors
+	if len(nbs) != 2 {
+		t.Fatalf("vecinos válidos: %d (%+v)", len(nbs), nbs)
+	}
+	if nbs[0].Port != "lan2" || nbs[0].Chassis != "switchcentral" || nbs[0].Mgmt != "" {
+		t.Fatalf("vecino saneado: %+v", nbs[0])
+	}
+	if got := len([]rune(nbs[1].Chassis)); got != maxBeaconLldpRunes {
+		t.Fatalf("nombre sin acotar: %d runas", got)
+	}
+}
+
+// El tope de vecinos evita que un datagrama grande se convierta en estado
+// ilimitado en memoria y en la API.
+func TestBeaconLldpCapsNeighbourCount(t *testing.T) {
+	entries := make([]beaconLldp, 0, maxBeaconLldpNeighbors+10)
+	for i := 0; i < maxBeaconLldpNeighbors+10; i++ {
+		entries = append(entries, beaconLldp{P: i%32 + 1, Cname: "n"})
+	}
+	ld := beaconLldpData(&entries)
+	if ld == nil || len(ld.Neighbors) != maxBeaconLldpNeighbors {
+		t.Fatalf("tope de vecinos: %d", len(ld.Neighbors))
+	}
+}