Просмотр исходного кода

Fix ghost port false positive and consolidate port alert storms (#382)

* fix(portmonitor): only observe fresh agent payloads, treat counter resets as a new era

Between agent pushes every overview rebuild re-derived the sondeo with the
same cached payload, so frozen counters were read as zero traffic and the
ghost port alert fired on healthy ports (97 duplicates on rt3 today).
Counter resets (router reboot) now reset the baseline instead of counting
an endless zero streak.

Closes #365

* fix(alerts): consolidate port alerts into one ongoing alert with recovery

Flap, ghost and degraded alerts now use EmitOrUpdate so a persistent
incident refreshes a single alert instead of leaking one new alert per
dedup window, and emit a one-time ok alert when the condition clears.

Closes #366

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
3bf3e5f077

+ 13 - 2
server-go/internal/adapters/agent.go

@@ -584,12 +584,23 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	}
 
 
 	l.mu.Lock()
 	l.mu.Lock()
+	freshPayload := p.Ts != l.lastObsTs[cfg.ID]
+	if freshPayload {
+		l.lastObsTs[cfg.ID] = p.Ts
+	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
 		wireless: out.wireless, fdb: out.fdb, luci: out.luci}
 		wireless: out.wireless, fdb: out.fdb, luci: out.luci}
 	l.mu.Unlock()
 	l.mu.Unlock()
 
 
-	l.recordPortSamples(cfg.ID, out.ports)
-	l.portMon.Observe(cfg.ID, out.ports, l.engine)
+	// Solo con un payload NUEVO alimentamos las series y el monitor de
+	// puertos (issue #365): entre pushes, cada rebuild del overview vuelve
+	// por aquí con el MISMO payload cacheado, y re-observar contadores
+	// congelados dispara alertas fantasma ("zero bytes" que solo es espera
+	// del siguiente push).
+	if freshPayload {
+		l.recordPortSamples(cfg.ID, out.ports)
+		l.portMon.Observe(cfg.ID, out.ports, l.engine)
+	}
 
 
 	if out.leases == nil {
 	if out.leases == nil {
 		out.leases = []DhcpLease{}
 		out.leases = []DhcpLease{}

+ 62 - 0
server-go/internal/adapters/agent_observe_dedup_test.go

@@ -0,0 +1,62 @@
+// agent_observe_dedup_test.go — issue #365: entre pushes del agente, cada
+// rebuild del overview re-deriva el sondeo con el MISMO payload cacheado.
+// Re-observar contadores congelados no debe alimentar el PortMonitor ni las
+// series por puerto (falsa alerta de puerto fantasma).
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func ghostPayload(ts int64, rx, tx uint64) *probe.Payload {
+	p := &probe.Payload{Router: "patio", Ts: ts, Version: "t"}
+	p.Data.FDB = &probe.FDBData{
+		MACs:  map[string]string{},
+		Ports: []probe.EthPort{{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", Iface: "lan1", RxBytes: rx, TxBytes: tx}},
+	}
+	return p
+}
+
+func TestPolledFromAgentDuplicatePayloadDoesNotObserve(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "patio", Host: "192.168.8.2", Name: "Patio"}}, nil)
+	cfg := l.routers[0]
+
+	// Historia sana: 12 payloads nuevos con tráfico creciente.
+	var rx uint64 = 1000
+	ts := int64(1000)
+	for i := 0; i < 12; i++ {
+		rx += 1000
+		ts += 30
+		l.polledFromAgent(cfg, ghostPayload(ts, rx, 500))
+	}
+
+	// El MISMO payload (ts congelado) re-derivado muchas veces: ninguna
+	// observación nueva, el streak no puede crecer.
+	frozen := ghostPayload(ts, rx, 500)
+	for i := 0; i < 10; i++ {
+		l.polledFromAgent(cfg, frozen)
+	}
+	for _, ev := range l.engine.List() {
+		if ev.Title == "Ghost port: LAN 1 went silent" {
+			t.Fatal("cached duplicate observations must not raise a ghost alert")
+		}
+	}
+
+	// 3 payloads NUEVOS con contadores congelados (silencio real) sí alertan,
+	// una única vez aunque lleguen más.
+	for i := 0; i < 3; i++ {
+		ts += 30
+		l.polledFromAgent(cfg, ghostPayload(ts, rx, 500))
+	}
+	n := 0
+	for _, ev := range l.engine.List() {
+		if ev.Title == "Ghost port: LAN 1 went silent" {
+			n++
+		}
+	}
+	if n != 1 {
+		t.Fatalf("ghost alerts = %d, want 1", n)
+	}
+}

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

@@ -195,6 +195,9 @@ type Live struct {
 	// (contadores absolutos + ts) para calcular los rates por boca con el
 	// (contadores absolutos + ts) para calcular los rates por boca con el
 	// delta entre payloads (issue #305). Protegido por mu.
 	// delta entre payloads (issue #305). Protegido por mu.
 	lastAgentIf map[string]*agentIfSample
 	lastAgentIf map[string]*agentIfSample
+	// lastObsTs: ts del último payload del agente que alimentó las series
+	// por puerto y el PortMonitor (issue #365). Protegido por mu.
+	lastObsTs map[string]int64
 	// snmpPorts (issue #309): contadores del último poll SNMP por router y
 	// snmpPorts (issue #309): contadores del último poll SNMP por router y
 	// puerto. Se usa para calcular rxBps/txBps entre polls sucesivos.
 	// puerto. Se usa para calcular rxBps/txBps entre polls sucesivos.
 	snmpPorts map[string]map[string]snmpPortSample
 	snmpPorts map[string]map[string]snmpPortSample
@@ -286,6 +289,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		layoutCache:          map[string][]PortLayout{},
 		layoutCache:          map[string][]PortLayout{},
 		extrasCache:          map[string]*extrasSnapshot{},
 		extrasCache:          map[string]*extrasSnapshot{},
 		lastAgentIf:          map[string]*agentIfSample{},
 		lastAgentIf:          map[string]*agentIfSample{},
+		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		lastPolled:           map[string]*routerPolled{},
 		lastPolled:           map[string]*routerPolled{},
 		failCount:            map[string]int{},
 		failCount:            map[string]int{},

+ 63 - 7
server-go/internal/adapters/portmonitor.go

@@ -30,6 +30,12 @@ type portState struct {
 	trafficTotal uint64
 	trafficTotal uint64
 	zeroStreak   int
 	zeroStreak   int
 	hadTraffic   bool
 	hadTraffic   bool
+	// Incidentes abiertos (issue #366): mientras la condición persiste hay
+	// UNA sola alerta viva por puerto (EmitOrUpdate la refresca in situ);
+	// la flag dispara la alerta de recuperación exactamente una vez.
+	flapActive     bool
+	ghostActive    bool
+	degradedActive bool
 }
 }
 
 
 type PortMonitor struct {
 type PortMonitor struct {
@@ -67,8 +73,8 @@ func (pm *PortMonitor) Observe(routerID string, ports []EthPort, engine *alerts.
 		}
 		}
 		pm.updateSpeedHistory(st, p)
 		pm.updateSpeedHistory(st, p)
 		pm.checkFlapping(key, st, p, now, engine)
 		pm.checkFlapping(key, st, p, now, engine)
-		pm.checkGhost(key, st, p, engine)
-		pm.checkDegraded(key, st, p, engine)
+		pm.checkGhost(key, st, p, now, engine)
+		pm.checkDegraded(key, st, p, now, engine)
 	}
 	}
 }
 }
 
 
@@ -100,7 +106,8 @@ func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now
 	}
 	}
 	st.transitions = kept
 	st.transitions = kept
 	if len(st.transitions) >= flapThreshold {
 	if len(st.transitions) >= flapThreshold {
-		engine.Emit(alerts.AlertEvent{
+		st.flapActive = true
+		engine.EmitOrUpdate(alerts.AlertEvent{
 			ID:          fmt.Sprintf("alert-flap-%s-%s", key.routerID, key.portID),
 			ID:          fmt.Sprintf("alert-flap-%s-%s", key.routerID, key.portID),
 			Category:    alerts.CatSystem,
 			Category:    alerts.CatSystem,
 			Urgent:      false,
 			Urgent:      false,
@@ -111,15 +118,38 @@ func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now
 			Time:        "ahora mismo",
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 			RouterID:    key.routerID,
 		})
 		})
+	} else if st.flapActive {
+		st.flapActive = false
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-flap-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "ok",
+			Title:       fmt.Sprintf("Port stable again: %s on %s", p.Label, key.routerID),
+			Description: fmt.Sprintf("Flapping stopped, fewer than %d transitions in %s", flapThreshold, flapWindow),
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
 	}
 	}
 }
 }
 
 
-func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, engine *alerts.Engine) {
+func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
 	total := p.RxBytes + p.TxBytes
 	total := p.RxBytes + p.TxBytes
 	if !p.Up {
 	if !p.Up {
 		st.zeroStreak = 0
 		st.zeroStreak = 0
 		st.hadTraffic = false
 		st.hadTraffic = false
 		st.trafficTotal = 0
 		st.trafficTotal = 0
+		st.ghostActive = false
+		return
+	}
+	if total < st.trafficTotal {
+		// Contador reseteado (reboot del router): arranca una era nueva del
+		// contador, no es un puerto muerto. Sin esto, el streak crecería
+		// durante horas hasta superar el total pre-reboot (issue #365).
+		st.trafficTotal = total
+		st.hadTraffic = false
+		st.zeroStreak = 0
+		st.ghostActive = false
 		return
 		return
 	}
 	}
 	if total > st.trafficTotal {
 	if total > st.trafficTotal {
@@ -133,7 +163,8 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, engine
 		return
 		return
 	}
 	}
 	if st.zeroStreak >= ghostConsecutive {
 	if st.zeroStreak >= ghostConsecutive {
-		engine.Emit(alerts.AlertEvent{
+		st.ghostActive = true
+		engine.EmitOrUpdate(alerts.AlertEvent{
 			ID:          fmt.Sprintf("alert-ghost-%s-%s", key.routerID, key.portID),
 			ID:          fmt.Sprintf("alert-ghost-%s-%s", key.routerID, key.portID),
 			Category:    alerts.CatSystem,
 			Category:    alerts.CatSystem,
 			Urgent:      false,
 			Urgent:      false,
@@ -144,10 +175,22 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, engine
 			Time:        "ahora mismo",
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 			RouterID:    key.routerID,
 		})
 		})
+	} else if st.ghostActive && st.zeroStreak == 0 {
+		st.ghostActive = false
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-ghost-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "ok",
+			Title:       fmt.Sprintf("Ghost port recovered: %s on %s", p.Label, key.routerID),
+			Description: "Port is moving traffic again",
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
 	}
 	}
 }
 }
 
 
-func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, engine *alerts.Engine) {
+func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
 	if len(st.speedHistory) < degradedMinHistory {
 	if len(st.speedHistory) < degradedMinHistory {
 		return
 		return
 	}
 	}
@@ -164,7 +207,8 @@ func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, engi
 		}
 		}
 	}
 	}
 	if allBelow && st.speedMbps < prev {
 	if allBelow && st.speedMbps < prev {
-		engine.Emit(alerts.AlertEvent{
+		st.degradedActive = true
+		engine.EmitOrUpdate(alerts.AlertEvent{
 			ID:          fmt.Sprintf("alert-degraded-%s-%s", key.routerID, key.portID),
 			ID:          fmt.Sprintf("alert-degraded-%s-%s", key.routerID, key.portID),
 			Category:    alerts.CatSystem,
 			Category:    alerts.CatSystem,
 			Urgent:      false,
 			Urgent:      false,
@@ -175,6 +219,18 @@ func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, engi
 			Time:        "ahora mismo",
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 			RouterID:    key.routerID,
 		})
 		})
+	} else if st.degradedActive {
+		st.degradedActive = false
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-degraded-%s-%s-ok-%d", key.routerID, key.portID, now.Unix()),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "ok",
+			Title:       fmt.Sprintf("Link speed recovered: %s on %s", p.Label, key.routerID),
+			Description: fmt.Sprintf("Port negotiated speed is back to %d Mbps", st.speedMbps),
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
 	}
 	}
 }
 }
 
 

+ 126 - 0
server-go/internal/adapters/portmonitor_test.go

@@ -231,3 +231,129 @@ func TestDominantSpeed(t *testing.T) {
 		}
 		}
 	}
 	}
 }
 }
+
+// buildGhostPort deja el monitor listo para el umbral de ghost: historia
+// suficiente y tráfico creciente. Devuelve el reloj mutable.
+func buildGhostPort(t *testing.T, pm *PortMonitor, engine *alerts.Engine) (EthPort, func(time.Time)) {
+	t.Helper()
+	now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC)
+	setClock := func(n time.Time) { pm.SetClock(func() time.Time { return n }) }
+	setClock(now)
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 0, TxBytes: 0, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+	for i := 0; i < ghostMinHistory; i++ {
+		port.RxBytes += 1000
+		port.TxBytes += 500
+		now = now.Add(45 * time.Second)
+		setClock(now)
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+	return port, setClock
+}
+
+func findAlerts(engine *alerts.Engine, title string) (int, alerts.AlertEvent) {
+	n := 0
+	var last alerts.AlertEvent
+	for _, ev := range engine.List() {
+		if ev.Title == title {
+			n++
+			last = ev
+		}
+	}
+	return n, last
+}
+
+// issue #366: un incidente persistente refresca UNA sola alerta (EmitOrUpdate)
+// en vez de colar una nueva por cada ventana de dedup.
+func TestPortMonitorGhostConsolidatesIntoOneAlert(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	port, setClock := buildGhostPort(t, pm, engine)
+
+	now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
+	for i := 0; i < 20; i++ {
+		now = now.Add(6 * time.Minute)
+		setClock(now)
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+	n, last := findAlerts(engine, "Ghost port: LAN1 went silent")
+	if n != 1 {
+		t.Fatalf("ghost alerts = %d, want 1 (consolidated)", n)
+	}
+	if last.Ts < now.Unix()-120 {
+		t.Errorf("consolidated alert ts %d should be recent (near %d)", last.Ts, now.Unix())
+	}
+	if last.ID != "alert-ghost-r1-eth0" {
+		t.Errorf("alert ID = %q, want stable alert-ghost-r1-eth0", last.ID)
+	}
+}
+
+// issue #365: un reset de contadores (reboot) NO es un puerto muerto.
+func TestPortMonitorGhostCounterResetNoAlert(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	port, setClock := buildGhostPort(t, pm, engine)
+
+	// Reboot: contadores caen de ~27k a 42 y vuelven a crecer desde ahí.
+	port.RxBytes, port.TxBytes = 42, 0
+	now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
+	for i := 0; i < ghostConsecutive+3; i++ {
+		if i > 0 {
+			port.RxBytes += 100
+		}
+		now = now.Add(45 * time.Second)
+		setClock(now)
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+	if n, _ := findAlerts(engine, "Ghost port: LAN1 went silent"); n != 0 {
+		t.Fatalf("ghost alerts after counter reset = %d, want 0", n)
+	}
+}
+
+// issue #366: al volver el tráfico se emite UNA alerta ok de recuperación.
+func TestPortMonitorGhostRecovery(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	port, setClock := buildGhostPort(t, pm, engine)
+
+	now := time.Date(2026, 8, 29, 13, 0, 0, 0, time.UTC)
+	for i := 0; i < ghostConsecutive; i++ {
+		now = now.Add(45 * time.Second)
+		setClock(now)
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+	if n, _ := findAlerts(engine, "Ghost port: LAN1 went silent"); n != 1 {
+		t.Fatalf("ghost alert not emitted before recovery")
+	}
+	// El tráfico vuelve y se mantiene: una única recuperación.
+	for round := 0; round < 2; round++ {
+		for i := 0; i < 4; i++ {
+			port.RxBytes += 500
+			now = now.Add(45 * time.Second)
+			setClock(now)
+			pm.Observe("r1", []EthPort{port}, engine)
+		}
+	}
+	if n, _ := findAlerts(engine, "Ghost port recovered: LAN1 on r1"); n != 1 {
+		t.Fatalf("recovery alerts = %d, want 1", n)
+	}
+}
+
+// issue #366: flapping persistente también se consolida en una alerta.
+func TestPortMonitorFlappingConsolidatesIntoOneAlert(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+	for i := 0; i < flapThreshold+4; i++ {
+		port.Up = !port.Up
+		now = now.Add(30 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+	if n, _ := findAlerts(engine, "Port flapping: LAN1 on r1"); n != 1 {
+		t.Fatalf("flap alerts = %d, want 1 (consolidated)", n)
+	}
+}