Procházet zdrojové kódy

fix(monitor): report router RAM as process RSS, not total-available (#513) (#540)

(total-available)/total overreports memory on ubifs/overlay routers (75% when
the processes hold ~20%), because /proc/meminfo never counts the squashfs page
cache as free. The agent now reports memory.used as the sum of process VmRSS
(sumProcRSS in probe.go) and the server prefers it over the classic formula
(used/total), falling back to (total-available) when the agent does not send
it.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho před 3 měsíci
rodič
revize
52bbbb262b

+ 11 - 6
agent/probe/local.go

@@ -154,12 +154,17 @@ 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
+			if si.Memory.Total > 0 {
+				// ubus system info no expone la caché de ficheros, la lee el
+				// agente de /proc/meminfo (fallback silencioso si no existe).
+				if cached := readMeminfoCachedKB(); cached > 0 {
+					si.Memory.Cached = float64(cached) * 1024
+				}
+				// Y el uso real (lo que el usuario percibe) es la memoria de
+				// los procesos; así el server no sobreestima en ubifs (#513).
+				if rss := sumProcRSS(); rss > 0 && rss < si.Memory.Total {
+					si.Memory.Used = rss
+				}
 			}
 			sd.SysInfo = &si
 			any = true

+ 45 - 4
agent/probe/probe.go

@@ -12,6 +12,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"net"
+	"os"
 	"regexp"
 	"sort"
 	"strconv"
@@ -135,10 +136,8 @@ 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"`
+		Cached    float64 `json:"cached,omitempty"` // cache de ficheros, la rellena el agente (ubus no lo da)
+		Used      float64 `json:"used"`             // suma de VmRSS de procesos (#513)
 	} `json:"memory"`
 }
 
@@ -1448,3 +1447,45 @@ func ParseArp(out string) map[string]string {
 	}
 	return m
 }
+
+// sumProcRSS returns the total VmRSS (bytes) of every user-space process
+// (/proc/<pid>/status): the memory actually held by processes, excluding the
+// kernel page cache that inflates (total-available) on ubifs/overlay routers.
+func sumProcRSS() float64 {
+	entries, err := os.ReadDir("/proc")
+	if err != nil {
+		return 0
+	}
+	var total float64
+	for _, e := range entries {
+		if !allDigits(e.Name()) {
+			continue
+		}
+		b, err := os.ReadFile("/proc/" + e.Name() + "/status")
+		if err != nil {
+			continue
+		}
+		for _, line := range strings.Split(string(b), "\n") {
+			if !strings.HasPrefix(line, "VmRSS:") {
+				continue
+			}
+			f := strings.Fields(line)
+			if len(f) >= 2 {
+				if v, err := strconv.ParseFloat(f[1], 64); err == nil {
+					total += v * 1024
+				}
+			}
+			break
+		}
+	}
+	return total
+}
+
+func allDigits(s string) bool {
+	for _, r := range s {
+		if r < '0' || r > '9' {
+			return false
+		}
+	}
+	return s != ""
+}

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

@@ -514,7 +514,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	mem := sysInfo.Memory
 	if mem.Total > 0 {
-		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available)
+		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
 	}
 	out.sysInfo = sysInfo
 	out.ram = ramPct

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

@@ -935,12 +935,13 @@ 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 de RAM: #513 (con Cached del agente, fórmula clásica sin caché
-	// reclamable; sin Cached, MemAvailable). Ver memUsagePct.
+	// Uso de RAM: #513. Si el agente reporta memory.used (procesos) lo
+	// usamos (lo que el usuario percibe como uso real); si no, la fórmula
+	// clásica sin caché reclamable (Cached) o MemAvailable. Ver memUsagePct.
 	mem := sysInfo.Memory
 	ramPct := 0
 	if mem.Total > 0 {
-		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available)
+		ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
 	}
 
 	isGw := gw != nil && cfg.ID == gw.ID

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

@@ -6,16 +6,19 @@ 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 {
+// Prioridad: si el agente reporta `usedProc` (suma de VmRSS de procesos) lo
+// usamos directamente, porque es lo que el usuario percibe como uso real.
+// Si no llega, con Cached > 0 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 cae a la fórmula previa basada en MemAvailable, que en
+// root ubifs/overlay tiende a sobreestimar el uso (#513).
+func memUsagePct(total, free, buffered, cached, available, usedProc float64) int {
 	if total <= 0 {
 		return 0
 	}
+	if usedProc > 0 && usedProc < total {
+		return int(math.Round(usedProc / total * 100))
+	}
 	if cached > 0 {
 		used := total - free - buffered - cached
 		if used < 0 {

+ 15 - 5
server-go/internal/adapters/mem_test.go

@@ -5,12 +5,17 @@ import "testing"
 
 func TestMemUsagePct(t *testing.T) {
 	cases := []struct {
-		name                       string
-		total, free, buff, cach, av float64
-		want                       int
+		name                                  string
+		total, free, buff, cach, av, usedProc float64
+		want                                  int
 	}{
 		{
-			// rt3 AX6 real: con Cached (fórmula clásica) baja del 79% al 67%.
+			// Con usedProc (RSS de procesos) se usa ese valor directamente: es
+			// lo que el usuario percibe como uso real (netgrip #279).
+			name: "rt3 con usedProc rss", total: 414264, free: 57364, buff: 0, cach: 94136, av: 99684, usedProc: 78000, want: 19,
+		},
+		{
+			// Sin usedProc pero 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,
 		},
 		{
@@ -26,11 +31,16 @@ func TestMemUsagePct(t *testing.T) {
 			// Sin available, cae a free+buffered.
 			name: "sin available", total: 1000, free: 100, buff: 50, cach: 0, av: 0, want: 85,
 		},
+		{
+			// usedProc mayor que total se ignora y cae a la fórmula clásica
+			// (con Cached): used = total - free - buffered - cached.
+			name: "usedProc invalido", total: 1000, free: 100, buff: 0, cach: 400, av: 0, usedProc: 5000, want: 50,
+		},
 		{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)
+		got := memUsagePct(tc.total, tc.free, tc.buff, tc.cach, tc.av, tc.usedProc)
 		if got != tc.want {
 			t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
 		}