Browse Source

feat(snmp): CPU and temperature for Netgear FastPath switches (private MIB 4526) (#1528)

Closes #1526.

PollNetgearVitals walks the FastPath private MIB (4526.11): CPU is the 5s-window sum of the per-process utilization table capped at 100 (no total scalar exists), temperature is the max across boxServices sensors, and RAM stays null because the MIB has no total-memory scalar. Wired after PollMikrotikTemp with the same best-effort semantics (walks that come back empty leave vitals as-is), and buildRouter gets a hasCpu flag so the #441 SNMP nulls do not overwrite the reading.

Co-authored-by: Bann-DEV <bann.dev@gmail.com>
Bann-DEV 1 month ago
parent
commit
153d034fce

+ 10 - 1
server-go/internal/adapters/live.go

@@ -101,7 +101,11 @@ type routerPolled struct {
 	// #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
+	hasTemp bool
+	// hasCpu: mismo contrato que hasTemp para la CPU de los switches SNMP
+	// (tabla de procesos Netgear FastPath): sin bandera, el null de #441
+	// pisaría la lectura real.
+	hasCpu   bool
 	sysDescr string
 	// sysName (#1256): hostname que el usuario define en el equipo; para
 	// SNMP alimenta el Name visible de la unidad en flota.
@@ -1554,6 +1558,11 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 		if p.hasTemp {
 			r.Temp = iptr(p.temp)
 		}
+		// Netgear FastPath: misma canalía para la CPU leída de la tabla de
+		// procesos del agente privado.
+		if p.hasCpu {
+			r.CPU = iptr(p.cpu)
+		}
 	}
 	r.SnmpEnabled = p.cfg.SnmpEnabled
 	if p.selfExpose {

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

@@ -51,6 +51,10 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 	// 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)
+	// 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)
 	// #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.
@@ -206,6 +210,12 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		p.sysName = sysInfo.Name
 	}
 	p.temp, p.hasTemp = mikroTemp, hasTemp
+	if !p.hasTemp && hasNgTemp {
+		p.temp, p.hasTemp = ngTemp, true
+	}
+	if hasNgCpu {
+		p.cpu, p.hasCpu = ngCpu, true
+	}
 	l.mu.Lock()
 	l.snmpLastPoll[cfg.ID] = now
 	l.mu.Unlock()

+ 104 - 0
server-go/internal/snmp/netgearVitals.go

@@ -0,0 +1,104 @@
+// netgearVitals.go — vitales (CPU y temperatura) de switches Netgear
+// FastPath (XS708T, GS728TXP/S3300 y familia) vía su MIB privada
+// (NETGEAR enterprise 4526, ng700smartswitch = 4526.11):
+//
+//   - agentSwitchCpuProcessPercentageUtilization
+//     1.3.6.1.4.1.4526.11.1.1.4.8.1.3.<idx>: STRING por proceso con tres
+//     ventanas, "    5 Sec (  0.19%)   60 Sec (  0.16%)  300 Sec (  0.15%)".
+//     El total del equipo es la suma por proceso (no hay tarea idle en la
+//     tabla ni escalar de total).
+//   - boxServicesTempSensorTemperature
+//     1.3.6.1.4.1.4526.11.43.1.8.1.5.<idx>: Integer32 en °C por sensor; con
+//     varios sensores se reporta el máximo (el punto caliente).
+//
+// No hay escalar de memoria TOTAL en la MIB (solo MemFree/MemAvailable), así
+// que el RAM queda a null antes que inventar un porcentaje.
+package snmp
+
+import (
+	"regexp"
+	"strconv"
+
+	g "github.com/gosnmp/gosnmp"
+)
+
+const (
+	// OidNetgearCpuUtil: columna de utilización por proceso (string 5/60/300s).
+	OidNetgearCpuUtil = ".1.3.6.1.4.1.4526.11.1.1.4.8.1.3"
+	// OidNetgearTempSensor: columna de temperatura por sensor (°C).
+	OidNetgearTempSensor = ".1.3.6.1.4.1.4526.11.43.1.8.1.5"
+)
+
+// cpuUtilRe casa la primera ventana ("5 Sec (  0.19%)") del string por
+// proceso; es la misma que pinta el panel web del switch como instantánea.
+var cpuUtilRe = regexp.MustCompile(`5\s+Sec\s*\(\s*([0-9]+(?:\.[0-9]+)?)\s*%\)`)
+
+// ParseNetgearCpuUtil suma la utilización de 5s de cada proceso: sin tarea
+// idle en la tabla, la suma es el total del equipo. Strings inparseables se
+// ignoran (firmwares que cambian el formato no deben romper el sondeo).
+func ParseNetgearCpuUtil(vals []string) (cpu int, ok bool) {
+	total := 0.0
+	seen := 0
+	for _, v := range vals {
+		m := cpuUtilRe.FindStringSubmatch(v)
+		if m == nil {
+			continue
+		}
+		f, err := strconv.ParseFloat(m[1], 64)
+		if err != nil {
+			continue
+		}
+		total += f
+		seen++
+	}
+	if seen == 0 {
+		return 0, false
+	}
+	pct := int(total + 0.5)
+	if pct > 100 {
+		pct = 100
+	}
+	return pct, true
+}
+
+// ParseNetgearTemps devuelve el máximo de los sensores (punto caliente):
+// con dos sensores (CPU y chasis) el que manda para alertas es el mayor.
+func ParseNetgearTemps(vals []int) (temp int, ok bool) {
+	max := 0
+	for _, v := range vals {
+		if v > max {
+			max = v
+		}
+		ok = true
+	}
+	return max, ok
+}
+
+// PollNetgearVitals lee CPU y temperatura del agente FastPath. Un switch sin
+// estos árboles (otra familia) devuelve ok=false en ambos y el caller
+// conserva sus vitales a null, como hoy.
+func PollNetgearVitals(s *g.GoSNMP) (cpu int, okCpu bool, temp int, okTemp bool) {
+	if s == nil {
+		return 0, false, 0, false
+	}
+	if pdus, err := walkSafe(s, OidNetgearCpuUtil); err == nil {
+		vals := make([]string, 0, len(pdus))
+		for _, p := range pdus {
+			vals = append(vals, stringVal(p))
+		}
+		cpu, okCpu = ParseNetgearCpuUtil(vals)
+	}
+	if pdus, err := walkSafe(s, OidNetgearTempSensor); err == nil {
+		vals := make([]int, 0, len(pdus))
+		for _, p := range pdus {
+			// mikrotikTempFromPDU es el conversor genérico PDU numérica→int
+			// del paquete (tipos + NoSuchObject); el nombre viene de su
+			// primer usuario, no de su alcance.
+			if v, ok := mikrotikTempFromPDU(p); ok {
+				vals = append(vals, v)
+			}
+		}
+		temp, okTemp = ParseNetgearTemps(vals)
+	}
+	return cpu, okCpu, temp, okTemp
+}

+ 47 - 0
server-go/internal/snmp/netgearVitals_test.go

@@ -0,0 +1,47 @@
+// netgearVitals_test.go — parsers de los vitales Netgear FastPath con
+// muestras reales capturadas de un XS708T (firmware 7.0.0.24).
+package snmp
+
+import "testing"
+
+func TestParseNetgearCpuUtil(t *testing.T) {
+	vals := []string{
+		"    5 Sec (  0.19%)   60 Sec (  0.16%)  300 Sec (  0.15%) ",
+		"    5 Sec (  0.00%)   60 Sec (  0.18%)  300 Sec (  0.23%) ",
+		"    5 Sec (  5.75%)   60 Sec (  5.39%)  300 Sec (  5.38%) ",
+		"    5 Sec (  1.34%)   60 Sec (  0.22%)  300 Sec (  0.44%) ",
+	}
+	cpu, ok := ParseNetgearCpuUtil(vals)
+	if !ok {
+		t.Fatal("ok = false, want true con strings válidos")
+	}
+	// 0.19+0.00+5.75+1.34 = 7.28 → redondeo 7.
+	if cpu != 7 {
+		t.Fatalf("cpu = %d, want 7 (suma de la ventana de 5s)", cpu)
+	}
+}
+
+func TestParseNetgearCpuUtilGarbage(t *testing.T) {
+	if cpu, ok := ParseNetgearCpuUtil([]string{"firmware nuevo sin formato", ""}); ok || cpu != 0 {
+		t.Fatalf("formato inparseable debe dar (0,false), tuve (%d,%v)", cpu, ok)
+	}
+}
+
+func TestParseNetgearCpuUtilCapsAt100(t *testing.T) {
+	vals := []string{"5 Sec ( 60.0%)", "5 Sec ( 55.0%)"}
+	cpu, ok := ParseNetgearCpuUtil(vals)
+	if !ok || cpu != 100 {
+		t.Fatalf("cpu = %d/%v, want 100 techado", cpu, ok)
+	}
+}
+
+func TestParseNetgearTemps(t *testing.T) {
+	// XS708T: dos sensores, 48 y 56 °C; el punto caliente manda.
+	temp, ok := ParseNetgearTemps([]int{48, 56})
+	if !ok || temp != 56 {
+		t.Fatalf("temp = %d/%v, want 56 (máximo de sensores)", temp, ok)
+	}
+	if _, ok := ParseNetgearTemps(nil); ok {
+		t.Fatal("sin sensores ok debe ser false")
+	}
+}