Przeglądaj źródła

fix(routers): keep the vitals an external pusher confirmed

A pusher that reports CPU, memory and temperature had all three published as
null: #441 nulls the vitals of every SNMP or external source, and the
hasCpu/hasTemp flags that rescue them were only set by the SNMP poller.

Mark what the payload actually confirms, and keep the anti-flicker cache
inside the same source: extrasCache is keyed by router ID alone, so a payload
without a system section could inherit the vitals the native agent confirmed
earlier and publish them as its own. Memory is only confirmed when there is a
usage figure to derive it from, since a payload carrying Mem.Total alone
rendered as 100 percent used.

Co-authored-by: Bann-DEV <hef.fangyuan@gmail.com>
Bann-DEV 1 miesiąc temu
rodzic
commit
2077bb2e53

+ 36 - 8
server-go/internal/adapters/agent.go

@@ -651,6 +651,17 @@ func injectPortRates(ports []EthPort, rates map[string]probe.IfRate) {
 	}
 }
 
+// agentSourceClass: la documentación de probe.Payload.Kind declara "" y
+// "native" como el mismo agente nativo, así que el cache de system los trata
+// como una sola fuente; cada kind restante (external, netgrip…) es la suya
+// propia.
+func agentSourceClass(kind string) string {
+	if kind == "" || kind == "native" {
+		return "native"
+	}
+	return kind
+}
+
 // polledFromAgent convierte el payload del agente en el routerPolled del
 // pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
 // que pollRouter: sección ausente en el payload = sonda fallida → conserva
@@ -681,10 +692,10 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 			l.mu.Unlock()
 		}
 		if sd.CPU != nil {
-			out.cpu = *sd.CPU
+			out.cpu, out.hasCpu = *sd.CPU, true
 		}
 		if sd.Temp != nil {
-			out.temp = *sd.Temp
+			out.temp, out.hasTemp = *sd.Temp, true
 		}
 		out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
 		out.latencyMs = sd.LatencyMs
@@ -693,25 +704,38 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		out.brMac = sd.BridgeMAC
 		out.flash = sd.Flash
 		out.firmwareAvailable = sd.FirmwareAvailable
-	} else if cached != nil && cached.system != nil {
+	} else if cached != nil && cached.system != nil && cached.systemKind == agentSourceClass(p.Kind) {
 		// #441: push event-driven (wireless-only) sin system → conserva las
 		// últimas vitals buenas cacheadas en vez de pintar ceros falsos.
 		// Solo vitals/uptime: net/latencia/backhaul no se reciclan (evita
 		// duplicar tráfico con muestras viejas).
+		//
+		// Solo dentro del mismo kind: extrasCache se clave únicamente por ID,
+		// así que un payload external sin sección system heredaría las vitals
+		// del agente nativo que alimentó al router antes. Como #1724 marca lo
+		// que trae el payload de confirmado, esa herencia se publicaría como
+		// lectura propia y acabaría en el histórico.
 		sd := cached.system
 		if sd.CPU != nil {
-			out.cpu = *sd.CPU
+			out.cpu, out.hasCpu = *sd.CPU, true
 		}
 		if sd.Temp != nil {
-			out.temp = *sd.Temp
+			out.temp, out.hasTemp = *sd.Temp, true
 		}
 		if sd.SysInfo != nil {
 			sysInfo = sd.SysInfo
 		}
 	}
 	mem := sysInfo.Memory
-	if mem.Total > 0 {
+	// Con solo Mem.Total y ninguna cifra de uso no hay nada que derivar:
+	// memUsagePct caería a "available = free + buffered = 0" y reportaría un
+	// 100 % inventado. Eso es memoria desconocida, no memoria llena.
+	if mem.Total > 0 && memUsageKnown(mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used) {
 		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
+		// La memoria del payload es una lectura confirmada (los pushers de
+		// RouterOS/AsusWRT la derivan de free/memory), no un hueco que haya
+		// que pintar a cero.
+		out.hasRam = true
 	}
 	out.sysInfo = sysInfo
 	out.ram = ramPct
@@ -900,15 +924,19 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	// #441: el cache de system guarda la última sección BUENA (un push
 	// wireless-only no la invalida).
 	sysSnap := p.Data.System
-	if sysSnap == nil && cached != nil {
+	sysSnapKind := ""
+	if kind := agentSourceClass(p.Kind); sysSnap != nil {
+		sysSnapKind = kind
+	} else if cached != nil && cached.systemKind == kind {
 		sysSnap = cached.system
+		sysSnapKind = cached.systemKind
 	}
 	lldpSnap := p.Data.Lldp
 	if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
 		lldpSnap = cached.lldp // conserva la última sección buena (#489)
 	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
-		wireless: out.wireless, fdb: out.fdb, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, lldp: lldpSnap,
+		wireless: out.wireless, fdb: out.fdb, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
 		clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
 	l.mu.Unlock()
 

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

@@ -105,7 +105,11 @@ type routerPolled struct {
 	// 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
+	hasCpu bool
+	// hasRam: mismo contrato para la RAM. Solo una fuente que declara memoria
+	// (Mem.Total>0 en el payload del agente/pusher) la pone; un SNMP sin
+	// lectura de memoria sigue sirviendo nil.
+	hasRam   bool
 	sysDescr string
 	// sysName (#1256): hostname que el usuario define en el equipo; para
 	// SNMP alimenta el Name visible de la unidad en flota.
@@ -219,6 +223,10 @@ type extrasSnapshot struct {
 	// Los pushes event-driven (wireless-only) van sin ella; sin este cache
 	// las vitales del router parpadeaban a 0 entre pushes completos.
 	system *probe.SystemData
+	// systemKind: el agent kind (probe.Payload.Kind) que escribió system. El
+	// cache se clave solo por ID, y una fuente sin sección system no debe
+	// heredar las vitales que confirmó otra fuente del mismo router.
+	systemKind string
 	// lldp (#489): última sección lldp del payload. Mismo anti-parpadeo:
 	// los pushes event-driven van sin ella y la topología no debe perder
 	// los switches managed entre pushes completos.
@@ -1544,8 +1552,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	for _, h := range history {
 		sparkline = append(sparkline, h.down)
 	}
-	// #441: SNMP y pushers externos no pueden reportar CPU/RAM/temp. Se marca
-	// el router y las vitals van a null (la UI no pinta ceros falsos).
+	// #441: SNMP y pushers externos no siempre pueden reportar CPU/RAM/temp.
+	// Se marca el router y las vitals van a null (la UI no pinta ceros falsos);
+	// las lecturas que la fuente sí confirma (hasCpu/hasRam/hasTemp) se conservan.
 	noVitals := p.cfg.SnmpEnabled || p.agentKind == "external"
 	r := Router{
 		ID: p.cfg.ID, Name: name, Model: model, ModelShort: model,
@@ -1558,7 +1567,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if noVitals {
 		r.CPU, r.RAM, r.Temp = nil, nil, nil
 		v := resolvePartialVitals(p)
-		r.CPU, r.Temp = v.cpu, v.temp
+		r.CPU, r.RAM, r.Temp = v.cpu, v.ram, v.temp
 		r.VitalsAvailable = bptr(v.available)
 	}
 	r.SnmpEnabled = p.cfg.SnmpEnabled
@@ -4563,13 +4572,17 @@ func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
 			LatencyMs: p.latencyMs,
 		}
 		// #441/#1568: sin lecturas no se persisten ceros falsos, pero una
-		// fuente SNMP/external con CPU o temperatura confirmada sí las conserva.
+		// fuente SNMP/external con CPU, memoria o temperatura confirmada sí
+		// las conserva.
 		if p.cfg.SnmpEnabled || p.agentKind == "external" {
 			v := resolvePartialVitals(p)
 			row.CPU, row.RAM, row.Temp = nil, nil, nil
 			if v.cpu != nil {
 				row.CPU = fptr(float64(*v.cpu))
 			}
+			if v.ram != nil {
+				row.RAM = fptr(float64(*v.ram))
+			}
 			if v.temp != nil {
 				row.Temp = fptr(float64(*v.temp))
 			}

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

@@ -37,6 +37,16 @@ func memUsagePct(total, free, buffered, cached, available, usedProc float64) int
 	return int(math.Round(used / total * 100))
 }
 
+// memUsageKnown: hay alguna cifra de uso de la que derivar el porcentaje.
+// memUsagePct no puede distinguirlas de un payload que solo trae el total: con
+// free/buffered/cached/available/used todos a 0 cae a "available = 0 →
+// used = total" y devuelve 100. Para un pusher parcial o malformado eso es
+// memoria desconocida, no memoria llena, y publicarlo como confirmado (ver
+// polledFromAgent) además la persiste en el histórico.
+func memUsageKnown(free, buffered, cached, available, used float64) bool {
+	return free > 0 || buffered > 0 || cached > 0 || available > 0 || used > 0
+}
+
 // memUsedBytes: mismos criterios que memUsagePct pero en bytes, para que el
 // server envíe la cifra de uso autoritativa (#1501): derivarla en el front
 // desde el porcentaje redondeado (pct × total) acumula hasta ~2% de error

+ 7 - 3
server-go/internal/adapters/vitals.go

@@ -1,15 +1,15 @@
 package adapters
 
 // partialVitals contiene solo lecturas que la fuente ha confirmado. Los flags
-// hasCpu/hasTemp distinguen un cero real de un OID ausente (#1528, #1568).
+// hasCpu/hasTemp/hasRam distinguen un cero real de un OID ausente (#1528, #1568).
 type partialVitals struct {
 	cpu       *int
+	ram       *int
 	temp      *int
 	available bool
 }
 
 // resolvePartialVitals evita repetir la regla en la tarjeta y en el histórico.
-// No deduce RAM: una fuente sin lectura de memoria debe seguir sirviendo nil.
 func resolvePartialVitals(p *routerPolled) partialVitals {
 	var out partialVitals
 	if p == nil {
@@ -19,10 +19,14 @@ func resolvePartialVitals(p *routerPolled) partialVitals {
 		cpu := p.cpu
 		out.cpu = &cpu
 	}
+	if p.hasRam {
+		ram := p.ram
+		out.ram = &ram
+	}
 	if p.hasTemp {
 		temp := p.temp
 		out.temp = &temp
 	}
-	out.available = out.cpu != nil || out.temp != nil
+	out.available = out.cpu != nil || out.ram != nil || out.temp != nil
 	return out
 }

+ 185 - 0
server-go/internal/adapters/vitals_test.go

@@ -3,6 +3,8 @@ package adapters
 import (
 	"context"
 	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
 )
 
 // #1568: una fuente SNMP puede tener solo CPU o solo temperatura. La lectura
@@ -80,6 +82,189 @@ func TestMetricsRowsKeepPartialSnmpVitals(t *testing.T) {
 	}
 }
 
+// Un pusher externo (routeros/asuswrt) declara CPU, memoria y temperatura en
+// el payload: son lecturas confirmadas, no huecos que pintar a cero. Antes solo
+// el sondeo SNMP ponía los flags, así que el null de #441 se llevaba las tres
+// vitals del equipo alimentado por pusher.
+func TestBuildRouterKeepsConfirmedPusherVitals(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "crs305", Host: "192.168.2.15", Name: "CRS305", Type: "external", AgentOnly: true}
+	cpu, temp := 1, 48
+	si := &probe.SysInfo{Uptime: 253000}
+	si.Memory.Total = 536870912
+	si.Memory.Free = 446193664
+	payload := &probe.Payload{
+		Router: "crs305", Ts: 1, Kind: "external", Version: "0.1.1",
+		Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: si}},
+	}
+
+	p := l.polledFromAgent(cfg, payload)
+	r := l.buildRouter(p, nil)
+	if r.CPU == nil || *r.CPU != cpu {
+		t.Fatalf("CPU=%v, esperaba %d", r.CPU, cpu)
+	}
+	if r.Temp == nil || *r.Temp != temp {
+		t.Fatalf("Temp=%v, esperaba %d", r.Temp, temp)
+	}
+	if r.RAM == nil || *r.RAM != p.ram {
+		t.Fatalf("RAM=%v, esperaba %d (Mem.Total/Free del payload)", r.RAM, p.ram)
+	}
+	if r.VitalsAvailable == nil || !*r.VitalsAvailable {
+		t.Fatalf("VitalsAvailable=%v, esperaba true", r.VitalsAvailable)
+	}
+
+	l.lastPolled[cfg.ID] = p
+	rows := l.GetMetricsRows(context.Background())
+	if len(rows) != 1 {
+		t.Fatalf("rows=%d, esperaba 1", len(rows))
+	}
+	row := rows[0]
+	if row.CPU == nil || *row.CPU != float64(cpu) || row.Temp == nil || *row.Temp != float64(temp) {
+		t.Fatalf("histórico: cpu=%v temp=%v", row.CPU, row.Temp)
+	}
+	if row.RAM == nil || *row.RAM != float64(p.ram) {
+		t.Fatalf("histórico: ram=%v, esperaba %d", row.RAM, p.ram)
+	}
+}
+
+// #441 sigue vivo: un beacon externo sin sección system no inventa vitals.
+func TestBuildRouterPusherSinSystemSigueSinVitals(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "beacon", Host: "192.168.2.99", Name: "Beacon", Type: "external", AgentOnly: true}
+	p := l.polledFromAgent(cfg, &probe.Payload{Router: "beacon", Ts: 1, Kind: "external"})
+	r := l.buildRouter(p, nil)
+	if r.CPU != nil || r.RAM != nil || r.Temp != nil {
+		t.Fatalf("sin sección system las vitals siguen nil: cpu=%v ram=%v temp=%v", r.CPU, r.RAM, r.Temp)
+	}
+	if r.VitalsAvailable == nil || *r.VitalsAvailable {
+		t.Fatalf("VitalsAvailable=%v, esperaba false", r.VitalsAvailable)
+	}
+}
+
+// extrasCache se clave solo por ID: reasignar un router de un agente nativo a
+// un pusher que no trae seccion system no debe publicar las vitales que
+// confirmo la fuente anterior. Sin la etiqueta de origen, #1724 las marcaria
+// como lecturas propias del pusher y acabarian tambien en el historico.
+func TestBuildRouterDoesNotCrossTheAgentSourceBoundary(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "rt-ax92u", Host: "192.168.3.6", Name: "AX92U", Type: "external", AgentOnly: true}
+	cpu, temp := 7, 61
+	nativeSys := &probe.SysInfo{Uptime: 100000}
+	nativeSys.Memory.Total = 536870912
+	nativeSys.Memory.Free = 400000000
+	l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 1, Kind: "native", Version: "3.0.30",
+		Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: nativeSys}},
+	})
+
+	// El router pasa a un pusher externo cuyo payload no trae seccion system
+	// (REST, o un scraper que todavia no llega a esa parte).
+	external := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 2, Kind: "external", Version: "0.1.1",
+	})
+	if external.cpu != 0 || external.temp != 0 || external.ram != 0 {
+		t.Fatalf("vitals heredadas de la otra fuente: cpu=%d temp=%d ram=%d", external.cpu, external.temp, external.ram)
+	}
+	if external.hasCpu || external.hasTemp || external.hasRam {
+		t.Fatalf("los flags de confirmacion no pueden venir de otra fuente: %+v", external)
+	}
+	r := l.buildRouter(external, nil)
+	if r.CPU != nil || r.Temp != nil || r.RAM != nil {
+		t.Fatalf("cpu=%v temp=%v ram=%v, esperaba nil en la tarjeta del router", r.CPU, r.Temp, r.RAM)
+	}
+	if r.VitalsAvailable == nil || *r.VitalsAvailable {
+		t.Fatalf("VitalsAvailable=%v, esperaba false", r.VitalsAvailable)
+	}
+
+	l.lastPolled[cfg.ID] = external
+	rows := l.GetMetricsRows(context.Background())
+	if len(rows) != 1 {
+		t.Fatalf("rows=%d, esperaba 1", len(rows))
+	}
+	if rows[0].CPU != nil || rows[0].Temp != nil || rows[0].RAM != nil {
+		t.Fatalf("historico con vitales de otra fuente: cpu=%v temp=%v ram=%v",
+			rows[0].CPU, rows[0].Temp, rows[0].RAM)
+	}
+
+	// La proteccion no es "un externo nunca tiene nada": su propia seccion
+	// system se publica, y cuando el propio externo confirma vitales el
+	// antiparpadeo #441 sigue reciclándolas dentro de la misma fuente.
+	boardOnly := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 3, Kind: "external", Version: "0.1.1",
+		Data: probe.PayloadData{System: &probe.SystemData{Board: &probe.BoardInfo{Model: "CRS305-1G-4S+"}}},
+	})
+	if rb := l.buildRouter(boardOnly, nil); rb.Model != "CRS305-1G-4S+" || rb.CPU != nil {
+		t.Fatalf("board propio del externo: model=%q cpu=%v", rb.Model, rb.CPU)
+	}
+	confirmed := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 4, Kind: "external", Version: "0.1.1",
+		Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu}},
+	})
+	if !confirmed.hasCpu || confirmed.cpu != cpu {
+		t.Fatalf("cpu=%d hasCpu=%v, el pusher confirmó 7", confirmed.cpu, confirmed.hasCpu)
+	}
+	recycled := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 5, Kind: "external", Version: "0.1.1",
+	})
+	if !recycled.hasCpu || recycled.cpu != cpu {
+		t.Fatalf("cpu=%d hasCpu=%v, dentro de la misma fuente el antiparpadeo #441 debe seguir vivo",
+			recycled.cpu, recycled.hasCpu)
+	}
+}
+
+// Un payload que solo trae Mem.Total, sin ninguna cifra de uso, no permite
+// derivar nada: memUsagePct cae a "available = free + buffered = 0" y daria un
+// 100 % de RAM inventado. Memoria desconocida, no memoria llena. Las demas
+// vitales del mismo payload siguen confirmadas.
+func TestBuildRouterTotalOnlyMemoryIsUnknown(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "bbox", Host: "192.168.1.1", Name: "Bbox", Type: "external", AgentOnly: true}
+	cpu, temp := 3, 40
+	totalOnly := &probe.SysInfo{Uptime: 1000}
+	totalOnly.Memory.Total = 100
+	p := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 1, Kind: "external", Version: "0.1.1",
+		Data: probe.PayloadData{System: &probe.SystemData{CPU: &cpu, Temp: &temp, SysInfo: totalOnly}},
+	})
+	if p.ram != 0 || p.hasRam {
+		t.Fatalf("ram=%d hasRam=%v, con solo el total la memoria es desconocida", p.ram, p.hasRam)
+	}
+	r := l.buildRouter(p, nil)
+	if r.RAM != nil {
+		t.Fatalf("RAM=%v, esperaba nil (no 100)", r.RAM)
+	}
+	if r.CPU == nil || *r.CPU != cpu || r.Temp == nil || *r.Temp != temp {
+		t.Fatalf("cpu=%v temp=%v, las otras vitales confirmadas no se tocan", r.CPU, r.Temp)
+	}
+	if r.VitalsAvailable == nil || !*r.VitalsAvailable {
+		t.Fatalf("VitalsAvailable=%v, esperaba true", r.VitalsAvailable)
+	}
+
+	l.lastPolled[cfg.ID] = p
+	rows := l.GetMetricsRows(context.Background())
+	if len(rows) != 1 {
+		t.Fatalf("rows=%d, esperaba 1", len(rows))
+	}
+	if rows[0].RAM != nil {
+		t.Fatalf("historico: ram=%v, esperaba NULL", *rows[0].RAM)
+	}
+	if rows[0].CPU == nil || rows[0].Temp == nil {
+		t.Fatalf("historico: cpu=%v temp=%v, esperando los valores confirmados", rows[0].CPU, rows[0].Temp)
+	}
+
+	// Con una sola cifra de uso ya es derivable: free = 40 de 100 es 60 %.
+	WithFree := &probe.SysInfo{Uptime: 1000}
+	WithFree.Memory.Total = 100
+	WithFree.Memory.Free = 40
+	p2 := l.polledFromAgent(cfg, &probe.Payload{
+		Router: cfg.ID, Ts: 2, Kind: "external", Version: "0.1.1",
+		Data: probe.PayloadData{System: &probe.SystemData{SysInfo: WithFree}},
+	})
+	if !p2.hasRam || p2.ram != 60 {
+		t.Fatalf("ram=%d hasRam=%v, esperaba 60 confirmado", p2.ram, p2.hasRam)
+	}
+}
+
 func intPtr(v int) *int { return &v }
 
 func equalOptionalInt(a, b *int) bool {