Browse Source

fix(beacon): unwrap 32-bit frame counters at ingest (#2241)

The firmware sends cumulative 32-bit frame counters and deriveFps reads any decrease as a reset, so the interval where the counter wraps was lost from the series and the hourly total. The ingest keeps the last raw value per port and direction, adds 2^32 on a wrap and uses the datagram uptime to tell a wrap from a reboot. A decrease with a smaller uptime restarts the base and contributes no rate, and a beacon process restart with the same uptime does the same. Only beacon ports take this path, so the 64-bit agent counters are untouched.

Closes #2221
Nacho 5 days ago
parent
commit
3a724bae26

+ 1 - 0
CHANGELOG.md

@@ -23,6 +23,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- Frame counters of a beacon-fed switch no longer lose the interval where the 32-bit counter wraps. The ingest unwraps it to 64 bits and uses the datagram uptime to tell a wrap from a reboot, so a reboot still contributes no rate instead of a spike of 2^32 frames (#2221).
 - The supervisor no longer restarts an agent or rotates its token when the server is rejecting its pushes as `stale_payload`. That reason means the unit clock is outside the freshness window, and neither a restart nor a rotation can move a clock: the loop just restarted the panel once per cooldown and dropped its buffered pushes. It now leaves an alert naming the clock and stays hands off (#2238).
 - A token rotation that succeeds but does not get the agent pushing is logged. Before it fell through both branches and the journal showed the attempt and then nothing (#2238).
 - `POST /api/alerts/silence` requires `duration` or `until`. A body with neither fell through to `forever`, so a client that forgot the field silenced the alert with no expiry and no signal. `forever` still exists, but only when it is asked for by name (#2223).

+ 2 - 0
docs/RTL-SWITCH-BEACON.md

@@ -20,6 +20,8 @@ The beacon does not provide CPU, RAM or switch temperature. LLDP transmission an
 
 A build that receives LLDP can also send the neighbours it learned, as an optional `lldp` section (#2184). Each entry carries the local port number, the remote chassis id or system name, the first management address, the enabled capabilities and the remote port description. The section is optional and bounded: 64 neighbours at most and 128 characters per text field, so it costs roughly 80 to 120 bytes per neighbour in the datagram. A build without the section simply does not send it, and the server then keeps the last known neighbours; an empty list means the switch received nothing, which is a different thing from not knowing.
 
+Frame counters leave the switch as cumulative 32-bit values. The server unwraps them at ingest into a monotonic 64-bit series and uses the datagram uptime to tell a wrap from a reboot: a counter that drops while the uptime keeps growing is a wrap (the value moves from the top quarter of the range to the bottom), and a decrease with a smaller uptime is a reboot, which contributes no rate. Only beacon ports take this path: agent ports carry 64-bit counters and are left alone (#2221).
+
 A beacon-fed device cannot currently use SNMP as a second NetPulse source. Optional SNMP support in the firmware can be used independently, but it does not add another source to the same NetPulse device.
 
 ## Requirements

+ 37 - 15
server-go/internal/httpapi/beacon.go

@@ -346,7 +346,7 @@ func (s *server) ingestBeacon(src string, raw []byte) {
 		}
 		ports = append(ports, ep)
 	}
-	s.recordBeaconPortSamples(p.Slug, p.Ports)
+	s.recordBeaconPortSamples(p.Slug, p.Up, p.Ports)
 	// Alertas SFP (#313): RX baja o temperatura alta en módulos ópticos.
 	// Se emiten aquí (no en polledFromAgent) para que el dedup del motor
 	// colapse duplicados entre beacons del mismo switch.
@@ -553,12 +553,42 @@ func (s *server) emitSFPAlerts(slug string, labels map[string]string, sfpByPort
 // recordBeaconPortSamples persists beacon frame counts as port series samples
 // (issue #302). Beacon ports carry cumulative tx/rx frame counts and link speed
 // but no byte counters (the 8051 firmware does not track bytes per port).
-func (s *server) recordBeaconPortSamples(slug string, bps []beaconPort) {
+func (s *server) recordBeaconPortSamples(slug string, up uint32, bps []beaconPort) {
 	if s.db == nil || s.db.PortSeries == nil || len(bps) == 0 {
 		return
 	}
+	// #2221: los contadores viajan en 32 bits y la serie los espera
+	// monótonos. El desenrollo va aquí, con el uptime del datagrama para
+	// distinguir una vuelta de un reinicio; deriveFps no cambia.
+	samples := make([]portseries.PortSample, len(bps))
+	s.beaconCntMu.Lock()
+	if s.beaconCnt == nil {
+		s.beaconCnt = map[string]beaconCounter{}
+	}
+	for i, bp := range bps {
+		portID := fmt.Sprintf("lan%d", bp.N)
+		rxKey := slug + "|" + portID + "|rx"
+		txKey := slug + "|" + portID + "|tx"
+		rxPrev, rxOK := s.beaconCnt[rxKey]
+		txPrev, txOK := s.beaconCnt[txKey]
+		rx, rxNext := unwrapBeaconCounter(rxPrev, rxOK, bp.Rx, up)
+		tx, txNext := unwrapBeaconCounter(txPrev, txOK, bp.Tx, up)
+		s.beaconCnt[rxKey] = rxNext
+		s.beaconCnt[txKey] = txNext
+		samples[i] = portseries.PortSample{
+			RouterID: slug,
+			PortID:   portID,
+			RxBytes:  uint64(bp.Ih)<<32 | uint64(bp.Il),
+			TxBytes:  uint64(bp.Oh)<<32 | uint64(bp.Ol),
+			RxFrames: rx,
+			TxFrames: tx,
+			RxErrors: uint64(bp.Ie),
+			TxErrors: uint64(bp.Oe),
+		}
+	}
+	s.beaconCntMu.Unlock()
 	now := time.Now()
-	for _, bp := range bps {
+	for i, bp := range bps {
 		if bp.N < 1 || bp.N > 32 {
 			continue
 		}
@@ -581,18 +611,10 @@ func (s *server) recordBeaconPortSamples(slug string, bps []beaconPort) {
 				speedMbps = 10
 			}
 		}
-		_ = s.db.PortSeries.RecordSample(portseries.PortSample{
-			RouterID:  slug,
-			PortID:    fmt.Sprintf("lan%d", bp.N),
-			TS:        now,
-			RxBytes:   uint64(bp.Ih)<<32 | uint64(bp.Il),
-			TxBytes:   uint64(bp.Oh)<<32 | uint64(bp.Ol),
-			RxFrames:  uint64(bp.Rx),
-			TxFrames:  uint64(bp.Tx),
-			RxErrors:  uint64(bp.Ie),
-			TxErrors:  uint64(bp.Oe),
-			SpeedMbps: speedMbps,
-		})
+		sample := samples[i]
+		sample.TS = now
+		sample.SpeedMbps = speedMbps
+		_ = s.db.PortSeries.RecordSample(sample)
 	}
 }
 

+ 47 - 0
server-go/internal/httpapi/beacon_counter.go

@@ -0,0 +1,47 @@
+package httpapi
+
+// Los contadores tx/rx del beacon son acumulados de 32 bits (ver
+// docs/RTL-SWITCH-BEACON.md) y `portseries.deriveFps` lee cualquier bajada
+// como un reset, así que una envoltura de 2^32 perdía ese intervalo. El
+// desenrollo se hace aquí, donde la anchura es parte del contrato: la tabla
+// de series también la alimentan los puertos del agente, con contadores de
+// 64 bits, y un heurístico genérico convertiría un reinicio del router en un
+// pico de 2^32 tramas (#2221).
+
+const (
+	beaconCounterWrap = uint64(1) << 32
+	// Solo es envoltura si el valor anterior estaba en el último cuarto del
+	// rango y el nuevo en el primero. Un reinicio del proceso del beacon
+	// deja el contador a cero con el uptime del equipo intacto, y sin esta
+	// condición se tomaría por una vuelta completa.
+	beaconWrapHigh = uint32(3) << 30
+	beaconWrapLow  = uint32(1) << 30
+)
+
+// beaconCounter es el último datagrama crudo visto para un contador concreto
+// (un puerto y un sentido).
+type beaconCounter struct {
+	raw  uint32
+	up   uint32 // uptime del datagrama: distingue envoltura de reinicio
+	high uint64 // múltiplos de 2^32 ya desenrollados
+}
+
+// unwrapBeaconCounter devuelve el valor monótono de 64 bits y el estado que
+// hay que guardar para el siguiente datagrama.
+func unwrapBeaconCounter(prev beaconCounter, hasPrev bool, raw, up uint32) (uint64, beaconCounter) {
+	if !hasPrev {
+		return uint64(raw), beaconCounter{raw: raw, up: up}
+	}
+	if raw >= prev.raw {
+		return prev.high + uint64(raw), beaconCounter{raw: raw, up: up, high: prev.high}
+	}
+	// El contador bajó: reinicio del equipo, envoltura o reset del proceso.
+	if prev.up != 0 && up != 0 && up < prev.up {
+		return uint64(raw), beaconCounter{raw: raw, up: up}
+	}
+	if prev.raw >= beaconWrapHigh && raw < beaconWrapLow {
+		high := prev.high + beaconCounterWrap
+		return high + uint64(raw), beaconCounter{raw: raw, up: up, high: high}
+	}
+	return uint64(raw), beaconCounter{raw: raw, up: up}
+}

+ 40 - 0
server-go/internal/httpapi/beacon_counter_2221_test.go

@@ -0,0 +1,40 @@
+package httpapi
+
+import "testing"
+
+// #2221: los contadores del beacon son de 32 bits y `deriveFps` lee la
+// envoltura como un reset, así que el ingest tiene que desenrollarlos.
+func TestUnwrapBeaconCounterWrapsAt2To32(t *testing.T) {
+	v1, st := unwrapBeaconCounter(beaconCounter{}, false, 4_294_967_290, 1000)
+	if v1 != 4_294_967_290 {
+		t.Fatalf("primer valor: %d", v1)
+	}
+	v2, _ := unwrapBeaconCounter(st, true, 5, 1001)
+	if got := v2 - v1; got != 11 {
+		t.Fatalf("delta tras la envoltura: %d, esperaba 11", got)
+	}
+}
+
+// Un reinicio del equipo baja el uptime y el contador: no es una envoltura y
+// no puede producir una tasa de 2^32 tramas.
+func TestUnwrapBeaconCounterRebootIsNotAWrap(t *testing.T) {
+	_, st := unwrapBeaconCounter(beaconCounter{}, false, 4_294_967_290, 1000)
+	v2, _ := unwrapBeaconCounter(st, true, 5, 3)
+	v3, _ := unwrapBeaconCounter(beaconCounter{raw: 5, up: 3}, true, 7, 5)
+	if v3 <= v2 {
+		t.Fatalf("el contador debe seguir: v2=%d v3=%d", v2, v3)
+	}
+	if v3-v2 != 2 {
+		t.Fatalf("delta tras reinicio: %d, esperaba 2", v3-v2)
+	}
+}
+
+// Un reinicio del proceso sin reinicio del equipo (mismo uptime, contador a
+// cero) tampoco es una envoltura: se reinicia la base, sin pico.
+func TestUnwrapBeaconCounterProcessResetIsNotAWrap(t *testing.T) {
+	_, st := unwrapBeaconCounter(beaconCounter{}, false, 900_000_000, 1000)
+	v2, _ := unwrapBeaconCounter(st, true, 12, 1001)
+	if v2 != 12 {
+		t.Fatalf("reset sin reinicio: %d, esperaba 12", v2)
+	}
+}

+ 4 - 0
server-go/internal/httpapi/server.go

@@ -225,6 +225,10 @@ type server struct {
 	beaconSeq    map[string]uint32
 	beaconCandMu sync.Mutex
 	beaconCand   map[string]beaconCandidate
+	// Último contador crudo por (slug, puerto, sentido) para desenrollar los
+	// acumulados de 32 bits del firmware (#2221).
+	beaconCntMu sync.Mutex
+	beaconCnt   map[string]beaconCounter
 
 	// Backups automáticos (#741): mutex single-flight entre el run manual
 	// (POST /api/backup/run) y el scheduler periódico.