Bläddra i källkod

feat(snmp): read the MikroTik health table by name, add HOST-RESOURCES vitals (#1758)

Reads the MikroTik health table by name (cpu-temperature first, max of the remaining temperature rows as fallback) instead of the fixed index from #1256, which RouterOS never answered. That legacy Get stays as the last attempt for SwOS.

Adds HOST-RESOURCES as the backup for CPU (max of hrProcessorLoad) and RAM (the hrStorage row whose description matches "main memory", used over size, null without it). The walks are gated by sysDescr, the HOST-RESOURCES probe runs once per router with a six hour negative cache, and the merge only fills vitals no other reader has set.

Closes #1725.

Co-authored-by: Bann-DEV <hef.fangyuan@gmail.com>
Bann-DEV 1 månad sedan
förälder
incheckning
18743e85ed

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

@@ -324,6 +324,10 @@ type Live struct {
 	// snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
 	// para loguear solo cuando el resultado cambia.
 	snmpFdbCount map[string]int
+	// snmpHr (#1725): si el agente de cada router publica HOST-RESOURCES y
+	// cuándo se preguntó. Se cachea porque hay agentes que descartan el árbol
+	// sin responder, y eso cuesta 10 s por operación.
+	snmpHr map[string]snmpHrEntry
 	// snmpBrMac (#1036): última MAC base del bridge leída por SNMP por
 	// router. Cache para no perderla cuando el equipo no contesta el OID
 	// en un poll (la MAC alimenta el matching por MAC de la topología).
@@ -529,6 +533,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		snmpSurface:          map[string]snmpSurfaceEntry{},
 		snmpFdbCount:         map[string]int{},
 		snmpBrMac:            map[string]string{},
+		snmpHr:               map[string]snmpHrEntry{},
 		snmpPollStats:        map[string]*snmpPollStat{},
 		ping:                 pingHost,
 		snmpLastMetricsTick:  map[string]int64{},

+ 76 - 4
server-go/internal/adapters/snmp_live.go

@@ -47,14 +47,31 @@ 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)
+	// #1256 + #1725: temperatura del chasis en switches MikroTik. Se lee la
+	// health table por el NOMBRE de la sonda ("cpu-temperature"), no por el
+	// índice 52 con `.0` que #1256 fijó de un SwOS: en RouterOS la tabla está
+	// ahí mismo pero en otra fila, y el Get nunca contestaba (medido:
+	// NoSuchObject en un CRS305 con 51 °C disponibles). Best-effort: los
+	// switches que no exponen nada dejan hasTemp false (vitals a null como
+	// antes, #441).
+	descr := ""
+	if sysInfo != nil {
+		descr = sysInfo.Descr
+	}
+	mikroTemp, hasTemp := npsnmp.PollMikrotikTemp(session, descr)
 	// Netgear FastPath (XS708T, GS728TXP/S3300…): CPU por proceso y sensores
 	// de temperatura en su MIB privada (4526.11). Best-effort igual que el
 	// MikroTik: sin esos árboles, ok=false y los vitales siguen a null.
 	ngCpu, hasNgCpu, ngTemp, hasNgTemp := npsnmp.PollNetgearVitals(session)
+	// #1725: HOST-RESOURCES (hrProcessorLoad / hrStorageTable "main memory")
+	// para los equipos sin MIB privada de vitales — RouterOS por SNMP es el
+	// caso real. Se pregunta primero y una sola vez por equipo
+	// (hostResourcesKnown), porque hay agentes que descartan el árbol en
+	// silencio y cada operación así cuesta DefaultTimeout×(Retries+1)=10 s.
+	hrCpu, hasHrCpu, hrRam, hasHrRam := 0, false, 0, false
+	if l.hostResourcesKnown(cfg.ID, func() bool { return npsnmp.HostResourcesPresent(session) }) {
+		hrCpu, hasHrCpu, hrRam, hasHrRam = npsnmp.PollHostResourcesVitals(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.
@@ -216,12 +233,67 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 	if hasNgCpu {
 		p.cpu, p.hasCpu = ngCpu, true
 	}
+	// #1725: HOST-RESOURCES solo rellena huecos (veáse
+	// applyHostResourcesVitals).
+	applyHostResourcesVitals(p, hrCpu, hasHrCpu, hrRam, hasHrRam)
 	l.mu.Lock()
 	l.snmpLastPoll[cfg.ID] = now
 	l.mu.Unlock()
 	return p, nil
 }
 
+// snmpHrEntry (#1725): si el agente de este equipo publica HOST-RESOURCES, y
+// cuándo se preguntó por última vez.
+type snmpHrEntry struct {
+	at time.Time
+	ok bool
+}
+
+// snmpHrProbeTTL: cada cuánto se vuelve a preguntar. Un firmware nuevo puede
+// añadir el árbol, y seis horas es un margen con el que nadie espera ver una
+// vital distinta; a cambio, un equipo que lo descarta en silencio paga UN
+// timeout por ventana en lugar de uno por poll (pollRouterSNMP corre cada
+// snmp_poll_interval, 60 s por defecto).
+const snmpHrProbeTTL = 6 * time.Hour
+
+// hostResourcesKnown cachea la respuesta de la pregunta "¿este agente tiene
+// HOST-RESOURCES?". El probe va como callback porque el paquete adapters no
+// importa gosnmp: la sesión SNMP sigue siendo un detalle de internal/snmp.
+func (l *Live) hostResourcesKnown(routerID string, probe func() bool) bool {
+	now := l.now()
+	l.mu.Lock()
+	entry, seen := l.snmpHr[routerID]
+	l.mu.Unlock()
+	if seen && now.Sub(entry.at) < snmpHrProbeTTL {
+		return entry.ok
+	}
+	ok := probe()
+	l.mu.Lock()
+	if l.snmpHr == nil {
+		l.snmpHr = map[string]snmpHrEntry{}
+	}
+	l.snmpHr[routerID] = snmpHrEntry{at: now, ok: ok}
+	l.mu.Unlock()
+	return ok
+}
+
+// applyHostResourcesVitals (#1725): HOST-RESOURCES es respaldo, no segunda
+// opinión. Una lectura privada (la health table de MikroTik, el FastPath de
+// Netgear) es lo que el panel del propio equipo muestra; el árbol genérico mide
+// de otra forma, así que aquí solo rellena lo que quedó sin bandera. Y sin
+// bandera no inventa: ok=false no escribe ni un cero (#441).
+func applyHostResourcesVitals(p *routerPolled, cpu int, okCpu bool, ramPct int, okRam bool) {
+	if p == nil {
+		return
+	}
+	if !p.hasCpu && okCpu {
+		p.cpu, p.hasCpu = cpu, true
+	}
+	if !p.hasRam && okRam {
+		p.ram, p.hasRam = ramPct, true
+	}
+}
+
 // snmpPollStat (issue #930): salud del sondeo SNMP por router. En memoria,
 // protegido por l.mu. failingOpen marca el incidente ABIERTO (alerta emitida
 // y aún no recuperada) para no repetir la alerta hasta la recuperación.

+ 80 - 0
server-go/internal/adapters/snmp_live_test.go

@@ -305,3 +305,83 @@ func TestSnmpSelfMacs(t *testing.T) {
 		t.Fatalf("devices: %+v, want solo el cliente real", devs)
 	}
 }
+
+// #1725: HOST-RESOURCES es respaldo, no segunda opinión. Donde la MIB privada
+// ya leyó, la genérica no pisa; donde no leyó nada, rellena; y donde el equipo
+// no publica el árbol, no escribe ni un cero (#441).
+func TestApplyHostResourcesVitalsSoloRellenaHuecos(t *testing.T) {
+	// Netgear FastPath ya dio CPU (suma de procesos). hrProcessorLoad diría
+	// otro número midiendo otra cosa: el panel del equipo muestra el primero.
+	p := &routerPolled{cpu: 7, hasCpu: true}
+	applyHostResourcesVitals(p, 73, true, 40, true)
+	if p.cpu != 7 || !p.hasCpu {
+		t.Errorf("cpu = %d/%v, want 7/true (la lectura privada manda)", p.cpu, p.hasCpu)
+	}
+	if p.ram != 40 || !p.hasRam {
+		t.Errorf("ram = %d/%v, want 40/true (la RAM sí era hueco)", p.ram, p.hasRam)
+	}
+
+	// RouterOS por SNMP: ninguna MIB privada, las dos entran.
+	r := &routerPolled{}
+	applyHostResourcesVitals(r, 1, true, 17, true)
+	if r.cpu != 1 || !r.hasCpu || r.ram != 17 || !r.hasRam {
+		t.Errorf("routeros = cpu %d/%v ram %d/%v, want 1/true 17/true", r.cpu, r.hasCpu, r.ram, r.hasRam)
+	}
+
+	// FN SWITCH 8 PRO: no publica HOST-RESOURCES. Sin bandera no se escribe
+	// nada y la tarjeta sigue mostrando null, no un 0 %.
+	f := &routerPolled{}
+	applyHostResourcesVitals(f, 0, false, 0, false)
+	if f.hasCpu || f.hasRam || f.cpu != 0 || f.ram != 0 {
+		t.Errorf("sin árbol genérico = %+v, want sin banderas y ceros intactos", f)
+	}
+
+	applyHostResourcesVitals(nil, 5, true, 5, true) // sin payload: no panica
+}
+
+// #1725: la pregunta por HOST-RESOURCES se hace una vez por equipo y se
+// recuerda TAMBIÉN cuando la respuesta fue negativa. Un agente que descarta el
+// árbol sin responder cuesta DefaultTimeout×(Retries+1)=10 s por operación;
+// sin cache eso se pagaría en cada poll (snmp_poll_interval, 60 s por
+// defecto) de forma indefinida.
+func TestHostResourcesKnownCachesBothAnswers(t *testing.T) {
+	base := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
+	calls := 0
+	l := NewLive(nil, nil, nil, nil)
+	l.now = func() time.Time { return base }
+	probe := func() bool { calls++; return false }
+
+	for i := 0; i < 5; i++ {
+		if l.hostResourcesKnown("sw1", probe) {
+			t.Fatal("el agente dijo que no; no puede salir true")
+		}
+		base = base.Add(time.Minute)
+		l.now = func() time.Time { return base }
+	}
+	if calls != 1 {
+		t.Fatalf("sondeos = %d, want 1 (la negativa se cachea igual que la afirmativa)", calls)
+	}
+
+	// Pasado el TTL se vuelve a preguntar: un firmware que añada el árbol se
+	// recoge sin reiniciar el server.
+	base = base.Add(snmpHrProbeTTL)
+	if l.hostResourcesKnown("sw1", probe) {
+		t.Fatal("sigue sin publicar el árbol")
+	}
+	if calls != 2 {
+		t.Fatalf("sondeos tras el TTL = %d, want 2", calls)
+	}
+
+	// Es por equipo, no global.
+	l.now = func() time.Time { return base }
+	otras := 0
+	if !l.hostResourcesKnown("sw2", func() bool { otras++; return true }) {
+		t.Fatal("sw2 sí publica y se descartó")
+	}
+	if otras != 1 {
+		t.Errorf("sondeos de sw2 = %d, want 1", otras)
+	}
+	if calls != 2 {
+		t.Errorf("sw1 no debe repetir su sondeo (%d)", calls)
+	}
+}

+ 195 - 0
server-go/internal/snmp/hostResources.go

@@ -0,0 +1,195 @@
+// hostResources.go — HOST-RESOURCES-MIB (#1725): CPU y RAM del árbol genérico,
+// para los equipos que no tienen ninguna MIB privada de vitales (RouterOS por
+// SNMP, agentes genéricos). Es RESPALDO: el caller solo lo usa cuando la
+// lectura del fabricante no dijo nada, porque la tabla privada es lo que el
+// propio firmware muestra en su panel.
+package snmp
+
+import (
+	"math"
+	"math/big"
+	"strings"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+// HostResourcesPresent: un Get barato para saber si el agente publica
+// HOST-RESOURCES antes de caminar sus tablas. Lo devuelven los equipos que sí
+// lo tienen (RouterOS: TimeTicks) y NoSuchObject en los que no (FN SWITCH 8
+// PRO: 1 ms), así que la pregunta cuesta un RTT; lo que cuesta caro es
+// caminar un árbol que el equipo va a descartar en silencio, por eso se
+// pregunta primero y el resultado se cachea arriba (#1725).
+func HostResourcesPresent(s *gosnmp.GoSNMP) bool {
+	if s == nil {
+		return false
+	}
+	result, err := s.Get([]string{OidHrSystemUptime})
+	if err != nil || result == nil || len(result.Variables) == 0 {
+		return false
+	}
+	v := result.Variables[0]
+	if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
+		return false
+	}
+	return v.Value != nil
+}
+
+// HrStorageRow: una fila de hrStorageTable con lo que hace falta para saber
+// cuánta memoria es y cuánta está usada. Size y Used vienen en las mismas
+// hrStorageAllocationUnits de la fila, así que la proporción es directa y no
+// hace falta leer allocationUnits para el porcentaje.
+type HrStorageRow struct {
+	Descr string
+	Size  uint64
+	Used  uint64
+}
+
+// ParseHrProcessorLoads: utilización de CPU = el MÁXIMO de hrProcessorLoad por
+// núcleo. Un promedio escondería un núcleo saturado en un equipo de dos, y la
+// pregunta que contesta el número en la tarjeta es "¿está ocupado este
+// equipo?". Sin filas válidas → (0, false); un valor fuera de 0..100 % no es
+// una utilización, se descarta (algunos agentes publican ahí otra magnitud).
+func ParseHrProcessorLoads(loads []int) (cpu int, ok bool) {
+	for _, v := range loads {
+		if v < 0 || v > 100 {
+			continue
+		}
+		if !ok || v > cpu {
+			cpu, ok = v, true
+		}
+	}
+	return cpu, ok
+}
+
+// ParseHrStorageRAM: porcentaje usado de la memoria principal. La fila se
+// reconoce por su descripción ("main memory", case-insensitive y aceptando
+// el sufijo de tamaño que algunos agentes añaden), NO por su índice:
+// hrStorageDescr varía por fabricante y elegir la primera fila que venga es
+// inventarse una lectura de RAM que puede ser un disco. Sin fila que case →
+// (0, false) y la vital se queda en null.
+func ParseHrStorageRAM(rows []HrStorageRow) (pct int, ok bool) {
+	for _, r := range rows {
+		if !isMainMemory(r.Descr) || r.Size == 0 || r.Used > r.Size {
+			continue
+		}
+		pct = int((r.Used*100 + r.Size/2) / r.Size) // redondeo, sin float
+		if pct < 0 {
+			pct = 0
+		}
+		if pct > 100 {
+			pct = 100
+		}
+		return pct, true
+	}
+	return 0, false
+}
+
+// isMainMemory: la descripción de la fila de RAM. Se compara en minúsculas y
+// sin el prefijo "system memory" que otros agentes usan para el mismo hueco.
+func isMainMemory(descr string) bool {
+	d := strings.ToLower(strings.TrimSpace(descr))
+	return d == "main memory" || strings.HasPrefix(d, "main memory")
+}
+
+// PollHostResourcesVitals lee CPU (hrProcessorTable) y RAM (hrStorageTable,
+// fila "main memory"). Best-effort como el resto del paquete: un walk que
+// falla o que no devuelve filas deja su vital sin bandera, y el poll sigue.
+func PollHostResourcesVitals(s *gosnmp.GoSNMP) (cpu int, okCpu bool, ramPct int, okRam bool) {
+	if s == nil {
+		return 0, false, 0, false
+	}
+	if pdus, err := walkSafe(s, OidHrProcessorLoad); err == nil {
+		loads := make([]int, 0, len(pdus))
+		for _, p := range pdus {
+			if v, ok := pduInt(p); ok {
+				loads = append(loads, v)
+			}
+		}
+		cpu, okCpu = ParseHrProcessorLoads(loads)
+	}
+	if rows, ok := pollHrStorage(s); ok {
+		ramPct, okRam = ParseHrStorageRAM(rows)
+	}
+	return cpu, okCpu, ramPct, okRam
+}
+
+// pduInt: entera de una PDU numérica. Rechaza NoSuchObject/Instance y
+// cualquier otro tipo (un string no es una utilización). A diferencia de
+// mikrotikTempFromPDU no aplica rango: lo decide el parser de cada vital, que
+// es el que sabe qué magnitud está leyendo.
+func pduInt(v gosnmp.SnmpPDU) (int, bool) {
+	switch v.Type {
+	case gosnmp.Integer, gosnmp.Gauge32, gosnmp.Counter32, gosnmp.Counter64, gosnmp.Uinteger32:
+	default:
+		return 0, false
+	}
+	// gosnmp deja el número como *big.Int en unos tipos y como entero nativo
+	// en otros (ToBigInt no convierte un *big.Int, devuelve 0).
+	bi, okBig := v.Value.(*big.Int)
+	if !okBig {
+		bi = gosnmp.ToBigInt(v.Value)
+	}
+	if !bi.IsInt64() {
+		return 0, false
+	}
+	n := bi.Int64()
+	if n < 0 || n > math.MaxInt32 {
+		return 0, false
+	}
+	return int(n), true
+}
+
+// pollHrStorage aparecea descr/size/used por índice de hrStorageTable. Como
+// mikrotikHealthRows con la tabla de salud: una fila a la que falte una
+// columna no es utilizable.
+//
+// La tabla se pide primero por su descripción y se aborta si no tiene filas:
+// un agente sin HOST-RESOURCES responde el walk vacío en un viaje, y seguir
+// con size/used serían dos RTTs más por cada poll de un equipo que nunca va
+// a dar RAM (#661 enseñó a mirar el coste del path SNMP).
+func pollHrStorage(s *gosnmp.GoSNMP) ([]HrStorageRow, bool) {
+	descr, errD := walkSafe(s, OidHrStorageDescr)
+	if errD != nil || len(descr) == 0 {
+		return nil, false
+	}
+	size, errS := walkSafe(s, OidHrStorageSize)
+	if errS != nil {
+		return nil, false
+	}
+	used, errU := walkSafe(s, OidHrStorageUsed)
+	if errU != nil {
+		return nil, false
+	}
+	type pair struct {
+		descr string
+		size  uint64
+	}
+	byIdx := map[int]*pair{}
+	for _, p := range descr {
+		if idx := trailingIndex(p.Name, OidHrStorageDescr); idx != 0 {
+			byIdx[idx] = &pair{descr: stringVal(p)}
+		}
+	}
+	for _, p := range size {
+		if idx := trailingIndex(p.Name, OidHrStorageSize); idx != 0 {
+			if row := byIdx[idx]; row != nil {
+				row.size = uint64Val(p)
+			}
+		}
+	}
+	out := make([]HrStorageRow, 0, len(byIdx))
+	for idx, row := range byIdx {
+		if row.size == 0 {
+			continue
+		}
+		usedVal := uint64(0)
+		for _, p := range used {
+			if trailingIndex(p.Name, OidHrStorageUsed) == idx {
+				usedVal = uint64Val(p)
+				break
+			}
+		}
+		out = append(out, HrStorageRow{Descr: row.descr, Size: row.size, Used: usedVal})
+	}
+	return out, len(out) > 0
+}

+ 112 - 0
server-go/internal/snmp/hostResources_test.go

@@ -0,0 +1,112 @@
+// hostResources_test.go — parsers de HOST-RESOURCES con la muestra real de un
+// CRS305 (RouterOS 7.25) capturada por #1725, y los casos en los que el árbol
+// no existe o no dice nada útil.
+package snmp
+
+import (
+	"math/big"
+	"testing"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+// Walk real (192.168.2.15, community del SNMP del equipo):
+//
+//	hrProcessorLoad.1 = 1  (cpu0)
+//	hrProcessorLoad.2 = 1  (cpu1)
+//	hrStorageDescr.65536 = "main memory"  hrStorageSize.65536 = 524288
+//	hrStorageUsed.65536  = 89840          allocationUnits = 1024 B
+//	hrStorageDescr.131072 = "system disk" (16384 KB)
+//
+// → CPU 1 %, RAM 89840/524288 = 17 %. El propio API de RouterOS decía
+// cpu-load=1 y free-memory=446193664 de total=536870912 (17 % usado): las dos
+// fuentes cuadran.
+func TestParseHrProcessorLoadsRealRouterOS(t *testing.T) {
+	cpu, ok := ParseHrProcessorLoads([]int{1, 1})
+	if !ok || cpu != 1 {
+		t.Fatalf("cpu = %d/%v, want 1/true", cpu, ok)
+	}
+}
+
+// El máximo, no la media: un núcleo al 73 % en un dual es un equipo ocupado, y
+// la media (37) escondería justo lo que la tarjeta tiene que avisar.
+func TestParseHrProcessorLoadsTakesMax(t *testing.T) {
+	cpu, ok := ParseHrProcessorLoads([]int{2, 73, 15})
+	if !ok || cpu != 73 {
+		t.Fatalf("cpu = %d/%v, want 73 (máximo por núcleo)", cpu, ok)
+	}
+}
+
+func TestParseHrProcessorLoadsRejectsGarbage(t *testing.T) {
+	if cpu, ok := ParseHrProcessorLoads([]int{200, 300}); ok || cpu != 0 {
+		t.Errorf("fuera de 0..100 no es una utilización: (%d,%v)", cpu, ok)
+	}
+	if _, ok := ParseHrProcessorLoads(nil); ok {
+		t.Error("sin filas ok debe ser false (null en la UI, no 0)")
+	}
+	// Un agente que publica un bicho suelto sí tiene lectura: el descarte no
+	// puede arrastrar a las filas válidas.
+	if cpu, ok := ParseHrProcessorLoads([]int{42, 7000}); !ok || cpu != 42 {
+		t.Errorf("cpu = %d/%v, want 42/true", cpu, ok)
+	}
+}
+
+func TestParseHrStorageRAMRealRouterOS(t *testing.T) {
+	rows := []HrStorageRow{
+		{Descr: "virtual memory", Size: 524288, Used: 0},
+		{Descr: "main memory", Size: 524288, Used: 89840},
+		{Descr: "system disk", Size: 16384, Used: 4096},
+	}
+	pct, ok := ParseHrStorageRAM(rows)
+	if !ok || pct != 17 {
+		t.Fatalf("ram = %d/%v, want 17 (89840/524288)", pct, ok)
+	}
+}
+
+// La fila se reconoce por su descripción, nunca por el índice: si no hay
+// "main memory", la RAM se queda en null, aunque el equipo publique discos y
+// memoria virtual. Un 100 % de "system disk" pintado como RAM es peor que un
+// null.
+func TestParseHrStorageRAMNoMainMemoryRowStaysUnknown(t *testing.T) {
+	rows := []HrStorageRow{
+		{Descr: "system disk", Size: 16384, Used: 15000},
+		{Descr: "virtual memory", Size: 524288, Used: 10},
+	}
+	if pct, ok := ParseHrStorageRAM(rows); ok || pct != 0 {
+		t.Fatalf("ram = %d/%v, want 0/false sin fila de memoria principal", pct, ok)
+	}
+}
+
+func TestParseHrStorageRAMVariantsAndBrokenRows(t *testing.T) {
+	if pct, ok := ParseHrStorageRAM([]HrStorageRow{{Descr: "Main Memory", Size: 1000, Used: 250}}); !ok || pct != 25 {
+		t.Errorf("la descripción se compara sin importar mayúsculas: (%d,%v)", pct, ok)
+	}
+	if _, ok := ParseHrStorageRAM([]HrStorageRow{{Descr: "main memory", Size: 0, Used: 0}}); ok {
+		t.Error("size 0 = fila sin dimensionar, no 0 % ni división por cero")
+	}
+	if _, ok := ParseHrStorageRAM([]HrStorageRow{{Descr: "main memory", Size: 100, Used: 140}}); ok {
+		t.Error("used > size es un contador roto: no se publica un 140 %")
+	}
+	// Redondeo: 1/3 = 33,3 %; 2/3 = 66,7 %.
+	if pct, _ := ParseHrStorageRAM([]HrStorageRow{{Descr: "main memory", Size: 3, Used: 1}}); pct != 33 {
+		t.Errorf("1/3 = %d, want 33", pct)
+	}
+	if pct, _ := ParseHrStorageRAM([]HrStorageRow{{Descr: "main memory", Size: 3, Used: 2}}); pct != 67 {
+		t.Errorf("2/3 = %d, want 67", pct)
+	}
+}
+
+func TestPduIntAceptaNumericosRechazaLoDemas(t *testing.T) {
+	if v, ok := pduInt(gosnmp.SnmpPDU{Type: gosnmp.Gauge32, Value: big.NewInt(73)}); !ok || v != 73 {
+		t.Errorf("gauge 73: (%d,%v)", v, ok)
+	}
+	if _, ok := pduInt(gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: "73"}); ok {
+		t.Error("un string no es una utilización")
+	}
+	if _, ok := pduInt(gosnmp.SnmpPDU{Type: gosnmp.NoSuchInstance}); ok {
+		t.Error("NoSuchInstance debe dar ok=false")
+	}
+	if _, ok := pduInt(gosnmp.SnmpPDU{Type: gosnmp.Counter32, Value: big.NewInt(-1)}); ok {
+		t.Error("un negativo no es una utilización")
+	}
+}

+ 32 - 6
server-go/internal/snmp/oids.go

@@ -47,11 +47,37 @@ const (
 	// vecino). Es la única identidad del vecino que estos switches dan.
 	OidLldpLocPortTable = ".1.0.8802.1.1.2.1.3.7.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: la fila que #1256 fijó a mano (SwOS, índice 52 y
+	// scalar .0, Gauge32 en GRADOS ENTEROS: un CSS610-8G-2S+ v2.21 reporta
+	// 60 = 60 °C; las décimas son convención de RouterOS, no asumirlas).
+	// RouterOS publica la MISMA tabla con la sonda en otro índice y sin .0,
+	// así que el lector pasó a caminar la tabla (#1725) y esto queda como
+	// último intento para equipos cuya tabla no exponga los nombres.
 	OidMikrotikTemp = ".1.3.6.1.4.1.14988.1.1.3.100.1.3.52.0"
+	// OidMikrotikHealthName/OidMikrotikHealthValue: columnas de la health
+	// table de MikroTik (14988.1.1.3.100.1). La fila 17 de un CRS305 real:
+	//
+	//	.100.1.2.17 = STRING: "cpu-temperature"
+	//	.100.1.3.17 = INTEGER: 48
+	//
+	// Se caminan las dos y se emparejan por índice (#1725): el valor sin su
+	// nombre no dice qué sonda es, y el nombre sin valor no da la lectura.
+	OidMikrotikHealthName  = ".1.3.6.1.4.1.14988.1.1.3.100.1.2"
+	OidMikrotikHealthValue = ".1.3.6.1.4.1.14988.1.1.3.100.1.3"
+
+	// HOST-RESOURCES-MIB (#1725): el árbol genérico que muchos agentes —
+	// RouterOS incluido— rellenan cuando no existe ninguna MIB privada. Son
+	// el respaldo cuando el fabricante no contesta, nunca por delante de él.
+	//
+	//	hrProcessorLoad.1 = 1     (cpu0)      → %, Gauge32 0..100
+	//	hrStorageDescr.65536       = "main memory"
+	//	hrStorageSize.65536 = 524288  hrStorageUsed.65536 = 89840
+	//
+	// Size y Used vienen en las MISMAS hrStorageAllocationUnits (1024 B aquí),
+	// así que la proporción es directa y no hace falta leer allocationUnits.
+	OidHrSystemUptime  = ".1.3.6.1.2.1.25.1.1.0"
+	OidHrProcessorLoad = ".1.3.6.1.2.1.25.3.3.1.2"
+	OidHrStorageDescr  = ".1.3.6.1.2.1.25.2.3.1.3"
+	OidHrStorageSize   = ".1.3.6.1.2.1.25.2.3.1.5"
+	OidHrStorageUsed   = ".1.3.6.1.2.1.25.2.3.1.6"
 )

+ 94 - 5
server-go/internal/snmp/system.go

@@ -3,6 +3,7 @@ package snmp
 import (
 	"fmt"
 	"math/big"
+	"strings"
 
 	"github.com/gosnmp/gosnmp"
 )
@@ -96,11 +97,41 @@ 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) {
+// PollMikrotikTemp lee la temperatura de la health table de MikroTik (#1725).
+//
+// Antes era un Get del índice 52 que #1256 copió de un SwOS. En RouterOS la
+// tabla existe pero la sonda está en otro índice y sin el `.0` final
+// (`100.1.2.17 = "cpu-temperature"`, `100.1.3.17 = 48`), así que el Get nunca
+// contestaba y la vital se quedaba en null aunque el agente tuviera el dato.
+//
+// La tabla se camina SOLO si sysDescr declara el firmware de MikroTik
+// ("RouterOS…" o "…SwOS…"): hay agentes que DESCARTAN lo que no está en su
+// vista MIB en vez de responder NoSuchObject, y cada operación así cuesta
+// DefaultTimeout×(Retries+1) = 10 s (medido en un XS708T y un S3300). Con el
+// filtro, un equipo que no es MikroTik paga exactamente lo que pagaba antes.
+//
+// Si la tabla no da nada —o ni siquiera se intentó, porque PollSystem falló y
+// no hay descripción— se cae al Get histórico de #1256, que es lo que hoy
+// responde en un SwOS. Best-effort en cualquier caso: sin lectura válida
+// (0, false) y el poll sigue (#1036), nunca un cero (#441).
+func PollMikrotikTemp(s *gosnmp.GoSNMP, sysDescr string) (temp int, ok bool) {
+	if s == nil {
+		return 0, false
+	}
+	if declaresMikrotik(sysDescr) {
+		names, errName := walkSafe(s, OidMikrotikHealthName)
+		values, errVal := []gosnmp.SnmpPDU(nil), error(nil)
+		if errName == nil && len(names) > 0 {
+			// Sin nombres no hay nada que aparear: el segundo walk sería un
+			// RTT más en cada poll de un equipo que no publica la tabla.
+			values, errVal = walkSafe(s, OidMikrotikHealthValue)
+		}
+		if errName == nil && errVal == nil {
+			if t, tok := ParseMikrotikHealth(mikrotikHealthRows(names, values)); tok {
+				return t, true
+			}
+		}
+	}
 	result, err := s.Get([]string{OidMikrotikTemp})
 	if err != nil {
 		return 0, false
@@ -114,6 +145,64 @@ func PollMikrotikTemp(s *gosnmp.GoSNMP) (temp int, ok bool) {
 	return 0, false
 }
 
+// declaresMikrotik: el firmware del equipo en su propia descripción. RouterOS
+// publica "RouterOS CRS305-1G-4S+ 7.25" y SwOS "CSS610-8G-2S+ SwOS v2.21"
+// (#1256); ambos son el mismo árbol 14988.
+func declaresMikrotik(sysDescr string) bool {
+	d := strings.ToLower(sysDescr)
+	return strings.Contains(d, "routeros") || strings.Contains(d, "swos")
+}
+
+// mikrotikHealthRows cruza nombre y valor por el índice final del OID. Un
+// índice sin nombre o sin valor utilizable se descarta: la tabla de salud
+// tiene filas que no son temperatura (el .4 es un flag), y aparearlas por las
+// fuerzas daría una lectura con nombre equivocado.
+func mikrotikHealthRows(names, values []gosnmp.SnmpPDU) map[string]int {
+	byIdx := map[int]int{}
+	for _, v := range values {
+		idx := trailingIndex(v.Name, OidMikrotikHealthValue)
+		if idx == 0 {
+			continue
+		}
+		if n, ok := mikrotikTempFromPDU(v); ok {
+			byIdx[idx] = n
+		}
+	}
+	out := map[string]int{}
+	for _, n := range names {
+		idx := trailingIndex(n.Name, OidMikrotikHealthName)
+		name := strings.ToLower(strings.TrimSpace(stringVal(n)))
+		if idx == 0 || name == "" {
+			continue
+		}
+		if val, ok := byIdx[idx]; ok {
+			out[name] = val
+		}
+	}
+	return out
+}
+
+// ParseMikrotikHealth: la temperatura de la health table a partir de las filas
+// ya apareadas nombre→valor. `cpu-temperature` manda (es la que /system health
+// imprime como CPU); si el equipo la nombra de otra forma se toma el MÁXIMO de
+// las filas cuyo nombre contenga "temperature" — el punto caliente, el mismo
+// criterio que los sensores Netgear (ParseNetgearTemps) y así el orden del
+// walk no decide la lectura.
+func ParseMikrotikHealth(rows map[string]int) (temp int, ok bool) {
+	if v, found := rows["cpu-temperature"]; found {
+		return v, true
+	}
+	for name, v := range rows {
+		if !strings.Contains(name, "temperature") {
+			continue
+		}
+		if !ok || v > temp {
+			temp, ok = v, true
+		}
+	}
+	return temp, ok
+}
+
 // 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.

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

@@ -49,3 +49,82 @@ func TestMikrotikTempFromPDU(t *testing.T) {
 		t.Error("900 fuera de rango debe dar ok=false")
 	}
 }
+
+// #1725: la health table de RouterOS. Muestra real de un CRS305 (RouterOS
+// 7.25), que es el caso que #1256 no cubría:
+//
+//	.100.1.2.17 = STRING: "cpu-temperature"
+//	.100.1.3.17 = INTEGER: 48
+//	.100.1.4.17 = INTEGER: 1
+//
+// El Get de 100.1.3.52.0 no contestaba nunca aquí (NoSuchObject), así que la
+// temperatura se quedaba en null con el dato puesto en la tabla de al lado.
+func TestMikrotikHealthRowsPareaNombreYValor(t *testing.T) {
+	names := []gosnmp.SnmpPDU{
+		{Name: OidMikrotikHealthName + ".17", Type: gosnmp.OctetString, Value: "cpu-temperature"},
+		{Name: OidMikrotikHealthName + ".18", Type: gosnmp.OctetString, Value: "switch-fan-state"},
+		{Name: OidMikrotikHealthName + ".19", Type: gosnmp.OctetString, Value: "board-temperature"},
+	}
+	values := []gosnmp.SnmpPDU{
+		{Name: OidMikrotikHealthValue + ".17", Type: gosnmp.Integer, Value: big.NewInt(48)},
+		{Name: OidMikrotikHealthValue + ".18", Type: gosnmp.Integer, Value: big.NewInt(1)},
+		{Name: OidMikrotikHealthValue + ".19", Type: gosnmp.Integer, Value: big.NewInt(51)},
+		{Name: OidMikrotikHealthValue + ".52.0", Type: gosnmp.Integer, Value: big.NewInt(60)},
+	}
+	rows := mikrotikHealthRows(names, values)
+	if len(rows) != 3 {
+		t.Fatalf("filas = %d, want 3 (el scalar .52.0 no es una fila de la tabla): %v", len(rows), rows)
+	}
+	if rows["cpu-temperature"] != 48 || rows["board-temperature"] != 51 {
+		t.Fatalf("apareadas mal: %v", rows)
+	}
+	if temp, ok := ParseMikrotikHealth(rows); !ok || temp != 48 {
+		t.Fatalf("temp = %d/%v, want 48/true (cpu-temperature manda)", temp, ok)
+	}
+}
+
+func TestParseMikrotikHealthFallbackYDescartes(t *testing.T) {
+	// Equipo que no nombra la sonda "cpu-temperature": el punto caliente de
+	// las filas de temperatura, no la primera que responde el walk.
+	rows := map[string]int{"board-temperature": 47, "switch-temperature": 53, "fan-state": 1}
+	if temp, ok := ParseMikrotikHealth(rows); !ok || temp != 53 {
+		t.Errorf("temp = %d/%v, want 53 (máximo de las filas de temperatura)", temp, ok)
+	}
+	// cpu-temperature gana aunque haya otra fila más caliente: es la lectura
+	// que /system health imprime como CPU.
+	conCpu := map[string]int{"cpu-temperature": 48, "switch-temperature": 61}
+	if temp, ok := ParseMikrotikHealth(conCpu); !ok || temp != 48 {
+		t.Errorf("temp = %d/%v, want 48 (la sonda nombrada manda)", temp, ok)
+	}
+	if _, ok := ParseMikrotikHealth(map[string]int{"fan-state": 1, "pcie-power": 12}); ok {
+		t.Error("una tabla sin ninguna fila de temperatura no da temperatura")
+	}
+	if _, ok := ParseMikrotikHealth(nil); ok {
+		t.Error("tabla vacía ok=false: la vital se queda en null (#441)")
+	}
+}
+
+// Las descripciones reales de los cuatro equipos de la flota que sirvieron de
+// muestra: dos MikroTik (un firmware y otro) y dos que no, para los que
+// preguntar la tabla costaría un timeout por poll.
+func TestDeclaresMikrotik(t *testing.T) {
+	for _, descr := range []string{
+		"RouterOS CRS305-1G-4S+ 7.25",
+		"RouterOS hEX",
+		"CSS610-8G-2S+ SwOS v2.21",
+	} {
+		if !declaresMikrotik(descr) {
+			t.Errorf("%q es MikroTik y se descartó", descr)
+		}
+	}
+	for _, descr := range []string{
+		"FN SWITCH 8 PRO",
+		"Netgear XS708T 8-Port 10-Gigabit Copper Smart Managed Pro Switch",
+		"Linux ds1821plus 5.2",
+		"",
+	} {
+		if declaresMikrotik(descr) {
+			t.Errorf("%q no es MikroTik y se caminaría su tabla", descr)
+		}
+	}
+}