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

feat(snmp): full device name and MikroTik SwOS chassis temperature (#1266)

* feat(snmp): full device name and MikroTik SwOS chassis temperature

Two gaps reported for SNMP switches (#1256, MikroTik CSS610-8G-2S+ on
SwOS):

- The fleet card showed the short configured name: sysDescr (already
  polled) now feeds the unit model, so the full name the switch
  declares (e.g. "CSS610-8G-2S+ SwOS v2.21") shows up.
- SNMP switches had no temperature vital at all. A best-effort read of
  the MikroTik enterprise health OID (14988.1.1.3.100.1.3.52.0) fills
  Temp in whole degrees (60 = 60 C on SwOS; the tenths convention is
  RouterOS, not SwOS). Values outside a physical range or non-numeric
  PDUs are discarded; switches without the OID keep Temp at null
  exactly as before (#441), and the extra GET never fails the poll.

Closes #1256

* feat(snmp): use sysName as the SNMP unit name

pl-komuch feedback on #1256: the user-defined sysName (system page of
SwOS) is the natural device name, while sysDescr stays as the model. So
Name <- sysName and Model <- sysDescr for SNMP units.
Nacho 2 месяцев назад
Родитель
Сommit
1a9db42915

+ 42 - 19
server-go/internal/adapters/live.go

@@ -91,18 +91,26 @@ func pickGatewayCfg(polled map[string]*routerPolled) *RouterConfig {
 
 // routerPolled es el sondeo de un tick de un router.
 type routerPolled struct {
-	cfg       RouterConfig
-	client    *OpenWrtClient
-	sysInfo   *SysInfo
-	board     *BoardInfo
-	cpu       int
-	ram       int
-	temp              int
+	cfg     RouterConfig
+	client  *OpenWrtClient
+	sysInfo *SysInfo
+	board   *BoardInfo
+	cpu     int
+	ram     int
+	temp    int
+	// #1256: SNMP rellena sysDescr (nombre/modelo completo del switch) y,
+	// en MikroTik SwOS, la temperatura del chasis (hasTemp). hasTemp
+	// distingue "no aplica" de "0 °C" para no pisar el null de #441.
+	hasTemp  bool
+	sysDescr string
+	// sysName (#1256): hostname que el usuario define en el equipo; para
+	// SNMP alimenta el Name visible de la unidad en flota.
+	sysName           string
 	flash             string
 	firmwareAvailable string
 	uptimeSec         float64
-	net       *NetDevBps
-	leases    []DhcpLease
+	net               *NetDevBps
+	leases            []DhcpLease
 	// glClients (GL.iNet): base de clientes del firmware, superset de las
 	// leases. Se usa SOLO para resolver IPs de dispositivos ya conocidos que
 	// salen sin IP (dnsmasq sin lease), nunca para crear dispositivos nuevos.
@@ -290,10 +298,10 @@ type Live struct {
 	// flap breve no cierre el incidente.
 	offlineOpen   map[string]bool
 	recoverStreak map[string]int
-	engine              *alerts.Engine
-	wgActive            map[string]bool
-	weakAlerted         map[string]int64
-	onlineMacs          map[string]bool
+	engine        *alerts.Engine
+	wgActive      map[string]bool
+	weakAlerted   map[string]int64
+	onlineMacs    map[string]bool
 	// unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
 	// MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
 	// (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
@@ -1250,6 +1258,11 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.board != nil && p.board.Model != "" {
 		model = p.board.Model
 	}
+	// #1256: los switches SNMP no tienen board (sondeo sin SSH); el
+	// sysDescr declara el nombre/modelo completo del equipo.
+	if p.cfg.SnmpEnabled && p.sysDescr != "" {
+		model = p.sysDescr
+	}
 	name := p.cfg.Name
 	if name == "" {
 		name = p.cfg.Host
@@ -1257,6 +1270,12 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.board != nil && p.board.Hostname != "" {
 		name = p.board.Hostname
 	}
+	// #1256: los switches SNMP no tienen board; el sysName (hostname que el
+	// usuario define en el equipo, p. ej. la página de sistema de SwOS) es
+	// el nombre natural de la unidad.
+	if p.cfg.SnmpEnabled && p.sysName != "" {
+		name = p.sysName
+	}
 	health := 100
 	if p.cpu > 85 {
 		health -= 20
@@ -1302,6 +1321,11 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if noVitals {
 		r.VitalsAvailable = bptr(false)
 		r.CPU, r.RAM, r.Temp = nil, nil, nil
+		// #1256: si el sondeo SNMP trajo temperatura real (MikroTik SwOS),
+		// no la pisamos con null: se conserva la vital junto a las demás.
+		if p.hasTemp {
+			r.Temp = iptr(p.temp)
+		}
 	}
 	r.SnmpEnabled = p.cfg.SnmpEnabled
 	if p.selfExpose {
@@ -4601,7 +4625,6 @@ func deviceDisplayName(mac string, leases map[string]DhcpLease, aliases map[stri
 	return mac
 }
 
-
 // portEnrichDeps: mapas compartidos del enriquecimiento de bocas del
 // detalle (extraído de GetRouterDetail, #1150, para poder testearlo).
 type portEnrichDeps struct {
@@ -4673,7 +4696,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 			// La pista "cliente WiFi detrás" la traduce el cliente
 			// según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
 			port.PeerKind = "ap-wifi"
-		return port
+			return port
 		}
 	}
 	// 2) Un solo dispositivo final
@@ -4695,7 +4718,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 			port.ConnectedTo = "Hypervisor"
 			port.DeviceMac = mac
 			port.Detail = virtualDetail(mac, d.leaseMap, d.aliasByMac)
-		return port
+			return port
 		}
 		// Label curada que no coincide con el dispositivo resuelto:
 		// - si el dispositivo tiene nombre real (lease/alias), la label
@@ -4725,7 +4748,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 			} else if lldpMgmt != "" && lldpName != "" {
 				port.Detail = lldpMgmt + " · LLDP"
 			}
-		return port
+			return port
 		}
 		switch {
 		case ok && lease.Hostname != "":
@@ -4759,7 +4782,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 		if len(all) > 3 {
 			// deviceCount lo traduce la app; aquí NO se formatea texto (#1036).
 			port.DeviceCount = len(all)
-		return port
+			return port
 		}
 		// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
 		// es mejor pista que el hostname DHCP.
@@ -4770,7 +4793,7 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 			} else {
 				port.Detail = "LLDP"
 			}
-		return port
+			return port
 		}
 		infraMac := ""
 		for _, mac := range all {

+ 12 - 0
server-go/internal/adapters/snmp_live.go

@@ -46,6 +46,10 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 	if sysErr != nil {
 		log.Printf("[netpulse] SNMP system %s: %v", cfg.LogLabel(), sysErr)
 	}
+	// #1256: temperatura del chasis en MikroTik SwOS (grados enteros).
+	// Best-effort: los switches que no exponen el OID responden
+	// NoSuchInstance y hasTemp queda false (vitals a null como antes).
+	mikroTemp, hasTemp := npsnmp.PollMikrotikTemp(session)
 	// #1036: MAC propia del switch (dot1dBaseBridgeAddress). Sin ella el
 	// equipo no tenía MAC en flota ni casaba por MAC en topología. Cache:
 	// si el OID no contesta en este poll se conserva la última conocida.
@@ -191,6 +195,14 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		lldp:      snmpLldpNeighbors(lldpRem, portIdxToName),
 		polledAt:  now.UnixMilli(),
 	}
+	if sysInfo != nil {
+		// #1256: sysDescr declara el modelo completo del equipo (p. ej.
+		// "CSS610-8G-2S+ SwOS v2.21") y sysName el hostname que define el
+		// usuario; buildRouter los reparte entre Model y Name.
+		p.sysDescr = sysInfo.Descr
+		p.sysName = sysInfo.Name
+	}
+	p.temp, p.hasTemp = mikroTemp, hasTemp
 	l.mu.Lock()
 	l.snmpLastPoll[cfg.ID] = now
 	l.mu.Unlock()

+ 23 - 15
server-go/internal/snmp/oids.go

@@ -1,33 +1,33 @@
 package snmp
 
 const (
-	OidSysDescr    = ".1.3.6.1.2.1.1.1.0"
-	OidSysName     = ".1.3.6.1.2.1.1.5.0"
-	OidSysUpTime   = ".1.3.6.1.2.1.1.3.0"
+	OidSysDescr  = ".1.3.6.1.2.1.1.1.0"
+	OidSysName   = ".1.3.6.1.2.1.1.5.0"
+	OidSysUpTime = ".1.3.6.1.2.1.1.3.0"
 
-	OidIfNumber    = ".1.3.6.1.2.1.2.1.0"
-	OidIfTable     = ".1.3.6.1.2.1.2.2.1"
-	OidIfIndex     = ".1.3.6.1.2.1.2.2.1.1"
-	OidIfDescr     = ".1.3.6.1.2.1.2.2.1.2"
-	OidIfType      = ".1.3.6.1.2.1.2.2.1.3"
-	OidIfSpeed     = ".1.3.6.1.2.1.2.2.1.5"
-	OidIfOperStatus= ".1.3.6.1.2.1.2.2.1.8"
-	OidIfInOctets  = ".1.3.6.1.2.1.2.2.1.10"
-	OidIfInErrors  = ".1.3.6.1.2.1.2.2.1.14"
+	OidIfNumber     = ".1.3.6.1.2.1.2.1.0"
+	OidIfTable      = ".1.3.6.1.2.1.2.2.1"
+	OidIfIndex      = ".1.3.6.1.2.1.2.2.1.1"
+	OidIfDescr      = ".1.3.6.1.2.1.2.2.1.2"
+	OidIfType       = ".1.3.6.1.2.1.2.2.1.3"
+	OidIfSpeed      = ".1.3.6.1.2.1.2.2.1.5"
+	OidIfOperStatus = ".1.3.6.1.2.1.2.2.1.8"
+	OidIfInOctets   = ".1.3.6.1.2.1.2.2.1.10"
+	OidIfInErrors   = ".1.3.6.1.2.1.2.2.1.14"
 
 	// OidDot1dBaseBridgeAddress (BRIDGE-MIB): MAC base del bridge del
 	// switch. Fuente para la MAC propia de un switch sondeado por SNMP
 	// (#1036): sin ella el equipo no casaba por MAC en topología.
 	OidDot1dBaseBridgeAddress = ".1.3.6.1.2.1.17.1.1.0"
-	OidIfOutOctets = ".1.3.6.1.2.1.2.2.1.16"
-	OidIfOutErrors = ".1.3.6.1.2.1.2.2.1.20"
+	OidIfOutOctets            = ".1.3.6.1.2.1.2.2.1.16"
+	OidIfOutErrors            = ".1.3.6.1.2.1.2.2.1.20"
 
 	OidIfXTable    = ".1.3.6.1.2.1.31.1.1.1"
 	OidIfName      = ".1.3.6.1.2.1.31.1.1.1.1"
 	OidIfHighSpeed = ".1.3.6.1.2.1.31.1.1.1.15"
 	OidIfAlias     = ".1.3.6.1.2.1.31.1.1.1.18"
 
-	OidDot1dTpFdbPort    = ".1.3.6.1.2.1.17.4.3.1.2"
+	OidDot1dTpFdbPort       = ".1.3.6.1.2.1.17.4.3.1.2"
 	OidDot1dBasePortIfIndex = ".1.3.6.1.2.1.17.1.4.1.2"
 	// OidDot1qTpFdbPort: tabla FDB de Q-BRIDGE MIB (RFC 4363). Algunos
 	// switches gestionados solo la exponen (y no la dot1d) → fallback (#661).
@@ -39,4 +39,12 @@ const (
 	// contrato que la sonda lldpd de los routers (#300).
 	OidLldpRemTable   = ".1.0.8802.1.1.2.1.4.1.1"
 	OidLldpRemManAddr = ".1.0.8802.1.1.2.1.4.2.1"
+
+	// OidMikrotikTemp: temperatura del chasis en switches MikroTik SwOS
+	// (OID empresarial 14988, health table). Gauge32 en GRADOS ENTEROS
+	// (#1256: un CSS610-8G-2S+ SwOS v2.21 reporta 60 = 60 °C; la convención
+	// de décimas es de RouterOS, no asumirla en SwOS). Best-effort: un
+	// switch que no lo expone responde NoSuchInstance y la vital queda a
+	// null como antes (#441).
+	OidMikrotikTemp = ".1.3.6.1.4.1.14988.1.1.3.100.1.3.52.0"
 )

+ 48 - 2
server-go/internal/snmp/system.go

@@ -8,8 +8,8 @@ import (
 )
 
 type SystemInfo struct {
-	Descr    string
-	Name     string
+	Descr     string
+	Name      string
 	UpTimeSec uint64
 }
 
@@ -95,3 +95,49 @@ func bridgeMacFromPDU(v gosnmp.SnmpPDU) string {
 	}
 	return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5])
 }
+
+// PollMikrotikTemp lee la temperatura del chasis de un switch MikroTik SwOS
+// (#1256, OidMikrotikTemp, grados enteros). Best-effort: cualquier fallo
+// (OID ausente, equipo no MikroTik, timeout) devuelve ok=false y NUNCA
+// tumba el poll, igual que PollBridgeAddress (#1036).
+func PollMikrotikTemp(s *gosnmp.GoSNMP) (temp int, ok bool) {
+	result, err := s.Get([]string{OidMikrotikTemp})
+	if err != nil {
+		return 0, false
+	}
+	for _, v := range result.Variables {
+		if v.Name != OidMikrotikTemp {
+			continue
+		}
+		return mikrotikTempFromPDU(v)
+	}
+	return 0, false
+}
+
+// mikrotikTempFromPDU convierte el Gauge32 del OID de temperatura a (°C,
+// true). NoSuchObject/Instance u otro tipo de dato → (0, false): la vital
+// queda a null en la UI (#441), no a cero falso.
+func mikrotikTempFromPDU(v gosnmp.SnmpPDU) (int, bool) {
+	if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
+		return 0, false
+	}
+	// Solo tipos numéricos: ToBigInt parsea strings y octet strings, que
+	// aquí serían un dato del equipo mal formado, no una temperatura.
+	switch v.Type {
+	case gosnmp.Gauge32, gosnmp.Integer, gosnmp.Counter32, gosnmp.Counter64:
+	default:
+		return 0, false
+	}
+	bi, okBig := v.Value.(*big.Int)
+	if !okBig {
+		bi = gosnmp.ToBigInt(v.Value)
+	}
+	if !bi.IsInt64() {
+		return 0, false
+	}
+	n := bi.Int64()
+	if n < -40 || n > 125 {
+		return 0, false // fuera de rango físico: dato basura, no una temp
+	}
+	return int(n), true
+}

+ 23 - 0
server-go/internal/snmp/system_test.go

@@ -1,6 +1,7 @@
 package snmp
 
 import (
+	"math/big"
 	"testing"
 
 	"github.com/gosnmp/gosnmp"
@@ -26,3 +27,25 @@ func TestBridgeMacFromPDU(t *testing.T) {
 		t.Errorf("nosuchobject: got %q, want vacío", got)
 	}
 }
+
+// #1256: el Gauge32 del OID MikroTik da grados enteros; NoSuchInstance u
+// otro tipo dejan la vital a null (ok=false), y un valor fuera de rango
+// físico se descarta como basura.
+func TestMikrotikTempFromPDU(t *testing.T) {
+	good := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.Gauge32, Value: big.NewInt(60)}
+	if n, ok := mikrotikTempFromPDU(good); !ok || n != 60 {
+		t.Errorf("gauge 60: got (%d,%v)", n, ok)
+	}
+	noObj := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.NoSuchInstance, Value: nil}
+	if _, ok := mikrotikTempFromPDU(noObj); ok {
+		t.Error("nosuchinstance debe dar ok=false")
+	}
+	str := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.OctetString, Value: "60"}
+	if _, ok := mikrotikTempFromPDU(str); ok {
+		t.Error("octetstring debe dar ok=false")
+	}
+	hot := gosnmp.SnmpPDU{Name: OidMikrotikTemp, Type: gosnmp.Gauge32, Value: big.NewInt(900)}
+	if _, ok := mikrotikTempFromPDU(hot); ok {
+		t.Error("900 fuera de rango debe dar ok=false")
+	}
+}