Переглянути джерело

fix(agent): report RAM usage excluding reclaimable cache (#513) (#516)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 місяців тому
батько
коміт
1a3cb193ae

+ 7 - 0
agent/probe/local.go

@@ -154,6 +154,13 @@ func (p *Prober) probeSystem(ctx context.Context) *SystemData {
 	if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" {
 		var si SysInfo
 		if err := json.Unmarshal([]byte(out), &si); err == nil {
+			// ubus system info no expone la caché de ficheros (Cached), que
+			// la fórmula de uso clásica (total-free-buffers-cached) necesita
+			// para no contar RAM reclamable como usada (#513). /proc/meminfo
+			// local la da; fallback silencioso si no está (host sin proc).
+			if cached := readMeminfoCachedKB(); cached > 0 {
+				si.Memory.Cached = float64(cached) * 1024 // ubus va en bytes
+			}
 			sd.SysInfo = &si
 			any = true
 		}

+ 40 - 0
agent/probe/meminfo.go

@@ -0,0 +1,40 @@
+// meminfo.go — lectura local de /proc/meminfo en el agente (#513).
+//
+// ubus system info no expone la caché de ficheros; la fórmula de uso clásica
+// (usado = total - free - buffers - cached) la necesita para no contar RAM
+// reclamable como consumida. El agente corre EN el router: /proc/meminfo
+// siempre está. Fuera de OpenWrt (hosts de desarrollo/tests) la lectura
+// falla y el agente simplemente no rellena Cached (fallback del servidor).
+package probe
+
+import (
+	"os"
+	"strconv"
+	"strings"
+)
+
+// readMeminfoCachedKB devuelve el campo Cached de /proc/meminfo en kB, o 0
+// si el fichero no existe o no se puede leer.
+func readMeminfoCachedKB() int64 {
+	data, err := os.ReadFile("/proc/meminfo")
+	if err != nil {
+		return 0
+	}
+	return parseMeminfoCachedKB(string(data))
+}
+
+// parseMeminfoCachedKB extrae "Cached: N kB" del contenido de /proc/meminfo.
+func parseMeminfoCachedKB(data string) int64 {
+	for _, line := range strings.Split(data, "\n") {
+		if !strings.HasPrefix(line, "Cached:") {
+			continue
+		}
+		fields := strings.Fields(line)
+		if len(fields) >= 2 {
+			if n, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
+				return n
+			}
+		}
+	}
+	return 0
+}

+ 23 - 0
agent/probe/meminfo_test.go

@@ -0,0 +1,23 @@
+package probe
+
+import "testing"
+
+func TestParseMeminfoCachedKB(t *testing.T) {
+	fixture := `MemTotal:         414264 kB
+MemFree:           45780 kB
+MemAvailable:      88088 kB
+Buffers:               0 kB
+Cached:            90464 kB
+SwapCached:            0 kB
+SReclaimable:      14356 kB
+`
+	if got := parseMeminfoCachedKB(fixture); got != 90464 {
+		t.Fatalf("Cached: got %d, esperado 90464", got)
+	}
+	if got := parseMeminfoCachedKB("MemTotal: 1 kB\n"); got != 0 {
+		t.Fatalf("sin Cached debería dar 0, got %d", got)
+	}
+	if got := parseMeminfoCachedKB("Cached: 123 kB"); got != 123 {
+		t.Fatalf("solo línea Cached: %d", got)
+	}
+}

+ 4 - 0
agent/probe/probe.go

@@ -135,6 +135,10 @@ type SysInfo struct {
 		Free      float64 `json:"free"`
 		Buffered  float64 `json:"buffered"`
 		Available float64 `json:"available"`
+		// Cached: caché de ficheros (Cached de /proc/meminfo). ubus system
+		// info no la trae; el agente local la rellena para que el servidor
+		// calcule el uso excluyendo RAM reclamable (#513).
+		Cached float64 `json:"cached,omitempty"`
 	} `json:"memory"`
 }
 

+ 1 - 6
server-go/internal/adapters/agent.go

@@ -12,7 +12,6 @@ package adapters
 
 import (
 	"fmt"
-	"math"
 	"strings"
 	"sync"
 	"time"
@@ -515,11 +514,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	mem := sysInfo.Memory
 	if mem.Total > 0 {
-		avail := mem.Available
-		if avail == 0 {
-			avail = mem.Free + mem.Buffered
-		}
-		ramPct = int(math.Round((mem.Total - avail) / mem.Total * 100))
+		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available)
 	}
 	out.sysInfo = sysInfo
 	out.ram = ramPct

+ 3 - 6
server-go/internal/adapters/live.go

@@ -935,15 +935,12 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, luci: luciGood, vlans: vlansGood}
 	l.mu.Unlock()
 
-	// Uso real de RAM como en la UI del router: used = total − available
+	// Uso de RAM: #513 (con Cached del agente, fórmula clásica sin caché
+	// reclamable; sin Cached, MemAvailable). Ver memUsagePct.
 	mem := sysInfo.Memory
 	ramPct := 0
 	if mem.Total > 0 {
-		avail := mem.Available
-		if avail == 0 {
-			avail = mem.Free + mem.Buffered
-		}
-		ramPct = int(math.Round((mem.Total - avail) / mem.Total * 100))
+		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available)
 	}
 
 	isGw := gw != nil && cfg.ID == gw.ID

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

@@ -0,0 +1,35 @@
+// mem.go — cálculo del uso de RAM de un router a partir de los campos de
+// memoria (issue #513).
+package adapters
+
+import "math"
+
+// memUsagePct devuelve el % de RAM en uso.
+//
+// Con Cached > 0 (el agente lo rellena desde /proc/meminfo; ubus system info
+// no lo da) usa la fórmula clásica que no cuenta la caché de ficheros como
+// consumida (paridad LuCI/htop): used = total - free - buffered - cached.
+// Sin Cached (payloads viejos o sondeo SSH de ubus) cae a la fórmula previa
+// basada en MemAvailable, que en root ubifs/overlay tiende a sobreestimar el
+// uso porque el kernel cuenta poca caché como reclamable a corto plazo.
+func memUsagePct(total, free, buffered, cached, available float64) int {
+	if total <= 0 {
+		return 0
+	}
+	if cached > 0 {
+		used := total - free - buffered - cached
+		if used < 0 {
+			used = 0
+		}
+		return int(math.Round(used / total * 100))
+	}
+	avail := available
+	if avail == 0 {
+		avail = free + buffered
+	}
+	used := total - avail
+	if used < 0 {
+		used = 0
+	}
+	return int(math.Round(used / total * 100))
+}

+ 38 - 0
server-go/internal/adapters/mem_test.go

@@ -0,0 +1,38 @@
+// mem_test.go — contraste de memUsagePct con mediciones reales (issue #513).
+package adapters
+
+import "testing"
+
+func TestMemUsagePct(t *testing.T) {
+	cases := []struct {
+		name                       string
+		total, free, buff, cach, av float64
+		want                       int
+	}{
+		{
+			// rt3 AX6 real: con Cached (fórmula clásica) baja del 79% al 67%.
+			name: "rt3 con cached", total: 414264, free: 45780, buff: 0, cach: 90464, av: 88088, want: 67,
+		},
+		{
+			// Sin Cached (payload viejo/ubus): se mantiene el comportamiento
+			// anterior basado en MemAvailable.
+			name: "rt3 fallback available", total: 414264, free: 45780, buff: 0, cach: 0, av: 88088, want: 79,
+		},
+		{
+			// rt4 AX6: 60% con la fórmula previa; la clásica baja.
+			name: "rt4 con cached", total: 414264, free: 120000, buff: 0, cach: 48876, av: 165268, want: 59,
+		},
+		{
+			// Sin available, cae a free+buffered.
+			name: "sin available", total: 1000, free: 100, buff: 50, cach: 0, av: 0, want: 85,
+		},
+		{name: "cached mayor que el resto", total: 100, free: 0, buff: 0, cach: 500, av: 0, want: 0},
+		{name: "total cero", total: 0, free: 0, buff: 0, cach: 0, av: 0, want: 0},
+	}
+	for _, tc := range cases {
+		got := memUsagePct(tc.total, tc.free, tc.buff, tc.cach, tc.av)
+		if got != tc.want {
+			t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
+		}
+	}
+}