Bläddra i källkod

feat(alerts): topology-based alert suppression (#332) (#353)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 månader sedan
förälder
incheckning
b764da16e6

+ 4 - 0
app/public/locales/en/translation.json

@@ -1435,5 +1435,9 @@
       "warn": "Warning",
       "critical": "Critical"
     }
+  },
+  "alertSuppression": {
+    "suppressedBy": "Suppressed by {{router}}",
+    "suppressedHint": "This alert is suppressed because a parent router is offline."
   }
 }

+ 4 - 0
app/public/locales/es/translation.json

@@ -1435,5 +1435,9 @@
       "warn": "Aviso",
       "critical": "Crítico"
     }
+  },
+  "alertSuppression": {
+    "suppressedBy": "Suprimida por {{router}}",
+    "suppressedHint": "Esta alerta está suprimida porque un router padre está offline."
   }
 }

+ 2 - 0
app/src/data/types.ts

@@ -269,6 +269,8 @@ export interface AlertEvent {
   ts: number
   read: boolean
   routerId?: string
+  /** Router padre que suprime esta alerta (issue #332). Ausente si no aplica. */
+  suppressedBy?: string
 }
 
 // ---------------------------------------------------------------------------

+ 5 - 0
app/src/pages/Alerts.tsx

@@ -317,6 +317,11 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence }: Fee
           {ev.hint && (
             <p className="mt-0.5 truncate text-caption italic text-text-muted">{ev.hint}</p>
           )}
+          {ev.suppressedBy && (
+            <p className="mt-0.5 truncate text-caption text-text-muted" title={t('alertSuppression.suppressedHint')}>
+              {t('alertSuppression.suppressedBy', { router: ev.suppressedBy })}
+            </p>
+          )}
         </div>
         <ChevronRight
           className={cn('h-4 w-4 shrink-0 text-text-muted transition-transform duration-200', expanded && 'rotate-90')}

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

@@ -252,6 +252,10 @@ type Live struct {
 	// detección de flapping, ghost port y link degradado.
 	portMon *PortMonitor
 
+	// suppression (issue #332): grafo de dependencias topológicas para
+	// suprimir alertas hijas cuando un router padre está offline.
+	suppression *alerts.SuppressionGraph
+
 	// now: reloj inyectable para tests deterministas (nil → time.Now).
 	// Mismo patrón que AgentRegistry.SetClock.
 	now func() time.Time
@@ -306,8 +310,10 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		routerMacs:           map[string]string{},
 		sshAuthFailAlerted:   map[string]bool{},
 		portMon:              NewPortMonitor(),
+		suppression:         alerts.NewSuppressionGraph(),
 	}
 	l.loadRouterMacs()
+	l.engine.SetSuppression(l.suppression)
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
 		var flag string
@@ -1193,6 +1199,9 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 			if name == "" {
 				name = res.cfg.Host
 			}
+			if l.suppression != nil {
+				l.suppression.MarkDown(res.cfg.ID)
+			}
 			l.engine.Emit(AlertEvent{
 				ID:       fmt.Sprintf("alert-offline-%s-%d", res.cfg.ID, time.Now().UnixMilli()),
 				Category: alerts.CatRouter, Urgent: true,
@@ -1215,6 +1224,9 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 // category router, urgent false, severity ok — SPEC-ALERTAS §1).
 // Debe llamarse con l.mu tomado (mismo contexto que el resto de emisiones).
 func (l *Live) emitRouterRecovered(routerID, name string) {
+	if l.suppression != nil {
+		l.suppression.MarkUp(routerID)
+	}
 	l.engine.Emit(AlertEvent{
 		ID:       fmt.Sprintf("alert-recovered-%s-%d", routerID, time.Now().UnixMilli()),
 		Category: alerts.CatRouter, Urgent: false,
@@ -2048,6 +2060,19 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	if l.db != nil {
 		devices, distNodes = applyTopologyOverrides(devices, distNodes, loadTopologyOverrides(l.db))
 	}
+	// Supresión topológica (#332): actualizar grafo parent→child.
+	// Todos los no-gateway cuelgan del gateway.
+	l.mu.Lock()
+	if gw != nil && l.suppression != nil {
+		parents := map[string]string{}
+		for _, r := range routers {
+			if r.ID != gw.ID {
+				parents[r.ID] = gw.ID
+			}
+		}
+		l.suppression.SetTopology(parents)
+	}
+	l.mu.Unlock()
 	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
 	for _, d := range devices {
 		if d.Online && d.SignalDbm != nil && *d.SignalDbm < -70 {

+ 23 - 1
server-go/internal/alerts/alerts.go

@@ -67,6 +67,9 @@ type AlertEvent struct {
 	Ts       int64  `json:"ts"`   // unix SEGUNDOS; el frontend calcula el relativo
 	Read     bool   `json:"read"`
 	RouterID string `json:"routerId"`
+	// SuppressedBy is the routerId of the parent router whose offline alert
+	// is suppressing this one (issue #332). Empty when not suppressed.
+	SuppressedBy string `json:"suppressedBy,omitempty"`
 }
 
 // Stable alert-type slugs (issue #310): keys of the Hints map.
@@ -137,6 +140,10 @@ type Engine struct {
 	readSet map[string]bool
 	readOrd []string // FIFO de IDs (cap 200) para podar readSet
 	silenceMap map[string]int64 // dedup key → expiry (unix seconds); 0 = forever
+
+	// suppression: grafo de dependencias topológicas (issue #332).
+	// nil = sin supresión (tests o sin topología).
+	suppression *SuppressionGraph
 }
 
 // New crea el motor cargando config y read-state de kv (si db != nil).
@@ -195,6 +202,14 @@ func (e *Engine) SetClock(f func() time.Time) {
 	e.now = f
 }
 
+// SetSuppression wirea el grafo de dependencias topológicas (issue #332).
+// nil desactiva la supresión (tests o arranque sin topología).
+func (e *Engine) SetSuppression(g *SuppressionGraph) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	e.suppression = g
+}
+
 // Config devuelve una copia de la config efectiva (siempre las 6 claves).
 func (e *Engine) Config() map[string]string {
 	e.mu.Lock()
@@ -279,17 +294,24 @@ func (e *Engine) insertaLocked(ev AlertEvent, now time.Time) bool {
 // Emit aplica la semántica none/urgent/all EN CREACIÓN, el dedup de 5 min y
 // el cap de 100; devuelve true si el evento pasó (se guardó). Los urgentes
 // que pasan disparan el Notifier (hook de Bloque C).
+// Supresión topológica (#332): si el router tiene un padre offline en el
+// grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
 func (e *Engine) Emit(ev AlertEvent) bool {
 	e.mu.Lock()
 	if !e.pasaLocked(ev) {
 		e.mu.Unlock()
 		return false
 	}
+	if e.suppression != nil && ev.RouterID != "" {
+		if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
+			ev.SuppressedBy = parent
+		}
+	}
 	now := e.now()
 	ok := e.insertaLocked(ev, now)
 	n := e.notifier
 	e.mu.Unlock()
-	if ok && n != nil && ev.Urgent {
+	if ok && n != nil && ev.Urgent && ev.SuppressedBy == "" {
 		n.Notify(ev)
 	}
 	return ok

+ 85 - 0
server-go/internal/alerts/suppression.go

@@ -0,0 +1,85 @@
+package alerts
+
+import (
+	"sync"
+)
+
+// SuppressionGraph models router parent-child relationships for alert
+// suppression: if a parent router is offline, child router alerts are marked
+// as suppressed instead of discarded (issue #332).
+type SuppressionGraph struct {
+	mu      sync.RWMutex
+	parent  map[string]string   // child -> parent routerId
+	down    map[string]bool     // routerId -> currently offline
+}
+
+func NewSuppressionGraph() *SuppressionGraph {
+	return &SuppressionGraph{
+		parent: map[string]string{},
+		down:   map[string]bool{},
+	}
+}
+
+// SetTopology replaces the parent map with fresh topology data.
+// parent maps child routerId to its parent routerId.
+func (g *SuppressionGraph) SetTopology(parent map[string]string) {
+	g.mu.Lock()
+	defer g.mu.Unlock()
+	g.parent = make(map[string]string, len(parent))
+	for k, v := range parent {
+		g.parent[k] = v
+	}
+}
+
+// MarkDown records a router as offline.
+func (g *SuppressionGraph) MarkDown(routerID string) {
+	g.mu.Lock()
+	defer g.mu.Unlock()
+	g.down[routerID] = true
+}
+
+// MarkUp clears a router's offline status.
+func (g *SuppressionGraph) MarkUp(routerID string) {
+	g.mu.Lock()
+	defer g.mu.Unlock()
+	delete(g.down, routerID)
+}
+
+// IsDown reports whether a router is currently offline.
+func (g *SuppressionGraph) IsDown(routerID string) bool {
+	g.mu.RLock()
+	defer g.mu.RUnlock()
+	return g.down[routerID]
+}
+
+// SuppressedBy returns the routerId suppressing alerts for child, or ""
+// if none. It walks up the parent chain: if any ancestor is down, that
+// ancestor suppresses the child.
+func (g *SuppressionGraph) SuppressedBy(child string) string {
+	g.mu.RLock()
+	defer g.mu.RUnlock()
+	visited := map[string]bool{}
+	cur := child
+	for {
+		p, ok := g.parent[cur]
+		if !ok || p == "" || visited[p] {
+			return ""
+		}
+		visited[p] = true
+		if g.down[p] {
+			return p
+		}
+		cur = p
+	}
+}
+
+// DownRouters returns a copy of the current down set.
+func (g *SuppressionGraph) DownRouters() []string {
+	g.mu.RLock()
+	defer g.mu.RUnlock()
+	out := make([]string, 0, len(g.down))
+	for id := range g.down {
+		out = append(out, id)
+	}
+	return out
+}

+ 108 - 0
server-go/internal/alerts/suppression_test.go

@@ -0,0 +1,108 @@
+package alerts
+
+import (
+	"testing"
+)
+
+func TestSuppressionGraphBasic(t *testing.T) {
+	g := NewSuppressionGraph()
+	g.SetTopology(map[string]string{
+		"ap-sala":  "gateway",
+		"ap-patio": "gateway",
+	})
+
+	if g.SuppressedBy("ap-sala") != "" {
+		t.Fatal("no parent should suppress when no one is down")
+	}
+
+	g.MarkDown("gateway")
+	if got := g.SuppressedBy("ap-sala"); got != "gateway" {
+		t.Fatalf("expected gateway, got %q", got)
+	}
+	if got := g.SuppressedBy("ap-patio"); got != "gateway" {
+		t.Fatalf("expected gateway, got %q", got)
+	}
+	if got := g.SuppressedBy("gateway"); got != "" {
+		t.Fatalf("gateway itself should not be suppressed, got %q", got)
+	}
+
+	g.MarkUp("gateway")
+	if g.SuppressedBy("ap-sala") != "" {
+		t.Fatal("after MarkUp, no suppression")
+	}
+}
+
+func TestSuppressionGraphChain(t *testing.T) {
+	g := NewSuppressionGraph()
+	g.SetTopology(map[string]string{
+		"switch-1": "gateway",
+		"ap-sala":  "switch-1",
+	})
+
+	g.MarkDown("gateway")
+	if got := g.SuppressedBy("ap-sala"); got != "gateway" {
+		t.Fatalf("chain: expected gateway, got %q", got)
+	}
+
+	g.MarkUp("gateway")
+	g.MarkDown("switch-1")
+	if got := g.SuppressedBy("ap-sala"); got != "switch-1" {
+		t.Fatalf("chain: expected switch-1, got %q", got)
+	}
+}
+
+func TestSuppressionGraphCycleSafe(t *testing.T) {
+	g := NewSuppressionGraph()
+	g.SetTopology(map[string]string{
+		"a": "b",
+		"b": "a",
+	})
+	g.MarkDown("a")
+	if got := g.SuppressedBy("b"); got != "a" {
+		t.Fatalf("cycle: expected a, got %q", got)
+	}
+	if got := g.SuppressedBy("c"); got != "" {
+		t.Fatalf("unknown node: expected empty, got %q", got)
+	}
+}
+
+func TestSuppressionInEmit(t *testing.T) {
+	g := NewSuppressionGraph()
+	g.SetTopology(map[string]string{"ap": "gw"})
+	g.MarkDown("gw")
+
+	spy := &spyNotifier{}
+	e := New(nil, spy)
+	e.SetSuppression(g)
+
+	ev := AlertEvent{
+		ID: "alert-offline-ap", Category: CatRouter, Urgent: true,
+		Severity: "critical", Title: "AP offline", RouterID: "ap",
+	}
+	if !e.Emit(ev) {
+		t.Fatal("emit should pass (router:urgent + urgent=true)")
+	}
+
+	list := e.List()
+	if len(list) != 1 {
+		t.Fatalf("expected 1 event, got %d", len(list))
+	}
+	if list[0].SuppressedBy != "gw" {
+		t.Fatalf("expected SuppressedBy=gw, got %q", list[0].SuppressedBy)
+	}
+	if len(spy.got) != 0 {
+		t.Fatal("suppressed alert should NOT notify")
+	}
+}
+
+func TestSuppressionNilGraph(t *testing.T) {
+	spy := &spyNotifier{}
+	e := New(nil, spy)
+	e.Emit(AlertEvent{
+		ID: "a1", Category: CatSystem, Urgent: true,
+		Severity: "warn", Title: "x", RouterID: "r",
+	})
+	if len(spy.got) != 1 {
+		t.Fatal("nil suppression should not block notification")
+	}
+}