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

fix(snmp): try qbridge FDB when dot1d yields no usable entries (#948) (#949)

The qbridge fallback in PollFdbTable only fired when the dot1dTpFdbPort
walk returned zero raw PDUs. Switches whose dot1d walk returns data that
does not parse into usable entries never got the qbridge table tried, and
the log showed "0 entradas (fuente dot1d)" with no clients despite a
populated qbridge table.

- fall back to dot1q whenever dot1d produces no usable entries
- return raw walk PDU counts (FdbPoll) so the FDB log line shows raw vs
  parsed, making remote diagnosis one round-trip shorter
- keep the #928 error semantics: real error when both walks fail
- unit tests for fdbEntries (dot1d/dot1q parse + unusable PDU skips)
Nacho 2 месяцев назад
Родитель
Сommit
1a1d53287d

+ 5 - 3
server-go/internal/adapters/snmp_live.go

@@ -50,20 +50,22 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 	if ifErr != nil {
 		log.Printf("[netpulse] SNMP ifTable %s: %v", cfg.ID, ifErr)
 	}
-	fdb, fdbSource, fdbErr := npsnmp.PollFdbTable(session)
+	fdbPoll, fdbErr := npsnmp.PollFdbTable(session)
+	fdb := fdbPoll.Entries
 	if fdbErr != nil {
 		log.Printf("[netpulse] SNMP FDB %s: %v", cfg.ID, fdbErr)
 	} else {
 		// #928: visibilidad mínima del resultado del FDB. Se loguea cuando el
 		// conteo cambia respecto al ciclo anterior (o en el primer poll), no
 		// cada 60 s: suficiente para diagnosticar "walk vacío/fallido" sin
-		// inundar el journal.
+		// inundar el journal. #948: la línea lleva además los PDUs crudos de
+		// cada walk para distinguir "tabla vacía" de "datos no utilizables".
 		l.mu.Lock()
 		last, seen := l.snmpFdbCount[cfg.ID]
 		l.snmpFdbCount[cfg.ID] = len(fdb)
 		l.mu.Unlock()
 		if !seen || last != len(fdb) {
-			log.Printf("[netpulse] SNMP FDB %s: %d entradas (fuente %s)", cfg.ID, len(fdb), fdbSource)
+			log.Printf("[netpulse] SNMP FDB %s: %d entradas (fuente %s; pdus dot1d=%d dot1q=%d)", cfg.ID, len(fdb), fdbPoll.Source, fdbPoll.RawDot1d, fdbPoll.RawDot1q)
 		}
 	}
 

+ 61 - 27
server-go/internal/snmp/fdbTable.go

@@ -13,12 +13,24 @@ type FdbEntry struct {
 	IfIndex        int
 }
 
-// PollFdbTable devuelve las entradas del FDB, la fuente usada ("dot1d" o
-// "dot1q") y el error. #928: antes el error del fallback dot1q se tragaba y
-// un fallo de ambos walks devolvía (vacío, nil): el caller no podía
-// distinguir "switch sin clientes" de "walk fallido", y el usuario veía 0
-// clientes sin ningún rastro en el log.
-func PollFdbTable(s *gosnmp.GoSNMP) ([]FdbEntry, string, error) {
+// FdbPoll es el resultado de sondear el FDB de un switch. Además de las
+// entradas y la fuente usada, lleva los conteos de PDUs crudos de cada walk
+// para que el log pueda distinguir "walk vacío" de "walk con datos no
+// utilizables" en diagnosis remotas (#948).
+type FdbPoll struct {
+	Entries  []FdbEntry
+	Source   string // "dot1d" o "dot1q"
+	RawDot1d int    // PDUs crudos devueltos por el walk dot1d
+	RawDot1q int    // PDUs crudos devueltos por el walk dot1q (0 si no se intentó)
+}
+
+// PollFdbTable sondea el FDB del switch. #928: antes el error del fallback
+// dot1q se tragaba y un fallo de ambos walks devolvía (vacío, nil): el caller
+// no podía distinguir "switch sin clientes" de "walk fallido". #948: el
+// fallback a dot1q no depende ya de que el walk dot1d devuelva cero PDUs,
+// sino de que no produzca ninguna entrada utilizable; un walk dot1d con datos
+// que no parsean ya no impide probar la tabla Q-BRIDGE.
+func PollFdbTable(s *gosnmp.GoSNMP) (FdbPoll, error) {
 	portToIfIndex := map[int]int{}
 	pdus, err := walkSafe(s, OidDot1dBasePortIfIndex)
 	if err == nil {
@@ -33,20 +45,52 @@ func PollFdbTable(s *gosnmp.GoSNMP) ([]FdbEntry, string, error) {
 
 	// Fuente del FDB: dot1d (RFC 1493) es la estándar, pero algunos switches
 	// gestionados solo exponen la tabla Q-BRIDGE (dot1q, RFC 4363) → fallback
-	// cuando la dot1d no devuelve entradas (#661).
-	fdbPdus, errD1 := walkSafe(s, OidDot1dTpFdbPort)
-	useDot1q := len(fdbPdus) == 0
-	source := "dot1d"
-	var errQ error
-	if useDot1q {
-		source = "dot1q"
-		fdbPdus, errQ = walkSafe(s, OidDot1qTpFdbPort)
+	// cuando la dot1d no produce entradas utilizables (#661, #948).
+	d1Pdus, errD1 := walkSafe(s, OidDot1dTpFdbPort)
+	res := FdbPoll{Source: "dot1d", RawDot1d: len(d1Pdus)}
+	res.Entries = fdbEntries(portToIfIndex, d1Pdus, false)
+	if len(res.Entries) > 0 {
+		return res, nil
+	}
+
+	qPdus, errQ := walkSafe(s, OidDot1qTpFdbPort)
+	res.RawDot1q = len(qPdus)
+	res.Entries = fdbEntries(portToIfIndex, qPdus, true)
+	if len(res.Entries) > 0 {
+		res.Source = "dot1q"
+		return res, nil
+	}
+
+	// Sin entradas de ninguna tabla: distinguir "FDB genuinamente vacío" de
+	// "walk fallido" devolviendo el error real para que el caller lo registre
+	// (#928). walkSafe devuelve (nil, err) en fallo, así que un error implica
+	// que ese walk no produjo nada.
+	res.Source = "dot1q"
+	if errD1 != nil {
+		res.Source = "dot1d"
+	}
+	switch {
+	case errD1 != nil && errQ != nil:
+		return res, fmt.Errorf("snmp fdb walk: dot1d: %v; dot1q: %w", errD1, errQ)
+	case errD1 != nil:
+		return res, fmt.Errorf("snmp fdb walk: %w", errD1)
+	case errQ != nil:
+		return res, fmt.Errorf("snmp fdb walk: dot1q: %w", errQ)
 	}
+	// Ambos walks respondieron pero no hay entradas utilizables: FDB vacío de
+	// verdad (o datos que no parsean; los conteos Raw lo delatan en el log).
+	res.Source = "dot1d"
+	return res, nil
+}
 
+// fdbEntries convierte los PDUs crudos de un walk FDB en entradas. Es pura
+// para probarla sin agente SNMP. dot1q indica que el índice es compuesto
+// (<vlan>.M.M.M.M.M.M) y la MAC son los últimos 6 octetos.
+func fdbEntries(portToIfIndex map[int]int, pdus []gosnmp.SnmpPDU, dot1q bool) []FdbEntry {
 	var out []FdbEntry
-	for _, pdu := range fdbPdus {
+	for _, pdu := range pdus {
 		var mac string
-		if useDot1q {
+		if dot1q {
 			mac = extractMacFromOidLast6(pdu.Name, OidDot1qTpFdbPort)
 		} else {
 			mac = extractMacFromOid(pdu.Name, OidDot1dTpFdbPort)
@@ -68,17 +112,7 @@ func PollFdbTable(s *gosnmp.GoSNMP) ([]FdbEntry, string, error) {
 			IfIndex:         ifIdx,
 		})
 	}
-	if len(out) == 0 {
-		// Distinguir "FDB genuinamente vacío" de "walk fallido": en el segundo
-		// caso devolvemos el error para que el caller lo registre (#928).
-		switch {
-		case useDot1q && errQ != nil:
-			return nil, source, fmt.Errorf("snmp fdb walk: dot1d: %v; dot1q: %w", errD1, errQ)
-		case !useDot1q && errD1 != nil:
-			return nil, source, fmt.Errorf("snmp fdb walk: %w", errD1)
-		}
-	}
-	return out, source, nil
+	return out
 }
 
 func extractMacFromOid(name, prefix string) string {

+ 68 - 0
server-go/internal/snmp/fdbTable_test.go

@@ -0,0 +1,68 @@
+package snmp
+
+import (
+	"testing"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+func fdbPdu(name string, port uint) gosnmp.SnmpPDU {
+	return gosnmp.SnmpPDU{Name: name, Type: gosnmp.Integer, Value: port}
+}
+
+// #948: el walk dot1d puede devolver PDUs que no producen ninguna entrada
+// utilizable (p.ej. el propio OID de la columna sin instancia, o índices con
+// un número de octetos distinto de 6). fdbEntries debe descartarlos sin
+// inventar entradas.
+func TestFdbEntriesDot1dSkipsUnusablePdus(t *testing.T) {
+	portMap := map[int]int{3: 103}
+	pdus := []gosnmp.SnmpPDU{
+		// OID de la columna sin índice (caso leaf del fallback GetRequest de gosnmp).
+		fdbPdu(OidDot1dTpFdbPort, 3),
+		// Índice de 5 octetos: no es una MAC.
+		fdbPdu(OidDot1dTpFdbPort+".1.2.3.4.5", 3),
+		// Octeto fuera de rango.
+		fdbPdu(OidDot1dTpFdbPort+".1.2.3.4.5.999", 3),
+		// Prefijo distinto (otra columna de la tabla).
+		fdbPdu(".1.3.6.1.2.1.17.4.3.1.3.1.2.3.4.5.6", 3),
+	}
+	if got := fdbEntries(portMap, pdus, false); len(got) != 0 {
+		t.Fatalf("esperaba 0 entradas, obtuve %d: %+v", len(got), got)
+	}
+}
+
+func TestFdbEntriesDot1d(t *testing.T) {
+	portMap := map[int]int{3: 103}
+	pdus := []gosnmp.SnmpPDU{
+		fdbPdu(OidDot1dTpFdbPort+".140.22.24.187.30.12", 3),
+		// bridgePort sin mapeo a ifIndex: cae al propio bridgePort (#661).
+		fdbPdu(OidDot1dTpFdbPort+".0.12.34.56.78.90", 7),
+	}
+	got := fdbEntries(portMap, pdus, false)
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 entradas, obtuve %d: %+v", len(got), got)
+	}
+	if got[0].MAC != "8c:16:18:bb:1e:0c" || got[0].BridgePortIndex != 3 || got[0].IfIndex != 103 {
+		t.Errorf("entrada 0 inesperada: %+v", got[0])
+	}
+	if got[1].MAC != "00:0c:22:38:4e:5a" || got[1].BridgePortIndex != 7 || got[1].IfIndex != 7 {
+		t.Errorf("entrada 1 inesperada: %+v", got[1])
+	}
+}
+
+func TestFdbEntriesDot1q(t *testing.T) {
+	portMap := map[int]int{5: 205}
+	pdus := []gosnmp.SnmpPDU{
+		// Índice compuesto <vlan>.M.M.M.M.M.M: la MAC son los últimos 6 octetos.
+		fdbPdu(OidDot1qTpFdbPort+".100.140.22.24.187.30.12", 5),
+		// Prefijo distinto: descartado.
+		fdbPdu(".1.3.6.1.2.1.17.7.1.2.2.1.3.100.140.22.24.187.30.12", 5),
+	}
+	got := fdbEntries(portMap, pdus, true)
+	if len(got) != 1 {
+		t.Fatalf("esperaba 1 entrada, obtuve %d: %+v", len(got), got)
+	}
+	if got[0].MAC != "8c:16:18:bb:1e:0c" || got[0].BridgePortIndex != 5 || got[0].IfIndex != 205 {
+		t.Errorf("entrada inesperada: %+v", got[0])
+	}
+}