Selaa lähdekoodia

feat(routers): merge the SNMP port surface into pusher polls (#1753)

Closes #1726

A unit can have `snmp_enabled` and also be fed by a pusher. `pollRouter` returns as soon as there is a fresh agent payload, so the SNMP branch never ran and the setting was a silent no-op.

This adds SNMP as a second source in that path. It only fills what the payload cannot provide:

- link speed per port (RouterOS does not expose it through the API, and the child switch reports `ifHighSpeed=0` in up ports)
- error counters (`ifErrors`/`ifInErrors`, only available over SNMP)
- LLDP neighbours (RouterOS 7.25 has no `/interface/lldp` menu), which replaces the FDB guess that labels `sfp-sfpplus1` as the wrong peer

What it does not touch: CPU, RAM and temperature (the payload wins since #1724) and the FDB (the agent already sends it). A payload value is never overwritten: the merge only fills empty speeds and zero counters, and an `ifHighSpeed=0` from a down port is not propagated as a speed.

The SNMP surface is cached per router with the same interval as the SNMP poller (`snmp_poll_interval`, 60 s by default), so a 30 s pusher does not turn into two SNMP walks per minute. It reuses `recordSnmpSuccess` and `recordSnmpFailure`, so the existing "SNMP polling failing" alert still fires on these units. It skips `recordPortSamples` and `portMon.Observe` on purpose: the pusher already persists its own series with its own port IDs, and duplicating them here would interleave `snmp-N` rows with the real ones.

Five tests cover the merge rules, the down-link case, payload priority for LLDP, the fresh-cache path (no second walk) and the disabled case.
Nacho 1 kuukausi sitten
vanhempi
sitoutus
792bb12af3

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

@@ -304,6 +304,10 @@ type Live struct {
 	snmpPorts map[string]map[string]snmpPortSample
 	// snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
 	snmpLastPoll map[string]time.Time
+	// snmpSurface (#1726): última superficie leída por SNMP (velocidad de
+	// boca, errores y LLDP) de las unidades que además van por pusher, para
+	// no sondear SNMP en cada push. Protegido por mu.
+	snmpSurface map[string]snmpSurfaceEntry
 	// fwAlert (#1411): estado de la alerta de firmware por unidad con target
 	// configurado: qué relación se alertó y contra qué versiones. Con eso la
 	// alerta es un episodio por unidad (se abre una vez, se actualiza solo si
@@ -522,6 +526,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		snmpLastPoll:         map[string]time.Time{},
+		snmpSurface:          map[string]snmpSurfaceEntry{},
 		snmpFdbCount:         map[string]int{},
 		snmpBrMac:            map[string]string{},
 		snmpPollStats:        map[string]*snmpPollStat{},
@@ -1182,6 +1187,10 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		if gw != nil && cfg.ID == gw.ID && client != nil && !hasWan {
 			p.wanInfo = l.probeWanInfo(cfg.ID, client)
 		}
+		// #1726: si la unidad también tiene SNMP configurado, completar con
+		// SNMP lo que el payload no puede dar (velocidad de boca, errores,
+		// LLDP). Sin esto el ajuste era un no-op silencioso.
+		l.mergeSNMPSurface(cfg, p)
 		return p, nil
 	}
 	if cfg.SnmpEnabled {

+ 162 - 0
server-go/internal/adapters/snmp_merge.go

@@ -0,0 +1,162 @@
+package adapters
+
+import (
+	"fmt"
+	"log"
+	"strings"
+	"time"
+
+	npsnmp "github.com/gnacho/netpulse/server-go/internal/snmp"
+)
+
+// snmpSurfaceEntry (#1726): lo que SNMP sabe de una unidad y el payload del
+// pusher no. Se cachea por router para no sondear SNMP en cada push.
+type snmpSurfaceEntry struct {
+	at      time.Time
+	byIface map[string]EthPort
+	lldp    []LldpNeighbor
+	ok      bool
+}
+
+// mergeSNMPSurface completa con SNMP un sondeo que ya llegó por pusher
+// (#1726). Una unidad puede tener snmp_enabled y a la vez estar alimentada
+// por un agente: hasta ahora el poller devolvía en cuanto había payload
+// fresco y la rama SNMP no se alcanzaba nunca, así que el ajuste era un
+// no-op silencioso. Aquí SNMP es segunda fuente: solo rellena lo que el
+// payload no trae (velocidad de boca, contadores de error y vecinos LLDP).
+// No toca vitals (CPU/RAM/temperatura), que manda el payload desde #1724, ni
+// el FDB, que sí trae el agente.
+func (l *Live) mergeSNMPSurface(cfg RouterConfig, p *routerPolled) {
+	if !cfg.SnmpEnabled || p == nil {
+		return
+	}
+	interval := cfg.SnmpPollInterval
+	if interval <= 0 {
+		interval = 60
+	}
+	now := l.now()
+	l.mu.Lock()
+	entry, has := l.snmpSurface[cfg.ID]
+	l.mu.Unlock()
+	if !has || now.Sub(entry.at) >= time.Duration(interval)*time.Second {
+		entry = l.pollSNMPSurface(cfg, now)
+		l.mu.Lock()
+		if l.snmpSurface == nil {
+			l.snmpSurface = map[string]snmpSurfaceEntry{}
+		}
+		l.snmpSurface[cfg.ID] = entry
+		l.mu.Unlock()
+	}
+	if !entry.ok {
+		return
+	}
+	applySNMPSurface(p, entry)
+}
+
+// pollSNMPSurface sondea solo la superficie que el pusher no puede dar: la
+// tabla de interfaces (velocidad de enlace y contadores de error) y los
+// vecinos LLDP. Deliberadamente no llama a recordPortSamples ni a
+// portMon.Observe: las muestras del pusher ya entran por otro camino con sus
+// propios IDs, y duplicarlas aquí intercalaría filas con ids "snmp-N".
+func (l *Live) pollSNMPSurface(cfg RouterConfig, now time.Time) snmpSurfaceEntry {
+	entry := snmpSurfaceEntry{at: now}
+	session, err := npsnmp.NewSession(npsnmp.Config{
+		Host:      cfg.Host,
+		Port:      cfg.SnmpPort,
+		Community: cfg.SnmpCommunity,
+	})
+	if err != nil {
+		l.recordSnmpFailure(cfg, err)
+		return entry
+	}
+	defer npsnmp.CloseSession(session)
+
+	ports, ifErr := npsnmp.PollIfTable(session)
+	if ifErr != nil || len(ports) == 0 {
+		pollErr := ifErr
+		if pollErr == nil {
+			pollErr = fmt.Errorf("snmp ifTable %s: sin puertos", cfg.Host)
+		}
+		l.recordSnmpFailure(cfg, pollErr)
+		return entry
+	}
+	// Misma salud SNMP que el poll completo: si esta unidad deja de responder
+	// por SNMP, la alerta de #930 sigue viéndose aunque el pusher vaya bien.
+	l.recordSnmpSuccess(cfg)
+
+	byIface := make(map[string]EthPort, len(ports))
+	portIdxToName := make(map[int]string, len(ports))
+	for _, ps := range ports {
+		name := ps.DisplayName()
+		portIdxToName[ps.Index] = name
+		key := strings.ToLower(strings.TrimSpace(name))
+		if key == "" {
+			continue
+		}
+		byIface[key] = EthPort{
+			ID:     fmt.Sprintf("snmp-%d", ps.Index),
+			Label:  name,
+			Up:     ps.OperUp,
+			Speed:  ps.SpeedString(),
+			Iface:  name,
+			RxErrs: ps.RxErrors,
+			TxErrs: ps.TxErrors,
+			Snmp:   true,
+		}
+	}
+
+	var lldp []LldpNeighbor
+	if rem, lldpErr := npsnmp.PollLldpRemTable(session); lldpErr != nil {
+		log.Printf("[netpulse] SNMP LLDP %s: %v", cfg.LogLabel(), lldpErr)
+	} else {
+		lldp = snmpLldpNeighbors(rem, portIdxToName)
+	}
+
+	entry.byIface = byIface
+	entry.lldp = lldp
+	entry.ok = true
+	return entry
+}
+
+// applySNMPSurface rellena en el sondeo del pusher lo que SNMP sí trae. Las
+// bocas se casan por ifName/ifAlias (el payload trae el mismo nombre que la
+// tabla de interfaces del equipo). Un dato del payload nunca se pisa: solo se
+// rellena cuando viene vacío o a cero.
+func applySNMPSurface(p *routerPolled, entry snmpSurfaceEntry) {
+	if p == nil || len(entry.byIface) == 0 {
+		return
+	}
+	for i := range p.ports {
+		port := &p.ports[i]
+		key := strings.ToLower(strings.TrimSpace(port.Iface))
+		if key == "" {
+			key = strings.ToLower(strings.TrimSpace(port.Label))
+		}
+		ref, ok := entry.byIface[key]
+		if !ok {
+			continue
+		}
+		// ifHighSpeed=0 significa "sin enlace" o "no reportado", no una
+		// velocidad: solo se propaga una cifra positiva y solo si el payload
+		// no dio ninguna.
+		if parseSpeedMbps(port.Speed) == 0 && parseSpeedMbps(ref.Speed) > 0 {
+			port.Speed = ref.Speed
+		}
+		// El contrato del payload no distingue "no reporto errores" de "cero
+		// errores", así que un 0 se trata como desconocido y SNMP lo completa.
+		if port.RxErrs == 0 && ref.RxErrs > 0 {
+			port.RxErrs = ref.RxErrs
+		}
+		if port.TxErrs == 0 && ref.TxErrs > 0 {
+			port.TxErrs = ref.TxErrs
+		}
+	}
+	// RouterOS por API no expone LLDP (#1726), así que en estas unidades la
+	// topología cae a las MACs del FDB. Los vecinos de LLDP-MIB son mejores
+	// que esa conjetura.
+	if len(p.lldp) == 0 && len(entry.lldp) > 0 {
+		p.lldp = entry.lldp
+		p.lldpUnavailable = false
+		p.lldpHint = ""
+	}
+}

+ 107 - 0
server-go/internal/adapters/snmp_merge_test.go

@@ -0,0 +1,107 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+)
+
+// #1726: SNMP como segunda fuente en unidades con pusher. Rellena lo que el
+// payload no trae y no pisa nada de lo que sí viene.
+func TestApplySNMPSurfaceFillsOnlyWhatPayloadLacks(t *testing.T) {
+	entry := snmpSurfaceEntry{
+		ok: true,
+		byIface: map[string]EthPort{
+			"sfp-sfpplus1": {Iface: "sfp-sfpplus1", Up: true, Speed: "10 Gbps", RxErrs: 5, TxErrs: 3},
+			"ether1":       {Iface: "ether1", Up: true, Speed: "1 Gbps", RxErrs: 9, TxErrs: 0},
+		},
+		lldp: []LldpNeighbor{{Port: "sfp-sfpplus1", Chassis: "XS708T"}},
+	}
+	p := &routerPolled{
+		ports: []EthPort{
+			// El pusher de RouterOS no da velocidad de enlace: se rellena.
+			{ID: "sfp-sfpplus1", Iface: "sfp-sfpplus1", Up: true},
+			// Aquí el payload sí trae velocidad y un contador de errores: no se pisa.
+			{ID: "ether1", Iface: "ether1", Up: true, Speed: "1 Gbps", RxErrs: 2},
+		},
+		lldpUnavailable: true,
+	}
+	applySNMPSurface(p, entry)
+
+	if got := p.ports[0].Speed; got != "10 Gbps" {
+		t.Fatalf("velocidad de la boca sin dato: quiero %q, tengo %q", "10 Gbps", got)
+	}
+	if p.ports[0].RxErrs != 5 || p.ports[0].TxErrs != 3 {
+		t.Fatalf("contadores de error: quiero 5/3, tengo %d/%d", p.ports[0].RxErrs, p.ports[0].TxErrs)
+	}
+	if got := p.ports[1].Speed; got != "1 Gbps" {
+		t.Fatalf("no debe pisar la velocidad del payload: tengo %q", got)
+	}
+	if p.ports[1].RxErrs != 2 {
+		t.Fatalf("no debe pisar errores del payload: tengo %d", p.ports[1].RxErrs)
+	}
+	if len(p.lldp) != 1 || p.lldp[0].Chassis != "XS708T" {
+		t.Fatalf("los vecinos LLDP de SNMP deben entrar cuando el payload no trae: %+v", p.lldp)
+	}
+	if p.lldpUnavailable {
+		t.Fatal("con vecinos LLDP la sonda no debe quedar marcada como no disponible")
+	}
+}
+
+func TestApplySNMPSurfaceIgnoresDownLinkSpeed(t *testing.T) {
+	entry := snmpSurfaceEntry{
+		ok: true,
+		byIface: map[string]EthPort{
+			// ifHighSpeed=0 en un puerto down: no es una velocidad.
+			"sfp-sfpplus3": {Iface: "sfp-sfpplus3", Speed: ""},
+		},
+	}
+	p := &routerPolled{ports: []EthPort{{ID: "sfp-sfpplus3", Iface: "sfp-sfpplus3"}}}
+	applySNMPSurface(p, entry)
+	if got := p.ports[0].Speed; got != "" {
+		t.Fatalf("una boca sin enlace no debe heredar velocidad: tengo %q", got)
+	}
+}
+
+func TestApplySNMPSurfaceKeepsPayloadLldp(t *testing.T) {
+	entry := snmpSurfaceEntry{
+		ok:      true,
+		byIface: map[string]EthPort{},
+		lldp:    []LldpNeighbor{{Port: "sfp-sfpplus1", Chassis: "desde-snmp"}},
+	}
+	p := &routerPolled{lldp: []LldpNeighbor{{Port: "sfp-sfpplus1", Chassis: "desde-payload"}}}
+	applySNMPSurface(p, entry)
+	if len(p.lldp) != 1 || p.lldp[0].Chassis != "desde-payload" {
+		t.Fatalf("los vecinos del payload mandan: %+v", p.lldp)
+	}
+}
+
+// Una entrada fresca en caché se aplica sin volver a sondear SNMP: el host de
+// prueba es inalcanzable, así que un sondeo real dejaría el puerto sin datos.
+func TestMergeSNMPSurfaceUsesFreshCache(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "crs305", Host: "127.0.0.1", SnmpEnabled: true, SnmpPort: 1}
+	l.snmpSurface[cfg.ID] = snmpSurfaceEntry{
+		at:      time.Now(),
+		ok:      true,
+		byIface: map[string]EthPort{"sfp-sfpplus1": {Iface: "sfp-sfpplus1", Speed: "10 Gbps"}},
+	}
+	p := &routerPolled{cfg: cfg, ports: []EthPort{{ID: "sfp-sfpplus1", Iface: "sfp-sfpplus1"}}}
+	l.mergeSNMPSurface(cfg, p)
+	if got := p.ports[0].Speed; got != "10 Gbps" {
+		t.Fatalf("la caché fresca debe aplicarse sin sondear: tengo %q", got)
+	}
+}
+
+// Sin snmp_enabled no se toca nada ni se siembra la caché.
+func TestMergeSNMPSurfaceSkipsWhenDisabled(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "crs305", Host: "127.0.0.1", SnmpPort: 1}
+	p := &routerPolled{cfg: cfg, ports: []EthPort{{ID: "sfp-sfpplus1", Iface: "sfp-sfpplus1"}}}
+	l.mergeSNMPSurface(cfg, p)
+	if _, ok := l.snmpSurface[cfg.ID]; ok {
+		t.Fatal("sin snmp_enabled no debe sondearse ni cachearse nada")
+	}
+	if p.ports[0].Speed != "" {
+		t.Fatalf("sin SNMP la boca debe quedar como vino: %q", p.ports[0].Speed)
+	}
+}