Ver código fonte

feat(agent): portable sysinfo round 2 — RAM, timezone, WAN label, hwmon temp (#1500/#1501/#1502) (#1503)

* feat(agent): portable RAM from /proc/meminfo when ubus is absent

Non-ubus targets (Asuswrt, Merlin, DSM) reported RAM 0% because
SysInfo.Memory only ever came from `ubus call system info`. Fill the raw
fields (total/free/buffers/cached/available) from /proc/meminfo instead
and never Used: memUsagePct gives the Used branch priority as the
process-RSS sum (#513), and precomputing used as total-MemAvailable
would hijack it with page cache included (measured 53% on a GT-BE98 Pro
where free(1)'s -/+ buffers/cache says 50.0%).

Item 1 of #1500.

* feat(agent): portable timezone for the detail panel slot

The frontend has rendered a Timezone row since #566 (extras.timezone,
"—" when absent) but no probe or poller ever filled it: ubus has no
timezone and the SSH/SNMP pollers read none. The agent now resolves the
IANA name from readlink /etc/localtime (fallbacks /etc/timezone and
/etc/TZ) on every target, and the server maps SysInfo.Timezone into
extras.timezone. Verified live: Asia/Shanghai on a GT-BE98 Pro and a
DS1821+ through a self-built server instance.

Item 2 of #1500.

* feat(agent): runtime uplink wins the WAN label on layout-less units

Without board.json (anything non-OpenWrt) the panel fallback hardcoded
eth1 as WAN (#847 era) even when the runtime uplink lives elsewhere: a
bridge-mode AP showed WAN on an idle port while its real uplink (the
bridge member facing the core switch) rendered as a plain ETH port.

Without ubus there is no WanInfo, so the uplink now comes from the
/proc/net/route default route; when it lands on a bridge (APs: the
default lives on br0) the physical port is the bridge member with an
LLDP neighbour — the mouth facing the core — falling back to the max-rx
member. Max-rx alone is wrong there: local bridged traffic (wireless↔LAN)
can out-rx the uplink (measured on a GT-BE98 Pro: eth3 619 MB vs eth0
188 MB since boot). Member iteration is sorted so ties and multi-LLDP
cases cannot flap between probes. The legacy wan/pppoe-wan/eth1 chain
still applies when there is no runtime uplink at all.

Item 3 of #1500, including the determinism note from review.

* feat(agent): hwmon last resort for machines with no thermal zones

Synology DSM (DS1821+, Ryzen V1500B) exposes zero thermal_zone entries:
the CPU temperature lives in hwmon (k10temp, 58 C measured). The #1484
zone-priority chain ended in "first readable zone" = nothing there, so
temp stayed absent. Add a final hwmon pass (k10temp|coretemp|k8temp|
cpu_thermal|soc_thermal, temp1_input) that only fires when NO zone
produced a value; zones keep priority wherever they exist, preserving
the single-source rule from #1484.

The test harness redirects the hwmon prefix to the fake root too (else
CI x86 hosts would read their real k10temp) and slash-normalizes the
temp dir, which also makes the three pre-existing CmdTemp tests pass
under a POSIX sh on Windows.

Item 4 of #1500.

* fix(server,app): RAM in MiB with a server-authoritative used figure

The detail panel divided the memory total by 1e6, so a 2 GiB module read
"2097 MB" and a 16 GiB box "16441 MB"; users read chip sizes in MiB
(2048, 16384). Divide by 1024^2 instead (#1501).

The "X MB used of Y MB" caption was derived frontend-side as
pct × total, accumulating the percentage rounding (50% × 2048 = 1024 vs
the real 1001 MiB measured with free(1)). The server now ships usedMb
from the same memUsagePct branches (memUsedBytes) and perfCaptions
prefers it, falling back to the derivation for old servers and demo.

* fix(app): Traffic history unit decided by the data, not the source type

RouterDetail passed 'fps' to PortSeriesChart for every external or
managed-switch unit without SNMP, on the assumption that non-SNMP
externals are RTLPlayground-style beacons (#641/#661). Agent-driven
units are in that class but ship per-port byte counters, so their
history chart plotted rxFps/txFps (always 0 on ethernet ports): a flat
line reading "0 fps" while the same series carried real bps and the
fleet card showed live Mbps for the very same unit.

PortSeriesChart now derives the unit from the fetched points (byte
rates present -> bps, only frame rates -> fps, prop as fallback for
empty series) and RouterDetail mirrors the FleetCard criterion for the
fallback hint. Closes the fleet-vs-detail disagreement by construction.

Fixes #1502.

* chore(agent): bump VERSION to 3.0.23 (release gate, per review of #1500)

* style: gofmt realignment after the liveExtras/SysInfo field additions

---------

Co-authored-by: Bann-DEV <bann.dev@gmail.com>
Bann-DEV 1 mês atrás
pai
commit
73d8ab127f

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.22
+3.0.23

+ 55 - 5
agent/probe/local.go

@@ -289,14 +289,24 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	pl.Data.System = p.probeSystem(ctx)
 	pl.Data.Wireless = p.probeWireless(ctx, true)
 	pl.Data.DHCP = p.probeDHCP(ctx)
-	pl.Data.FDB = p.probeFDB(ctx)
+	// LLDP antes que FDB (#1500): los puertos con vecino LLDP deciden qué
+	// miembro de un bridge es el uplink del AP. Una sola sonda por push:
+	// el resultado se reusa para el payload.
+	lldpData := p.probeLldp(ctx)
+	pl.Data.Lldp = lldpData
+	lldpPorts := map[string]bool{}
+	if lldpData != nil {
+		for _, nb := range lldpData.Neighbors {
+			if nb.Port != "" {
+				lldpPorts[nb.Port] = true
+			}
+		}
+	}
+	pl.Data.FDB = p.probeFDB(ctx, lldpPorts)
 	pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
 	pl.Data.Dawn = p.probeDawn(ctx)
 	pl.Data.Usteer = p.probeUsteer(ctx)
 	pl.Data.LuCI = p.probeLuCI(ctx)
-	// LLDP (#489): vecinos de lldpd en el payload del agente (antes solo
-	// llegaban por la sonda SSH del server, muerta para routers con agente).
-	pl.Data.Lldp = p.probeLldp(ctx)
 	// ClientBw (#551): tráfico por cliente desde nlbwmon (solo si instalado).
 	pl.Data.ClientBw = p.probeClientBw(ctx)
 	// Discovery (#338): mDNS services + randomized MAC detection.
@@ -367,6 +377,34 @@ func (p *Prober) probeSystem(ctx context.Context) *SystemData {
 			}
 		}
 	}
+	// #1500: memoria portable de /proc/meminfo cuando ubus no la dio (sin
+	// esto la ficha pinta RAM 0% en todo target sin ubus). Se rellenan los
+	// campos crudos y NUNCA Used: el server aplica su fórmula clásica
+	// (total-free-buffered-cached), la misma semántica que en unidades con
+	// ubus donde Used es la suma de RSS (#513).
+	if m := readMeminfoFieldsKB(); m.total > 0 {
+		if sd.SysInfo == nil {
+			sd.SysInfo = &SysInfo{}
+		}
+		if sd.SysInfo.Memory.Total == 0 {
+			sd.SysInfo.Memory.Total = float64(m.total) * 1024
+			sd.SysInfo.Memory.Free = float64(m.free) * 1024
+			sd.SysInfo.Memory.Buffered = float64(m.buffered) * 1024
+			sd.SysInfo.Memory.Cached = float64(m.cached) * 1024
+			sd.SysInfo.Memory.Available = float64(m.avail) * 1024
+			any = true
+		}
+	}
+	// #1500: zona horaria portable (ubus no la da nunca; la ficha pintaba
+	// "—" incluso en equipos con ubus).
+	if tz := readTimezone(); tz != "" {
+		if sd.SysInfo == nil {
+			sd.SysInfo = &SysInfo{}
+		}
+		if sd.SysInfo.Timezone == "" {
+			sd.SysInfo.Timezone = tz
+		}
+	}
 	if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" {
 		var b BoardInfo
 		if err := json.Unmarshal([]byte(out), &b); err == nil {
@@ -642,7 +680,7 @@ func (p *Prober) probeWan(ctx context.Context) *WanInfo {
 }
 
 // probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys).
-func (p *Prober) probeFDB(ctx context.Context) *FDBData {
+func (p *Prober) probeFDB(ctx context.Context, lldpPorts map[string]bool) *FDBData {
 	fd := &FDBData{}
 	any := false
 	if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
@@ -682,6 +720,18 @@ func (p *Prober) probeFDB(ctx context.Context) *FDBData {
 		if p.lastWan != nil {
 			uplink = p.lastWan.Port
 		}
+		// #1500: sin ubus no hay WanInfo: el uplink sale de la ruta default
+		// de /proc/net/route. Si cae en un bridge (APs: la default vive en
+		// br0), la boca física es el miembro con un vecino LLDP (la que
+		// mira al core) o, en su defecto, el de más rx bytes.
+		if uplink == "" {
+			uplink = defaultRouteIface()
+		}
+		if uplink != "" && isBridgeIface(uplink) {
+			if m := bridgeMemberUplink(members, lldpPorts, states, ifaces); m != "" {
+				uplink = m
+			}
+		}
 		fd.Ports = BuildEthPorts(layout, states, members, ifaces, uplink)
 		any = true
 	}

+ 174 - 0
agent/probe/portable.go

@@ -0,0 +1,174 @@
+// portable.go — sondas portables sin ubus (#1481 phase 1.5): lecturas de
+// /proc y /etc que funcionan en cualquier Linux (Asuswrt, Merlin, DSM).
+package probe
+
+import (
+	"os"
+	"sort"
+	"strconv"
+	"strings"
+)
+
+// meminfoKB: campos de /proc/meminfo en kB que necesita el fallback portable
+// (#1481 phase 1.5). Sin ubus, el server aplica su fórmula clásica
+// (total-free-buffered-cached) con estos campos: misma semántica de "uso"
+// que en unidades con ubus, donde Used es la suma de RSS (#513). Rellenar
+// Used con total-available incluiría la caché de ficheros y dispararía el
+// porcentaje muy por encima del uso real de procesos.
+type meminfoKB struct {
+	total, free, buffered, cached, avail int64
+}
+
+// parseMeminfoFieldsKB extrae los campos de /proc/meminfo. Sin
+// MemAvailable (kernels viejos) aproxima con MemFree.
+func parseMeminfoFieldsKB(data string) meminfoKB {
+	var m meminfoKB
+	haveAvail := false
+	for _, line := range strings.Split(data, "\n") {
+		f := strings.Fields(line)
+		if len(f) < 2 {
+			continue
+		}
+		n, err := strconv.ParseInt(f[1], 10, 64)
+		if err != nil {
+			continue
+		}
+		switch f[0] {
+		case "MemTotal:":
+			m.total = n
+		case "MemFree:":
+			m.free = n
+		case "Buffers:":
+			m.buffered = n
+		case "Cached:":
+			m.cached = n
+		case "MemAvailable:":
+			m.avail, haveAvail = n, true
+		}
+	}
+	if !haveAvail {
+		m.avail = m.free
+	}
+	return m
+}
+
+// readMeminfoFieldsKB lee /proc/meminfo del propio host (el agente corre EN
+// el equipo; fuera de Linux la lectura falla y devuelve cero).
+func readMeminfoFieldsKB() meminfoKB {
+	data, err := os.ReadFile("/proc/meminfo")
+	if err != nil {
+		return meminfoKB{}
+	}
+	return parseMeminfoFieldsKB(string(data))
+}
+
+// parseTimezoneLocaltime convierte el destino del symlink /etc/localtime
+// (".../usr/share/zoneinfo/Asia/Shanghai") en el nombre IANA de la zona.
+func parseTimezoneLocaltime(link string) string {
+	const marker = "zoneinfo/"
+	i := strings.LastIndex(link, marker)
+	if i < 0 {
+		return ""
+	}
+	return strings.TrimSpace(link[i+len(marker):])
+}
+
+// readTimezone: nombre IANA de la zona horaria del equipo. ubus no la da
+// nunca, así que se lee del sistema: symlink /etc/localtime (OpenWrt,
+// Asuswrt, Merlin, DSM), luego /etc/timezone (Debian) y por último /etc/TZ
+// (forma POSIX "CST-8", menos bonita pero mejor que "—").
+func readTimezone() string {
+	if link, err := os.Readlink("/etc/localtime"); err == nil {
+		if tz := parseTimezoneLocaltime(link); tz != "" {
+			return tz
+		}
+	}
+	for _, f := range []string{"/etc/timezone", "/etc/TZ"} {
+		if b, err := os.ReadFile(f); err == nil {
+			if s := strings.TrimSpace(string(b)); s != "" {
+				return s
+			}
+		}
+	}
+	return ""
+}
+
+// parseDefaultRouteIface extrae la interfaz de la ruta default de
+// /proc/net/route (destino y máscara 00000000; métrica mínima gana).
+func parseDefaultRouteIface(data string) string {
+	best := ""
+	bestMetric := int64(-1)
+	for i, line := range strings.Split(data, "\n") {
+		f := strings.Fields(line)
+		if len(f) < 8 || i == 0 && f[0] == "Iface" {
+			continue
+		}
+		if f[1] != "00000000" || f[7] != "00000000" {
+			continue
+		}
+		metric, _ := strconv.ParseInt(f[6], 10, 64)
+		if best == "" || metric < bestMetric {
+			best, bestMetric = f[0], metric
+		}
+	}
+	return best
+}
+
+// defaultRouteIface lee /proc/net/route del host; "" si no hay ruta default
+// o no se puede leer.
+func defaultRouteIface() string {
+	data, err := os.ReadFile("/proc/net/route")
+	if err != nil {
+		return ""
+	}
+	return parseDefaultRouteIface(string(data))
+}
+
+// isBridgeIface: ¿existe /sys/class/net/<name>/bridge? (es un bridge Linux).
+func isBridgeIface(name string) bool {
+	if name == "" {
+		return false
+	}
+	st, err := os.Stat("/sys/class/net/" + name + "/bridge")
+	return err == nil && st.IsDir()
+}
+
+// bridgeMemberUplink: boca miembro del bridge que hace de uplink en un AP
+// bridgeado. Criterio: primero el miembro con un vecino LLDP (la boca que
+// mira al core: switch/router aguas arriba); si ninguno anuncia LLDP, el
+// miembro con más bytes rx. El max-rx a secas se equivoca en APs donde un
+// puerto LAN carga tráfico local puenteado (wireless↔LAN) mayor que el del
+// uplink (medido en un GT-BE98 Pro: eth3 619 MB vs eth0 188 MB desde el
+// arranque). Iteración en orden de nombre: con empates de rx o varios
+// miembros LLDP la elección no debe bailar entre sondeos (review #1500).
+func bridgeMemberUplink(members map[string]bool, lldpPorts map[string]bool, states []PortState, ifaces map[string]IfRate) string {
+	byName := map[string]PortState{}
+	for _, st := range states {
+		byName[st.Name] = st
+	}
+	names := make([]string, 0, len(members))
+	for m := range members {
+		names = append(names, m)
+	}
+	sort.Strings(names)
+	qualifies := func(m string) bool {
+		st, ok := byName[m]
+		return ok && st.Up && !st.DSA && phyRe.MatchString(m) && !skipRe.MatchString(m)
+	}
+	for _, m := range names {
+		if qualifies(m) && lldpPorts[m] {
+			return m
+		}
+	}
+	best := ""
+	bestRx := uint64(0)
+	for _, m := range names {
+		if !qualifies(m) {
+			continue
+		}
+		if best == "" || ifaces[m].Rx > bestRx {
+			best, bestRx = m, ifaces[m].Rx
+		}
+	}
+	return best
+}

+ 126 - 0
agent/probe/portable_test.go

@@ -0,0 +1,126 @@
+// portable_test.go — parsers portables del phase 1.5 (#1500): meminfo,
+// timezone, ruta default y la WAN por uplink runtime en equipos sin layout.
+// Fixtures reales recortados de un GT-BE98 Pro (Asuswrt/Merlin) y un
+// DS1821+ (DSM) donde aplica.
+package probe
+
+import "testing"
+
+func TestParseMeminfoMem(t *testing.T) {
+	m := parseMeminfoFieldsKB(`MemTotal:       32841568 kB
+MemFree:         9959988 kB
+MemAvailable:   24142564 kB
+Buffers:          512128 kB
+Cached:         12582912 kB
+`)
+	if m.total != 32841568 || m.avail != 24142564 || m.free != 9959988 || m.buffered != 512128 || m.cached != 12582912 {
+		t.Fatalf("campos meminfo: %+v", m)
+	}
+	// Kernel sin MemAvailable: aproxima con MemFree.
+	m = parseMeminfoFieldsKB("MemTotal: 1000 kB\nMemFree: 400 kB\n")
+	if m.total != 1000 || m.avail != 400 {
+		t.Fatalf("fallback MemFree: %+v", m)
+	}
+	if m := parseMeminfoFieldsKB("basura\n"); m.total != 0 {
+		t.Fatalf("basura debía dar 0, dio %+v", m)
+	}
+}
+
+func TestParseTimezoneLocaltime(t *testing.T) {
+	cases := map[string]string{
+		"/usr/share/zoneinfo/Asia/Shanghai":     "Asia/Shanghai",
+		"/rom/usr/share/zoneinfo/Asia/Shanghai": "Asia/Shanghai",
+		"/usr/share/zoneinfo/Europe/Madrid":     "Europe/Madrid",
+		"/etc/localtime":                        "",
+		"":                                      "",
+	}
+	for link, want := range cases {
+		if got := parseTimezoneLocaltime(link); got != want {
+			t.Fatalf("parseTimezoneLocaltime(%q) = %q, want %q", link, got, want)
+		}
+	}
+}
+
+func TestParseDefaultRouteIface(t *testing.T) {
+	out := `Iface	Destination	Gateway 	Flags	RefCnt	Use	Metric	Mask		MTU	Window	IRTT
+eth0	00000000	0102A8C0	0003	0	0	10	00000000	0	0	0
+br0	00000000	00000000	0001	0	0	20	00000000	0	0	0
+eth1	0002A8C0	00000000	0001	0	0	0	00FFFFFF	0	0	0
+`
+	if got := parseDefaultRouteIface(out); got != "eth0" {
+		t.Fatalf("default route = %q, want eth0 (métrica mínima)", got)
+	}
+	if got := parseDefaultRouteIface("basura\n"); got != "" {
+		t.Fatalf("basura debía dar vacío, dio %q", got)
+	}
+}
+
+// Sin layout y con uplink runtime físico: la WAN es esa boca aunque exista
+// eth1 (la heurística ciega del #847 no debe pisar al runtime).
+func TestBuildEthPortsUplinkFisicoSinLayout(t *testing.T) {
+	states := ParsePortStates("eth0 up 1000\neth1 up 1000\neth4 up 1000\n")
+	ifaces := map[string]IfRate{"eth0": {}, "eth1": {}, "eth4": {}}
+	ports := BuildEthPorts(nil, states, nil, ifaces, "eth4")
+	if len(ports) != 3 {
+		t.Fatalf("bocas: %+v", ports)
+	}
+	if ports[0].ID != "wan" || ports[0].Iface != "eth4" {
+		t.Fatalf("WAN debía ser eth4: %+v", ports[0])
+	}
+}
+
+// Sin layout y con uplink sobre bridge: la WAN es el miembro con vecino
+// LLDP aunque otro cargue más rx (tráfico local puenteado).
+func TestBuildEthPortsUplinkBridgeMiembroMaxRx(t *testing.T) {
+	states := ParsePortStates("eth0 up 1000\neth1 up 1000\neth3 up 1000\nbr0 up 1000\n")
+	members := map[string]bool{"eth0": true, "eth1": true, "eth3": true}
+	ifaces := map[string]IfRate{
+		"eth0": {IfCounters: IfCounters{Rx: 188583580}},
+		"eth1": {IfCounters: IfCounters{Rx: 40756909}},
+		"eth3": {IfCounters: IfCounters{Rx: 619101463}},
+	}
+	// Uplink bridge ya resuelto por bridgeMemberUplink en probeFDB: aquí se
+	// comprueba que BuildEthPorts acepta el miembro físico como uplink.
+	ports := BuildEthPorts(nil, states, members, ifaces, "eth0")
+	if len(ports) != 3 || ports[0].ID != "wan" || ports[0].Iface != "eth0" {
+		t.Fatalf("WAN debía ser eth0: %+v", ports)
+	}
+}
+
+// bridgeMemberUplink: LLDP gana sobre rx, y los empates se resuelven por
+// nombre ordenado (sin baile entre sondeos, review de #1500).
+func TestBridgeMemberUplinkPrefiereLldp(t *testing.T) {
+	states := ParsePortStates("eth0 up 1000\neth1 up 1000\neth3 up 1000\nbr0 up 1000\n")
+	members := map[string]bool{"eth0": true, "eth1": true, "eth3": true}
+	ifaces := map[string]IfRate{
+		"eth0": {IfCounters: IfCounters{Rx: 188583580}},
+		"eth3": {IfCounters: IfCounters{Rx: 619101463}},
+	}
+	if got := bridgeMemberUplink(members, map[string]bool{"eth0": true}, states, ifaces); got != "eth0" {
+		t.Fatalf("con vecino LLDP debía ganar eth0, dio %q", got)
+	}
+	if got := bridgeMemberUplink(members, nil, states, ifaces); got != "eth3" {
+		t.Fatalf("sin LLDP debía ganar el de más rx (eth3), dio %q", got)
+	}
+	// Empate de rx con dos miembros LLDP: gana el primero en orden de nombre.
+	tie := map[string]IfRate{
+		"eth1": {IfCounters: IfCounters{Rx: 500}},
+		"eth0": {IfCounters: IfCounters{Rx: 500}},
+	}
+	if got := bridgeMemberUplink(members, map[string]bool{"eth0": true, "eth1": true}, states, tie); got != "eth0" {
+		t.Fatalf("empate LLDP debía ganar eth0 (orden de nombre), dio %q", got)
+	}
+	if got := bridgeMemberUplink(map[string]bool{}, nil, states, ifaces); got != "" {
+		t.Fatalf("sin miembros cualificados debía dar vacío, dio %q", got)
+	}
+}
+
+// Sin uplink runtime se conserva la heurística clásica (eth1).
+func TestBuildEthPortsSinUplinkMantieneHeuristica(t *testing.T) {
+	states := ParsePortStates("eth0 up 1000\neth1 up 1000\n")
+	ifaces := map[string]IfRate{"eth0": {}, "eth1": {}}
+	ports := BuildEthPorts(nil, states, nil, ifaces, "")
+	if len(ports) != 2 || ports[0].ID != "wan" || ports[0].Iface != "eth1" {
+		t.Fatalf("sin uplink la WAN heurística es eth1: %+v", ports)
+	}
+}

+ 51 - 9
agent/probe/probe.go

@@ -32,7 +32,10 @@ const (
 	// CmdTemp (#1484): temperatura de la CPU. En x86 la thermal_zone0 suele ser
 	// acpitz (ambiente ACPI), así que se elige por `type` con prioridad y la
 	// primera zona legible queda solo como fallback (ARM/SBC: cpu-thermal).
-	CmdTemp   = `o=""; for w in x86_pkg_temp cpu-thermal cpu_thermal soc-thermal; do for d in /sys/class/thermal/thermal_zone*; do [ "$(cat "$d/type" 2>/dev/null)" = "$w" ] && o=$(cat "$d/temp" 2>/dev/null) && break 2; done; done; [ -n "$o" ] || for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && o=$(cat "$f") && break; done; printf '%s\n' "$o"`
+	// Último recurso (#1500): hwmon para equipos SIN thermal zones (Synology
+	// DSM: k10temp en /sys/class/hwmon, cero zones). Con zones presentes
+	// mandan las zones: una sola fuente por equipo (#1484).
+	CmdTemp   = `o=""; for w in x86_pkg_temp cpu-thermal cpu_thermal soc-thermal; do for d in /sys/class/thermal/thermal_zone*; do [ "$(cat "$d/type" 2>/dev/null)" = "$w" ] && o=$(cat "$d/temp" 2>/dev/null) && break 2; done; done; [ -n "$o" ] || for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && o=$(cat "$f") && break; done; [ -n "$o" ] || for h in /sys/class/hwmon/hwmon*; do case "$(cat "$h/name" 2>/dev/null)" in k10temp|coretemp|k8temp|cpu_thermal|soc_thermal) [ -r "$h/temp1_input" ] && o=$(cat "$h/temp1_input") && break;; esac; done; printf '%s\n' "$o"`
 	CmdNetDev = "cat /proc/net/dev | tail -n +3"
 	// CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target.
 	CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2"
@@ -245,7 +248,11 @@ func CmdScanIface(iface string) string {
 type SysInfo struct {
 	Uptime float64   `json:"uptime"`
 	Load   []float64 `json:"load"`
-	Memory struct {
+	// Timezone (#1500): nombre IANA ("Asia/Shanghai") que el agente lee de
+	// /etc/localtime (o /etc/timezone, /etc/TZ). ubus nunca lo da, así que
+	// sin este campo la ficha mostraba "—" incluso en equipos con ubus.
+	Timezone string `json:"timezone,omitempty"`
+	Memory   struct {
 		Total     float64 `json:"total"`
 		Free      float64 `json:"free"`
 		Buffered  float64 `json:"buffered"`
@@ -1202,13 +1209,48 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 			used[p.Name] = true
 		}
 		wanName := ""
-		if _, ok := byName["wan"]; ok {
-			wanName = "wan"
-		} else if _, ok := byName["pppoe-wan"]; ok {
-			wanName = "eth1"
-		} else if st, ok := byName["eth1"]; ok && !st.DSA {
-			// #847: un conduit DSA no es la WAN física aunque se llame eth1.
-			wanName = "eth1"
+		if uplink != "" {
+			// #1500: con uplink runtime la WAN es esa boca, no la heurística
+			// ciega de abajo (un AP bridge sin layout marcaba WAN en eth1
+			// teniendo el uplink en eth0). El uplink puede llegar etiquetado
+			// ("br0.1"): la boca es la de debajo.
+			base := uplink
+			if i := strings.LastIndexByte(base, '.'); i > 0 {
+				base = base[:i]
+			}
+			if st, ok := byName[base]; ok && phyRe.MatchString(base) && isEthNetdev(st, ok) && !conduits[base] {
+				wanName = base
+			} else if len(brMembers) > 0 {
+				// Uplink sobre bridge (APs: la ruta default vive en br0): la
+				// boca WAN es el miembro con vecino LLDP (la que mira al
+				// core) o, en su defecto, el de más rx bytes. Iteración
+				// ordenada: empates no deben bailar entre sondeos (#1500).
+				names := make([]string, 0, len(brMembers))
+				for m := range brMembers {
+					names = append(names, m)
+				}
+				sort.Strings(names)
+				bestRx := uint64(0)
+				for _, m := range names {
+					st, ok := byName[m]
+					if !ok || !st.Up || !phyRe.MatchString(m) || !isEthNetdev(st, ok) || conduits[m] {
+						continue
+					}
+					if wanName == "" || ifaces[m].Rx > bestRx {
+						wanName, bestRx = m, ifaces[m].Rx
+					}
+				}
+			}
+		}
+		if wanName == "" {
+			if _, ok := byName["wan"]; ok {
+				wanName = "wan"
+			} else if _, ok := byName["pppoe-wan"]; ok {
+				wanName = "eth1"
+			} else if st, ok := byName["eth1"]; ok && !st.DSA {
+				// #847: un conduit DSA no es la WAN física aunque se llame eth1.
+				wanName = "eth1"
+			}
 		}
 		if wanName != "" {
 			st := byName[wanName]

+ 44 - 0
agent/probe/temp_test.go

@@ -34,7 +34,13 @@ func fakeThermal(t *testing.T, zones map[string][2]string) string {
 
 func runCmdTemp(t *testing.T, root string) string {
 	t.Helper()
+	// Rutas con slashes: bajo sh de Git en Windows los backslashes del
+	// TempDir romperían los globs del comando (en Linux es no-op).
+	root = filepath.ToSlash(root)
 	cmd := strings.ReplaceAll(CmdTemp, "/sys/class/thermal", root)
+	// El fallback hwmon también se redirige: sin esto los tests leerían el
+	// hwmon REAL del host que corre el test (k10temp/coretemp en CI x86).
+	cmd = strings.ReplaceAll(cmd, "/sys/class/hwmon", root+"-hwmon")
 	out, err := exec.Command("sh", "-c", cmd).Output()
 	if err != nil {
 		t.Fatalf("CmdTemp: %v", err)
@@ -42,6 +48,44 @@ func runCmdTemp(t *testing.T, root string) string {
 	return strings.TrimSpace(string(out))
 }
 
+// fakeHwmon construye un /sys/class/hwmon de mentira bajo root+"-hwmon"
+// (el mismo sufijo que sustituye runCmdTemp).
+func fakeHwmon(t *testing.T, root, name, temp string) {
+	t.Helper()
+	dir := filepath.Join(root+"-hwmon", "hwmon0")
+	if err := os.MkdirAll(dir, 0o755); err != nil {
+		t.Fatalf("mkdir %s: %v", dir, err)
+	}
+	if err := os.WriteFile(filepath.Join(dir, "name"), []byte(name+"\n"), 0o644); err != nil {
+		t.Fatalf("name: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(dir, "temp1_input"), []byte(temp+"\n"), 0o644); err != nil {
+		t.Fatalf("temp1_input: %v", err)
+	}
+}
+
+// Sin thermal zones pero con hwmon de CPU (Synology DSM: k10temp, cero
+// zones): el fallback hwmon es la única fuente y debe ganar.
+func TestCmdTempHwmonSinZonas(t *testing.T) {
+	root := fakeThermal(t, nil)
+	fakeHwmon(t, root, "k10temp", "58000")
+	if got := runCmdTemp(t, root); got != "58000" {
+		t.Fatalf("temperatura %q, want 58000 (hwmon sin zones)", got)
+	}
+}
+
+// Con zones presentes mandan las zones: el hwmon no debe pisarlas aunque
+// exista (una sola fuente por equipo, criterio del maintainer en #1484).
+func TestCmdTempZonesGananSobreHwmon(t *testing.T) {
+	root := fakeThermal(t, map[string][2]string{
+		"thermal_zone0": {"x86_pkg_temp", "52000"},
+	})
+	fakeHwmon(t, root, "k10temp", "58000")
+	if got := runCmdTemp(t, root); got != "52000" {
+		t.Fatalf("temperatura %q, want 52000 (la zone gana al hwmon)", got)
+	}
+}
+
 // El caso del issue: x86 con acpitz en la zona 0 y x86_pkg_temp en la 2. Debe
 // ganar la zona de CPU aunque la primera legible sea el ambiente ACPI.
 func TestCmdTempPrefersCPUZone(t *testing.T) {

+ 20 - 5
app/src/components/routers/PortSeriesChart.tsx

@@ -199,16 +199,31 @@ export function PortSeriesChart({
     fetchData()
   }, [fetchData])
 
+  // #1502: la unidad la deciden los datos, no solo el tipo de la fuente: si
+  // la serie trae tasas de bytes se pinta bps (unidades con agente), si solo
+  // trae tramas, fps (beacons, #641); el prop queda como fallback para
+  // series vacías. Así un caller que clasifique mal no puede dejar el
+  // gráfico plano a cero teniendo contadores de bytes.
+  const effUnit: TrafficUnit = useMemo(
+    () =>
+      data.some((p) => p.rxBps > 0 || p.txBps > 0)
+        ? 'bps'
+        : data.some((p) => p.rxFps > 0 || p.txFps > 0)
+          ? 'fps'
+          : unit,
+    [data, unit],
+  )
+
   const chartData = useMemo(() => {
     const pts = data
       .map((p) => ({
         t: fmtTime(p.ts, range),
-        rx: unit === 'fps' ? p.rxFps : p.rxBps,
-        tx: unit === 'fps' ? p.txFps : p.txBps,
+        rx: effUnit === 'fps' ? p.rxFps : p.rxBps,
+        tx: effUnit === 'fps' ? p.txFps : p.txBps,
       }))
       .filter((p) => !Number.isNaN(p.rx) && !Number.isNaN(p.tx))
     return downscale(pts, 600)
-  }, [data, range, unit])
+  }, [data, range, effUnit])
 
   const hasData = chartData.length > 1
   const peakRx = hasData ? Math.max(...chartData.map((p) => p.rx)) : 0
@@ -326,7 +341,7 @@ export function PortSeriesChart({
         </span>
         {hasData && (
           <span className="font-mono text-[10px] text-text-muted">
-            ↓ {fmtRate(unit, peakRx)} · ↑ {fmtRate(unit, peakTx)}
+            ↓ {fmtRate(effUnit, peakRx)} · ↑ {fmtRate(effUnit, peakTx)}
           </span>
         )}
       </div>
@@ -351,7 +366,7 @@ export function PortSeriesChart({
               </defs>
               <CartesianGrid vertical={false} stroke="rgb(var(--border) / 0.5)" strokeDasharray="3 6" />
               <XAxis dataKey="t" hide />
-              <Tooltip content={<PortTooltip unit={unit} />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
+              <Tooltip content={<PortTooltip unit={effUnit} />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
               <Area
                 type="monotone"
                 dataKey="rx"

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

@@ -66,7 +66,7 @@ function PerfTooltip({
 /** ② Rendimiento (router-detail.md §②) — 3 áreas con crosshair sincronizado.
  * En live usa las series reales que sirve el backend (por router y rango);
  * en demo conserva la serie sintética canónica. */
-export function RouterPerformance({ router, liveSeries, totalRamMb }: { router: Router; liveSeries?: PerfSeriesLive; totalRamMb?: number }) {
+export function RouterPerformance({ router, liveSeries, totalRamMb, usedRamMb }: { router: Router; liveSeries?: PerfSeriesLive; totalRamMb?: number; usedRamMb?: number }) {
   const { t } = useTranslation()
   const { isDemo } = useNetPulse()
   const [tempUnit] = useTempUnit()
@@ -81,8 +81,8 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
     return [{ t: '', cpu: router.cpu ?? 0, ram: router.ram ?? 0, temp: router.temp ?? 0 }]
   }, [isDemo, router, range, liveSeries])
   const captions = useMemo(
-    () => perfCaptions(router, data, isDemo ? undefined : totalRamMb, tempUnit),
-    [router, data, isDemo, totalRamMb, tempUnit],
+    () => perfCaptions(router, data, isDemo ? undefined : totalRamMb, isDemo ? undefined : usedRamMb, tempUnit),
+    [router, data, isDemo, totalRamMb, usedRamMb, tempUnit],
   )
 
   // #441: null cuando la fuente no reporta vitals (el panel no se monta,

+ 8 - 5
app/src/components/routers/routerExtras.ts

@@ -167,6 +167,8 @@ export interface RouterExtras {
   soc: string
   flash: string
   ramMb: number
+  /** RAM en uso en MiB según el backend (#1501); si falta, se deriva de pct. */
+  usedMb?: number
   bandSplit: BandSplit
   /** Zona horaria del router (p. ej. 'Europe/Madrid'); vacía si se desconoce. */
   timezone?: string
@@ -380,26 +382,27 @@ export function perfSeries(router: Router, range: '1h' | '24h' | '7d'): PerfPoin
   return points
 }
 
-export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number, unit: TempUnit = 'c'): { cpu: string; ram: string; temp: string } {
+export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number, usedMb?: number, unit: TempUnit = 'c'): { cpu: string; ram: string; temp: string } {
   // totalMb es la RAM total real (live, del backend). En demo (sin totalMb)
   // se usa el resolver demo, igual que antes.
   const total = totalMb && totalMb > 0 ? totalMb : getRouterExtras(router.id).ramMb
+  // #1501: el backend envía el uso autoritativo; derivarlo de pct × total
+  // acumulaba el error de redondeo del porcentaje.
+  const used = usedMb && usedMb > 0 ? usedMb : Math.round(((router.ram ?? 0) / 100) * total)
   if (data.length === 0) {
     const cpu = router.cpu ?? 0
     const temp = router.temp ?? 0
-    const ramUsed = Math.round(((router.ram ?? 0) / 100) * total)
     return {
       cpu: i18n.t('routerDetail.perf.peakCpu', { pct: cpu, t: '—' }),
-      ram: i18n.t('routerDetail.perf.ramUsed', { used: ramUsed, total }),
+      ram: i18n.t('routerDetail.perf.ramUsed', { used, total }),
       temp: i18n.t('routerDetail.perf.maxTemp', { temp: fmtTemp(temp, unit) }),
     }
   }
   const cpuMax = data.reduce((m, p) => (p.cpu > m.cpu ? p : m), data[0]!)
   const tempMax = data.reduce((m, p) => (p.temp > m.temp ? p : m), data[0]!)
-  const ramUsed = Math.round(((router.ram ?? 0) / 100) * total)
   return {
     cpu: i18n.t('routerDetail.perf.peakCpu', { pct: cpuMax.cpu, t: cpuMax.t }),
-    ram: i18n.t('routerDetail.perf.ramUsed', { used: ramUsed, total }),
+    ram: i18n.t('routerDetail.perf.ramUsed', { used, total }),
     temp: i18n.t('routerDetail.perf.maxTemp', { temp: fmtTemp(tempMax.temp, unit) }),
   }
 }

+ 10 - 5
app/src/pages/RouterDetail.tsx

@@ -272,7 +272,7 @@ export default function RouterDetail() {
             </div>
           </section>
         ) : (
-          <RouterPerformance router={router} liveSeries={detail?.series} totalRamMb={detail?.extras?.ramMb} />
+          <RouterPerformance router={router} liveSeries={detail?.series} totalRamMb={detail?.extras?.ramMb} usedRamMb={detail?.extras?.usedMb} />
         )}
       </div>
 
@@ -310,10 +310,15 @@ export default function RouterDetail() {
           ports={detail.extras.ethPorts}
           // #641/#661: los beacons RTLPlayground solo reportan tramas (fps),
           // pero un managed-switch sondeado por SNMP sí tiene contadores de
-          // bytes → se pinta en bps.
-          unit={router.type === 'managed-switch' || router.type === 'external'
-            ? (router.snmpEnabled ? 'bps' : 'fps')
-            : 'bps'}
+          // bytes → se pinta en bps. Las unidades con agente (external sin
+          // SNMP) TAMBIÉN llevan contadores de bytes: mismo criterio que
+          // FleetCard (vitalsAvailable === false identifica al beacon). El
+          // gráfico además se autocorrige desde los datos (#1502).
+          unit={router.snmpEnabled
+            ? 'bps'
+            : router.vitalsAvailable === false
+              ? 'fps'
+              : 'bps'}
           className="lg:col-span-12"
         />
       )}

+ 24 - 9
server-go/internal/adapters/live.go

@@ -4060,14 +4060,21 @@ func countClientsPerRouter(routers []Router, devices []Device) {
 
 // liveExtras es el objeto extras del detalle live (index.js:677-700).
 type liveExtras struct {
-	MAC                 string        `json:"mac"`
-	Firmware            string        `json:"firmware"`
-	FirmwareUpdated     bool          `json:"firmwareUpdated"`
-	FirmwareAvailable   string        `json:"firmwareAvailable,omitempty"`
-	LastReboot          string        `json:"lastReboot"`
-	Soc                 string        `json:"soc"`
-	Flash               string        `json:"flash"`
-	RamMb               int           `json:"ramMb"`
+	MAC               string `json:"mac"`
+	Firmware          string `json:"firmware"`
+	FirmwareUpdated   bool   `json:"firmwareUpdated"`
+	FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
+	LastReboot        string `json:"lastReboot"`
+	Soc               string `json:"soc"`
+	Flash             string `json:"flash"`
+	RamMb             int    `json:"ramMb"`
+	// Timezone (#1500): nombre IANA del equipo; lo aporta el agente desde
+	// /etc/localtime (ubus nunca lo dio y ningún sondeo SSH/SNMP tampoco).
+	Timezone string `json:"timezone,omitempty"`
+	// UsedMb (#1501): RAM en uso en MiB con la misma fórmula del porcentaje
+	// (memUsedBytes); el front la pinta directamente en vez de derivarla de
+	// pct × total, que acumulaba el error de redondeo.
+	UsedMb              int           `json:"usedMb,omitempty"`
 	BandSplit           demoBandSplit `json:"bandSplit"`
 	TrafficNow          float64       `json:"trafficNow"`
 	GatewayLatencySpark []float64     `json:"gatewayLatencySpark"`
@@ -4244,7 +4251,15 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 			extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
 		}
 		if p.sysInfo != nil && p.sysInfo.Memory.Total > 0 {
-			extras.RamMb = int(math.Round(p.sysInfo.Memory.Total / 1e6))
+			// MiB, no MB SI: un módulo de 2 GiB debe leerse "2048 MB" en el
+			// panel, que es como el usuario lee el tamaño del chip (#1501;
+			// antes /1e6 daba 2097).
+			extras.RamMb = int(math.Round(p.sysInfo.Memory.Total / (1024 * 1024)))
+			m := p.sysInfo.Memory
+			extras.UsedMb = int(math.Round(memUsedBytes(m.Total, m.Free, m.Buffered, m.Cached, m.Available, m.Used) / (1024 * 1024)))
+		}
+		if p.sysInfo != nil && p.sysInfo.Timezone != "" {
+			extras.Timezone = p.sysInfo.Timezone
 		}
 		if p.net != nil {
 			extras.TrafficNow = mbps(p.net.RxBps)

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

@@ -36,3 +36,32 @@ func memUsagePct(total, free, buffered, cached, available, usedProc float64) int
 	}
 	return int(math.Round(used / total * 100))
 }
+
+// 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
+// visible en el texto "X MB used of Y MB".
+func memUsedBytes(total, free, buffered, cached, available, usedProc float64) float64 {
+	if total <= 0 {
+		return 0
+	}
+	if usedProc > 0 && usedProc < total {
+		return usedProc
+	}
+	if cached > 0 {
+		used := total - free - buffered - cached
+		if used < 0 {
+			used = 0
+		}
+		return used
+	}
+	avail := available
+	if avail == 0 {
+		avail = free + buffered
+	}
+	used := total - avail
+	if used < 0 {
+		used = 0
+	}
+	return used
+}