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

feat(alerts): Dead Man's Switch — confirm agent down after 3 min (P6) (#89)

Agent-down alerts fired immediately on the first poller tick after the
90s TTL expired, causing spam during brief network blips (fiber flaps,
router reboots, WiFi disconnects of ~2 min).

Add a confirmation period (agentDownConfirm, default 3 min): the alert
only fires when the agent has been stale for longer than the confirm
threshold (not just the TTL). Between TTL and confirm, the agent
silently degrades to SSH without alerting. A blip that recovers before
the confirm period generates NO alert at all (neither down nor recovery).

- AgentRegistry.StaleFor(slug, threshold): true if lastSeen exceeds threshold
- Live.agentDownConfirm: configurable via NETPULSE_AGENT_DOWN_CONFIRM_S
- pollRouterAgent: uses StaleFor for the DOWN alert, Expired for SSH degrade
- Description now includes the elapsed time (e.g. 'more than 3m0s')

Tests: TestDeadMansSwitch (3-phase: stale-silent → stale-alert → recovery),
TestDeadMansSwitchBlipNoAlert (brief blip → no alerts). Existing
TestLiveAgentFallbackAndRecovery updated with 1ms confirm (immediate).

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

+ 7 - 0
server-go/cmd/netpulse/main.go

@@ -179,6 +179,13 @@ func run() error {
 			sshPool = pool
 			live := adapters.NewLive(cfg, dbHandle, routers, pool)
 			live.SetAgents(agentReg)
+			// Dead Man's Switch (P6): periodo de confirmación antes de
+			// alertar caída de agente (default 3 min, config por env).
+			if v := os.Getenv("NETPULSE_AGENT_DOWN_CONFIRM_S"); v != "" {
+				if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
+					live.SetAgentDownConfirm(time.Duration(sec) * time.Second)
+				}
+			}
 			adapter = live
 		}
 	}

+ 48 - 14
server-go/internal/adapters/agent.go

@@ -93,6 +93,19 @@ func (r *AgentRegistry) Expired(slug string) bool {
 	return ok && r.now().Sub(st.LastSeen) > r.ttl
 }
 
+// StaleFor reporta si el slug lleva más de threshold sin empujar datos.
+// Se usa para el Dead Man's Switch (P6): confirmar que un agente está
+// realmente caído antes de disparar la alerta, evitando spam en flapeos.
+func (r *AgentRegistry) StaleFor(slug string, threshold time.Duration) bool {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, ok := r.states[slug]
+	if !ok || st.LastSeen.IsZero() {
+		return false
+	}
+	return r.now().Sub(st.LastSeen) > threshold
+}
+
 // ActiveCount devuelve cuántos agentes tienen su último push dentro del TTL
 // (métricas operativas de /api/health).
 func (r *AgentRegistry) ActiveCount() int {
@@ -145,8 +158,18 @@ func (r *AgentRegistry) Forget(slug string) {
 // soporte de agentes; todo va por SSH como antes).
 func (l *Live) SetAgents(r *AgentRegistry) {
 	l.mu.Lock()
-	defer l.mu.Unlock()
 	l.agents = r
+	l.mu.Unlock()
+}
+
+// SetAgentDownConfirm fija el periodo de confirmación del Dead Man's Switch
+// (P6): tiempo sin push tras el cual se confirma la caída de un agente.
+func (l *Live) SetAgentDownConfirm(d time.Duration) {
+	l.mu.Lock()
+	if d > 0 {
+		l.agentDownConfirm = d
+	}
+	l.mu.Unlock()
 }
 
 // agentName: nombre para las alertas (cfg.Name o Host como el resto).
@@ -187,20 +210,31 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 		return true, l.polledFromAgent(cfg, p)
 	}
 	if reg.Expired(cfg.ID) {
-		l.mu.Lock()
-		if !l.agentDown[cfg.ID] {
-			l.agentDown[cfg.ID] = true
-			name := agentName(cfg)
-			l.engine.Emit(AlertEvent{
-				ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
-				Category: alerts.CatSystem, Urgent: false,
-				Severity:    "warn",
-				Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),
-				Description: fmt.Sprintf("Sin datos del agente de %s — sondeo SSH reanudado", name),
-				Time:        "ahora mismo", RouterID: cfg.ID,
-			})
+		// Dead Man's Switch (P6): el agente está stale (más allá del TTL),
+		// pero solo disparamos la alerta de caída si lleva más de
+		// agentDownConfirm sin empujar. Entre TTL y agentDownConfirm el
+		// router degrada a SSH silenciosamente (sin alertar), evitando
+		// spam en flapeos breves de fibra/WiFi.
+		confirm := l.agentDownConfirm
+		if confirm <= 0 {
+			confirm = 3 * time.Minute
+		}
+		if reg.StaleFor(cfg.ID, confirm) {
+			l.mu.Lock()
+			if !l.agentDown[cfg.ID] {
+				l.agentDown[cfg.ID] = true
+				name := agentName(cfg)
+				l.engine.Emit(AlertEvent{
+					ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
+					Category: alerts.CatSystem, Urgent: false,
+					Severity:    "warn",
+					Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),
+					Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — sondeo SSH reanudado", name, confirm),
+					Time:        "ahora mismo", RouterID: cfg.ID,
+				})
+			}
+			l.mu.Unlock()
 		}
-		l.mu.Unlock()
 	}
 	return false, nil
 }

+ 79 - 0
server-go/internal/adapters/agent_live_test.go

@@ -100,6 +100,8 @@ func newLiveAgentTest(t *testing.T, reg *AgentRegistry) *Live {
 		{ID: "patio", Name: "Patio", Host: "127.0.0.1", Type: "openwrt"},
 	}, pool)
 	l.SetAgents(reg)
+	// Tests legacy: confirmación inmediata (sin Dead Man's Switch delay).
+	l.SetAgentDownConfirm(time.Millisecond)
 	return l
 }
 
@@ -215,3 +217,80 @@ func TestLiveAgentAntiFlicker(t *testing.T) {
 		t.Fatalf("anti-parpadeo: %+v %+v %+v %+v", p.wireless, p.radios, p.ports, p.fdb)
 	}
 }
+
+// TestDeadMansSwitch verifica que la alerta de caída NO se dispara
+// inmediatamente cuando el agente expira, sino solo tras el periodo de
+// confirmación (agentDownConfirm). Un blip breve (< confirm) no genera
+// alerta; el agente degrada a SSH silenciosamente y se recupera sin alerta.
+func TestDeadMansSwitch(t *testing.T) {
+	reg := NewAgentRegistry(50 * time.Millisecond)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	l := newLiveAgentTest(t, reg)
+	l.SetAgentDownConfirm(200 * time.Millisecond)
+	cfg := RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1"}
+
+	// Push inicial: agente fresco.
+	reg.Ingest(testPayload())
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente fresco: %v", err)
+	}
+
+	// Avanzar 60ms: agente expirado (TTL=50ms) pero NO confirmado (< 200ms).
+	now = now.Add(60 * time.Millisecond)
+	if _, err := l.pollRouter(t.Context(), cfg); err == nil {
+		t.Fatal("con agente expirado debería intentar SSH y fallar")
+	}
+	if a := findAlert(l.engine.List(), "Agente caído"); a != nil {
+		t.Fatalf("NO debería haber alerta de caída tras blip breve: %+v", a)
+	}
+
+	// Avanzar otros 200ms (total 260ms > 200ms confirm): ahora SÍ alerta.
+	now = now.Add(200 * time.Millisecond)
+	if _, err := l.pollRouter(t.Context(), cfg); err == nil {
+		t.Fatal("SSH sigue fallando")
+	}
+	down := findAlert(l.engine.List(), "Agente caído en Patio")
+	if down == nil {
+		t.Fatal("debería haber alerta de caída tras confirmación")
+	}
+
+	// Recuperación: el agente vuelve a empujar → alerta ok.
+	reg.Ingest(testPayload())
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente recuperado: %v", err)
+	}
+	ok := findAlert(l.engine.List(), "Agente recuperado en Patio")
+	if ok == nil {
+		t.Fatal("debería haber alerta de recuperación")
+	}
+}
+
+// TestDeadMansSwitchBlipNoAlert verifica que un blip breve (expira pero
+// recupera antes del confirm) NO genera NINGUNA alerta.
+func TestDeadMansSwitchBlipNoAlert(t *testing.T) {
+	reg := NewAgentRegistry(50 * time.Millisecond)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	l := newLiveAgentTest(t, reg)
+	l.SetAgentDownConfirm(200 * time.Millisecond)
+	cfg := RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1"}
+
+	reg.Ingest(testPayload())
+	l.pollRouter(t.Context(), cfg)
+
+	// Blip: expira (60ms) pero recupera antes del confirm (200ms).
+	now = now.Add(60 * time.Millisecond)
+	l.pollRouter(t.Context(), cfg)
+	reg.Ingest(testPayload())
+	l.pollRouter(t.Context(), cfg)
+
+	if a := findAlert(l.engine.List(), "Agente caído"); a != nil {
+		t.Fatalf("blip breve no debería generar alerta de caída: %+v", a)
+	}
+	if a := findAlert(l.engine.List(), "Agente recuperado"); a != nil {
+		t.Fatalf("blip breve no debería generar alerta de recuperación: %+v", a)
+	}
+}

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

@@ -142,8 +142,9 @@ type Live struct {
 
 	// Agentes nativos (Tier 2): último payload por slug + flag de caída
 	// (degradado a SSH tras emitir la alerta, SPEC-AGENTE-PILOTO §1).
-	agents    *AgentRegistry
-	agentDown map[string]bool
+	agents           *AgentRegistry
+	agentDown        map[string]bool
+	agentDownConfirm time.Duration // Dead Man's Switch: confirmar caída tras este periodo sin alertar
 
 	agStd *AdGuardClient
 	agGL  *AdGuardGlinetClient
@@ -179,7 +180,8 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		wanDown:       map[string]int{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
-		agentDown:     map[string]bool{},
+		agentDown:        map[string]bool{},
+		agentDownConfirm: 3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
 	}
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {