Forráskód Böngészése

fix(routers): expose real partial vitals (#1569)

SNMP and external sources could already carry confirmed CPU or temperature readings, but the router DTO still marked vitals unavailable and the metrics writer discarded them. Resolve the partial readings once, persist only the confirmed values and render only the metrics that exist. No Netgear memory OIDs or vendor-specific polling is added.
Nacho 1 hónapja
szülő
commit
d98240d607

+ 3 - 3
app/src/components/RouterCard.tsx

@@ -96,9 +96,9 @@ export function RouterCard({ router, index = 0, className }: RouterCardProps) {
           {/* #441: sin vitals (switch SNMP/beacon) no se pintan ceros falsos */}
           {router.vitalsAvailable !== false && (
             <>
-              <MiniMetric icon={Cpu} value={`${router.cpu} %`} label="CPU" hot={router.hotMetric === 'cpu'} />
-              <MiniMetric icon={MemoryStick} value={`${router.ram} %`} label="RAM" hot={router.hotMetric === 'ram'} />
-              <MiniMetric icon={Thermometer} value={fmtTemp(router.temp, tempUnit)} label={t('common.temperature')} hot={router.hotMetric === 'temp'} />
+              {router.cpu !== null && <MiniMetric icon={Cpu} value={`${router.cpu} %`} label="CPU" hot={router.hotMetric === 'cpu'} />}
+              {router.ram !== null && <MiniMetric icon={MemoryStick} value={`${router.ram} %`} label="RAM" hot={router.hotMetric === 'ram'} />}
+              {router.temp !== null && <MiniMetric icon={Thermometer} value={fmtTemp(router.temp, tempUnit)} label={t('common.temperature')} hot={router.hotMetric === 'temp'} />}
             </>
           )}
           <MiniMetric icon={Users} value={String(router.clients)} label={t('common.clients')} />

+ 12 - 10
app/src/components/routers/FleetCard.tsx

@@ -276,16 +276,18 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
             </p>
           ) : (
             <>
-              <MetricRow icon={Cpu} label="CPU" value={`${router.cpu} %`} pct={router.cpu ?? 0} hot={router.hotMetric === 'cpu'} />
-              <MetricRow icon={MemoryStick} label={t('common.memory')} value={`${router.ram} %`} pct={router.ram ?? 0} hot={router.hotMetric === 'ram'} />
-              <MetricRow
-                icon={Thermometer}
-                label={t('common.temperature')}
-                value={fmtTemp(router.temp, tempUnit)}
-                pct={Math.min(100, ((router.temp ?? 0) / 90) * 100)}
-                hot={router.hotMetric === 'temp'}
-                title={router.hotMetric === 'temp' ? t('routers.tempThreshold', { value: fmtTemp(router.tempThreshold ?? 65, tempUnit) }) : undefined}
-              />
+              {router.cpu !== null && <MetricRow icon={Cpu} label="CPU" value={`${router.cpu} %`} pct={router.cpu ?? 0} hot={router.hotMetric === 'cpu'} />}
+              {router.ram !== null && <MetricRow icon={MemoryStick} label={t('common.memory')} value={`${router.ram} %`} pct={router.ram ?? 0} hot={router.hotMetric === 'ram'} />}
+              {router.temp !== null && (
+                <MetricRow
+                  icon={Thermometer}
+                  label={t('common.temperature')}
+                  value={fmtTemp(router.temp, tempUnit)}
+                  pct={Math.min(100, ((router.temp ?? 0) / 90) * 100)}
+                  hot={router.hotMetric === 'temp'}
+                  title={router.hotMetric === 'temp' ? t('routers.tempThreshold', { value: fmtTemp(router.tempThreshold ?? 65, tempUnit) }) : undefined}
+                />
+              )}
             </>
           )}
         </div>

+ 3 - 1
app/src/components/routers/RouterPerformance.tsx

@@ -89,6 +89,8 @@ export function RouterPerformance({ router, liveSeries, totalRamMb, usedRamMb }:
   // pero el tipo lo exige); se normaliza a 0 para el render defensivo.
   const current: Record<SeriesDef['key'], number> = { cpu: router.cpu ?? 0, ram: router.ram ?? 0, temp: router.temp ?? 0 }
   const captionByKey: Record<SeriesDef['key'], string> = { cpu: captions.cpu, ram: captions.ram, temp: captions.temp }
+  // #1568: una fuente con vitals parciales no dibuja como cero las ausentes.
+  const visibleSeries = SERIES.filter((s) => router[s.key] !== null)
   return (
     <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
       <div className="flex flex-wrap items-center justify-between gap-3">
@@ -102,7 +104,7 @@ export function RouterPerformance({ router, liveSeries, totalRamMb, usedRamMb }:
       </div>
 
       <div className="mt-4 space-y-4">
-        {SERIES.map((s, si) => (
+        {visibleSeries.map((s, si) => (
           <motion.div
             key={`${range}-${s.key}`}
             initial={reduce ? false : { opacity: 0, y: 10 }}

+ 12 - 13
server-go/internal/adapters/live.go

@@ -1551,18 +1551,10 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 		LatencyMs: p.latencyMs,
 	}
 	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)
-		}
-		// 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)
-		}
+		v := resolvePartialVitals(p)
+		r.CPU, r.Temp = v.cpu, v.temp
+		r.VitalsAvailable = bptr(v.available)
 	}
 	r.SnmpEnabled = p.cfg.SnmpEnabled
 	if p.selfExpose {
@@ -4566,10 +4558,17 @@ func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
 			Temp:      fptr(float64(p.temp)),
 			LatencyMs: p.latencyMs,
 		}
-		// #441: SNMP/pushers externos no tienen vitals reales; no se
-		// persisten ceros que luego pintan series planas.
+		// #441/#1568: sin lecturas no se persisten ceros falsos, pero una
+		// fuente SNMP/external con CPU 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.temp != nil {
+				row.Temp = fptr(float64(*v.temp))
+			}
 		}
 		if p.net != nil {
 			row.RxBps = p.net.RxBps

+ 28 - 0
server-go/internal/adapters/vitals.go

@@ -0,0 +1,28 @@
+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).
+type partialVitals struct {
+	cpu       *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 {
+		return out
+	}
+	if p.hasCpu {
+		cpu := p.cpu
+		out.cpu = &cpu
+	}
+	if p.hasTemp {
+		temp := p.temp
+		out.temp = &temp
+	}
+	out.available = out.cpu != nil || out.temp != nil
+	return out
+}

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

@@ -0,0 +1,90 @@
+package adapters
+
+import (
+	"context"
+	"testing"
+)
+
+// #1568: una fuente SNMP puede tener solo CPU o solo temperatura. La lectura
+// presente debe llegar al contrato y marcar las vitals como disponibles; las
+// ausentes siguen siendo nil para que la UI no invente valores.
+func TestBuildRouterExposesPartialSnmpVitals(t *testing.T) {
+	tests := []struct {
+		name              string
+		cpu, temp         int
+		hasCPU, hasTemp   bool
+		wantCPU, wantTemp *int
+		wantAvailable     bool
+	}{
+		{name: "cpu only", cpu: 37, hasCPU: true, wantCPU: intPtr(37), wantAvailable: true},
+		{name: "temp only", temp: 51, hasTemp: true, wantTemp: intPtr(51), wantAvailable: true},
+		{name: "cpu and temp", cpu: 22, temp: 48, hasCPU: true, hasTemp: true, wantCPU: intPtr(22), wantTemp: intPtr(48), wantAvailable: true},
+		{name: "no readings", cpu: 90, temp: 90, wantAvailable: false},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			l := NewLive(nil, nil, nil, nil)
+			p := &routerPolled{
+				cfg:      RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true},
+				cpu:      tc.cpu,
+				temp:     tc.temp,
+				hasCpu:   tc.hasCPU,
+				hasTemp:  tc.hasTemp,
+				polledAt: 1000,
+			}
+			r := l.buildRouter(p, nil)
+			if r.VitalsAvailable == nil || *r.VitalsAvailable != tc.wantAvailable {
+				t.Fatalf("VitalsAvailable=%v, esperaba %v", r.VitalsAvailable, tc.wantAvailable)
+			}
+			if !equalOptionalInt(r.CPU, tc.wantCPU) || !equalOptionalInt(r.Temp, tc.wantTemp) || r.RAM != nil {
+				t.Fatalf("vitals: cpu=%v (quiere %v) ram=%v temp=%v (quiere %v)", r.CPU, tc.wantCPU, r.RAM, r.Temp, tc.wantTemp)
+			}
+		})
+	}
+}
+
+// #1568: el histórico usa los mismos flags que la tarjeta. Antes limpiaba CPU
+// y temperatura para cualquier fuente SNMP aunque el poller sí las tuviera.
+func TestMetricsRowsKeepPartialSnmpVitals(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	l.lastPolled["sw1"] = &routerPolled{
+		cfg:      RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true},
+		cpu:      37,
+		temp:     51,
+		hasCpu:   true,
+		hasTemp:  true,
+		polledAt: 1000,
+	}
+	l.lastPolled["sw2"] = &routerPolled{
+		cfg:      RouterConfig{ID: "sw2", Host: "192.168.1.11", SnmpEnabled: true},
+		temp:     49,
+		hasTemp:  true,
+		polledAt: 1000,
+	}
+
+	rows := l.GetMetricsRows(context.Background())
+	if len(rows) != 2 {
+		t.Fatalf("rows=%d, esperaba 2", len(rows))
+	}
+	byID := map[string]MetricsRow{}
+	for _, row := range rows {
+		byID[row.RouterID] = row
+	}
+	row := byID["sw1"]
+	if row.CPU == nil || *row.CPU != 37 || row.Temp == nil || *row.Temp != 51 || row.RAM != nil {
+		t.Fatalf("sw1: cpu=%v ram=%v temp=%v", row.CPU, row.RAM, row.Temp)
+	}
+	row = byID["sw2"]
+	if row.CPU != nil || row.Temp == nil || *row.Temp != 49 || row.RAM != nil {
+		t.Fatalf("sw2: cpu=%v ram=%v temp=%v", row.CPU, row.RAM, row.Temp)
+	}
+}
+
+func intPtr(v int) *int { return &v }
+
+func equalOptionalInt(a, b *int) bool {
+	if a == nil || b == nil {
+		return a == nil && b == nil
+	}
+	return *a == *b
+}