Explorar o código

fix(alerts): consolidate repeated auto-rearm alerts into one per incident (#272)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho hai 3 meses
pai
achega
6f77a407a2

+ 67 - 10
server-go/internal/alerts/alerts.go

@@ -195,23 +195,24 @@ func (e *Engine) SetConfig(patch map[string]string) error {
 	return nil
 }
 
-// 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).
-func (e *Engine) Emit(ev AlertEvent) bool {
-	e.mu.Lock()
+// pasaLocked: ¿el evento supera la config de su categoría? (none descarta;
+// urgent solo deja urgentes; all deja todo). Requiere e.mu ya tomado.
+func (e *Engine) pasaLocked(ev AlertEvent) bool {
 	level, known := e.cfg[ev.Category]
 	if known {
 		if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
-			e.mu.Unlock()
 			return false
 		}
 	}
 	// Categoría desconocida: pasa (la validación estricta es de SetConfig).
-	now := e.now()
+	return true
+}
+
+// insertaLocked inserta un evento nuevo al frente con dedup y cap.
+// Requiere e.mu ya tomado. Devuelve true si se guardó.
+func (e *Engine) insertaLocked(ev AlertEvent, now time.Time) bool {
 	key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
 	if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
-		e.mu.Unlock()
 		return false
 	}
 	e.dedup[key] = now.UnixMilli()
@@ -226,12 +227,68 @@ func (e *Engine) Emit(ev AlertEvent) bool {
 	if len(e.list) > MaxEvents {
 		e.list = e.list[:MaxEvents]
 	}
+	return true
+}
+
+// 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).
+func (e *Engine) Emit(ev AlertEvent) bool {
+	e.mu.Lock()
+	if !e.pasaLocked(ev) {
+		e.mu.Unlock()
+		return false
+	}
+	now := e.now()
+	ok := e.insertaLocked(ev, now)
 	n := e.notifier
 	e.mu.Unlock()
-	if n != nil && ev.Urgent {
+	if ok && n != nil && ev.Urgent {
 		n.Notify(ev)
 	}
-	return true
+	return ok
+}
+
+// EmitOrUpdate: como Emit, pero si YA existe una alerta con el mismo ID, la
+// actualiza en sitio (ts, título, descripción, severidad, urgent, router) y
+// la mueve al frente de la lista (más reciente) en vez de insertar una copia.
+// Diseñado para alertas "en curso" que se actualizan (p.ej. auto-rearme sin
+// recuperación: un incidente = una sola alerta, issue #271). El update NO
+// pasa por el dedup (consolida, no duplica); la inserción de un ID nuevo sí.
+// Devuelve true si el evento pasó la config (insertado o actualizado).
+func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
+	e.mu.Lock()
+	if !e.pasaLocked(ev) {
+		e.mu.Unlock()
+		return false
+	}
+	now := e.now()
+	for i := range e.list {
+		if e.list[i].ID == ev.ID {
+			old := e.list[i]
+			ev.Ts = now.Unix()
+			ev.Time = "ahora mismo"
+			ev.Read = old.Read
+			if ev.RouterID == "" {
+				ev.RouterID = old.RouterID
+			}
+			e.list = append(e.list[:i], e.list[i+1:]...)
+			e.list = append([]AlertEvent{ev}, e.list...)
+			n := e.notifier
+			e.mu.Unlock()
+			if n != nil && ev.Urgent {
+				n.Notify(ev)
+			}
+			return true
+		}
+	}
+	ok := e.insertaLocked(ev, now)
+	n := e.notifier
+	e.mu.Unlock()
+	if ok && n != nil && ev.Urgent {
+		n.Notify(ev)
+	}
+	return ok
 }
 
 // Seed inserta un evento histórico (arranque del modo demo) SIN aplicar el

+ 75 - 0
server-go/internal/alerts/alerts_test.go

@@ -257,3 +257,78 @@ func TestSeedSkipsConfigButKeepsDedup(t *testing.T) {
 		t.Fatalf("lista: %d", got)
 	}
 }
+
+// TestEmitOrUpdateConsolida (#271): re-emitir con el MISMO ID actualiza la
+// alerta existente (ts nuevo, al frente, sin duplicar) en vez de insertar.
+func TestEmitOrUpdateConsolida(t *testing.T) {
+	e := New(nil, nil)
+	now := time.Unix(1_700_000_000, 0)
+	e.SetClock(func() time.Time { return now })
+
+	base := AlertEvent{ID: "fail-patio-1", Category: CatSystem, Severity: "warn",
+		Title: "Auto-rearme sin recuperación en patio", Description: "intento 1",
+		RouterID: "patio"}
+	if !e.EmitOrUpdate(base) {
+		t.Fatal("primer emit debía pasar")
+	}
+	// Mismo ID, descripción nueva: debe actualizar, no duplicar.
+	now = now.Add(10 * time.Minute) // fuera del dedup, pero consolidación por ID
+	upd := base
+	upd.Description = "intento 2"
+	upd.Urgent = true
+	if !e.EmitOrUpdate(upd) {
+		t.Fatal("update del mismo ID debía pasar")
+	}
+	list := e.List()
+	if len(list) != 1 {
+		t.Fatalf("consolidación: quiero 1 evento, hay %d", len(list))
+	}
+	if list[0].Description != "intento 2" {
+		t.Fatalf("descripción no actualizada: %s", list[0].Description)
+	}
+	if list[0].Ts != now.Unix() {
+		t.Fatalf("ts no refrescado: %d, esperaba %d", list[0].Ts, now.Unix())
+	}
+}
+
+// TestEmitOrUpdateIDNuevoInserta (#271): un ID distinto con la misma clave de
+// dedup dentro de la ventana se descarta (misma semántica que Emit).
+func TestEmitOrUpdateIDNuevoInserta(t *testing.T) {
+	e := New(nil, nil)
+	now := time.Unix(1_700_000_000, 0)
+	e.SetClock(func() time.Time { return now })
+	base := AlertEvent{ID: "a1", Category: CatSystem, Severity: "warn",
+		Title: "mismo", RouterID: "r1"}
+	if !e.EmitOrUpdate(base) {
+		t.Fatal("primer emit debía pasar")
+	}
+	// Mismo (cat,title,routerId) pero ID distinto dentro de 5 min → dedup.
+	dup := base
+	dup.ID = "a2"
+	if e.EmitOrUpdate(dup) {
+		t.Fatal("dedup 5 min debía ignorar el ID nuevo")
+	}
+	if got := len(e.List()); got != 1 {
+		t.Fatalf("lista: %d, esperaba 1", got)
+	}
+}
+
+// TestEmitOrUpdateConservaRead (#271): el update no resetea el read-state.
+func TestEmitOrUpdateConservaRead(t *testing.T) {
+	e := New(nil, nil)
+	ev := ev("fail-x", CatSystem, false)
+	if !e.EmitOrUpdate(ev) {
+		t.Fatal("emit debía pasar")
+	}
+	e.MarkRead("fail-x")
+	now := time.Now()
+	e.SetClock(func() time.Time { return now.Add(time.Hour) })
+	if !e.EmitOrUpdate(ev) {
+		t.Fatal("update debía pasar")
+	}
+	for _, x := range e.List() {
+		if !x.Read {
+			t.Fatalf("Read debe conservarse tras el update: %+v", x)
+		}
+	}
+}

+ 63 - 13
server-go/internal/rearmer/rearmer.go

@@ -48,8 +48,11 @@ type SSHRunner interface {
 }
 
 // AlertsEngine: mínimo del motor de alertas que necesita el rearmer.
+// EmitOrUpdate consolida alertas "en curso" por ID (issue #271): el primer
+// fallo crea la alerta; los reintentos la actualizan en vez de duplicar.
 type AlertsEngine interface {
 	Emit(alerts.AlertEvent) bool
+	EmitOrUpdate(alerts.AlertEvent) bool
 }
 
 // Result es el resultado de un intento de rearme.
@@ -83,6 +86,7 @@ type Rearmer struct {
 	pool     SSHRunner
 	engine   AlertsEngine
 	pollWait time.Duration
+	cooldown time.Duration
 
 	mu        sync.Mutex
 	lastRearm map[string]time.Time
@@ -96,7 +100,7 @@ func New(db *sql.DB, agents *adapters.AgentRegistry, pool SSHRunner, engine Aler
 	}
 	return &Rearmer{
 		db: db, agents: agents, pool: pool, engine: engine,
-		pollWait: pollWait, lastRearm: map[string]time.Time{},
+		pollWait: pollWait, cooldown: Cooldown, lastRearm: map[string]time.Time{},
 	}
 }
 
@@ -107,6 +111,14 @@ func (r *Rearmer) SetPollWait(d time.Duration) {
 	}
 }
 
+// SetCooldown ajusta el anti-martilleo manual por slug (solo tests; en prod
+// el cooldown del supervisor de 600 s manda y nunca llega a este de 60 s).
+func (r *Rearmer) SetCooldown(d time.Duration) {
+	if d > 0 {
+		r.cooldown = d
+	}
+}
+
 // Rearm ejecuta un rearme completo del slug. Errores tipificados
 // (ErrNoDB, ErrNoToken, ErrNoRouter, ErrNoSSH, ErrCooldown) para que el
 // handler HTTP los mapee a su status; cualquier otro error es fallo SSH.
@@ -137,8 +149,8 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 
 	// Anti-martilleo por slug (manual).
 	r.mu.Lock()
-	if last, ok := r.lastRearm[slug]; ok && time.Since(last) < Cooldown {
-		wait := Cooldown - time.Since(last)
+	if last, ok := r.lastRearm[slug]; ok && time.Since(last) < r.cooldown {
+		wait := r.cooldown - time.Since(last)
 		r.mu.Unlock()
 		return Result{}, ErrCooldown{Wait: wait}
 	}
@@ -213,6 +225,12 @@ type Supervisor struct {
 	mu    sync.Mutex
 	slots map[string]time.Time
 
+	// failIDs: slug → ID de la alerta de fallo abierta (issue #271). Mientras
+	// el incidente persiste, los reintentos actualizan esa misma alerta en vez
+	// de insertar una copia cada cooldown. Al recuperarse se borra la entrada
+	// y el próximo fallo vuelve a crear una alerta nueva.
+	failIDs map[string]string
+
 	stop chan struct{}
 	done chan struct{}
 }
@@ -229,8 +247,8 @@ func NewSupervisor(r *Rearmer, registry *adapters.AgentRegistry, db *sql.DB, eng
 	return &Supervisor{
 		rearmer: r, registry: registry, db: db, engine: engine,
 		interval: interval, cooldown: cooldown,
-		slots: map[string]time.Time{},
-		stop:  make(chan struct{}), done: make(chan struct{}),
+		slots: map[string]time.Time{}, failIDs: map[string]string{},
+		stop: make(chan struct{}), done: make(chan struct{}),
 	}
 }
 
@@ -269,6 +287,10 @@ func (s *Supervisor) CheckOnce() {
 		// fuera del TTL. Un slug sin push nunca visto no se rearma (no hay
 		// evidencia de que el servicio haya estado vivo).
 		if !s.registry.Expired(slug) {
+			// El agente volvió a empujar (recuperado sin rearme): si había
+			// una alerta de fallo abierta, se cierra el incidente (issue
+			// #271) para que el próximo fallo cree una alerta nueva.
+			s.closeFailID(slug)
 			continue
 		}
 		if !s.slotFree(slug) {
@@ -281,16 +303,44 @@ func (s *Supervisor) CheckOnce() {
 			continue
 		}
 		s.markSlot(slug)
-		if !res.Recovered && s.engine != nil {
-			s.engine.Emit(alerts.AlertEvent{
-				ID:       fmt.Sprintf("alert-agent-autorearm-fail-%s-%d", slug, time.Now().UnixMilli()),
-				Category: alerts.CatSystem, Urgent: false, Severity: "warn",
-				Title:       fmt.Sprintf("Auto-rearme sin recuperación en %s", slug),
-				Description: fmt.Sprintf("El supervisor reinició netpulse-agent en %s pero el agente no ha vuelto a empujar; próximo intento en %d s", slug, int(s.cooldown.Seconds())),
-				Time:        "ahora mismo", RouterID: slug,
-			})
+		if res.Recovered {
+			// Rearme con éxito: incidente cerrado.
+			s.closeFailID(slug)
+			continue
 		}
+		if s.engine != nil {
+			s.emitFail(slug)
+		}
+	}
+}
+
+// emitFail: alerta consolidada de fallo (issue #271). La primera vez del
+// incidente crea la alerta con ID = slug + timestamp del primer fallo; cada
+// reintento del MISMO incidente la actualiza (EmitOrUpdate) en vez de
+// insertar una copia. Al recuperarse se cierra el incidente (closeFailID) y
+// el próximo fallo vuelve a crear una alerta nueva.
+func (s *Supervisor) emitFail(slug string) {
+	s.mu.Lock()
+	id, ok := s.failIDs[slug]
+	if !ok {
+		id = fmt.Sprintf("alert-agent-autorearm-fail-%s-%d", slug, time.Now().UnixMilli())
+		s.failIDs[slug] = id
 	}
+	s.mu.Unlock()
+	s.engine.EmitOrUpdate(alerts.AlertEvent{
+		ID:          id,
+		Category:    alerts.CatSystem, Urgent: false, Severity: "warn",
+		Title:       fmt.Sprintf("Auto-rearme sin recuperación en %s", slug),
+		Description: fmt.Sprintf("El supervisor reinició netpulse-agent en %s pero el agente no ha vuelto a empujar; próximo intento en %d s", slug, int(s.cooldown.Seconds())),
+		Time:        "ahora mismo", RouterID: slug,
+	})
+}
+
+// closeFailID: borra el ID de fallo abierto del slug (incidente resuelto).
+func (s *Supervisor) closeFailID(slug string) {
+	s.mu.Lock()
+	delete(s.failIDs, slug)
+	s.mu.Unlock()
 }
 
 // registeredSlugs: slugs con token en kv (agent.token.*).

+ 92 - 0
server-go/internal/rearmer/rearmer_test.go

@@ -49,6 +49,19 @@ func (f *fakeEngine) Emit(ev alerts.AlertEvent) bool {
 	return true
 }
 
+func (f *fakeEngine) EmitOrUpdate(ev alerts.AlertEvent) bool {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	for i := range f.evs {
+		if f.evs[i].ID == ev.ID {
+			f.evs[i] = ev
+			return true
+		}
+	}
+	f.evs = append(f.evs, ev)
+	return true
+}
+
 func (f *fakeEngine) count() int {
 	f.mu.Lock()
 	defer f.mu.Unlock()
@@ -196,6 +209,85 @@ func TestSupervisorAlertaSinRecuperacion(t *testing.T) {
 	}
 }
 
+// TestSupervisorConsolidaFallosRepetidos (#271): N reintentos fallidos del
+// mismo slug → UNA sola alerta (mismo ID, actualizada), no N copias.
+func TestSupervisorConsolidaFallosRepetidos(t *testing.T) {
+	env := makeRearmEnv(t, "patio")
+	env.pushViejo("patio")
+	env.expira(time.Minute)
+
+	// pollWait corto para no dormir; cooldowns cortos para poder reintentar
+	// en el mismo test (en prod supervisor 600 s y Rearmer 60 s).
+	env.arm.SetPollWait(50 * time.Millisecond)
+	env.arm.SetCooldown(5 * time.Millisecond)
+	sup := rearmer.NewSupervisor(env.arm, env.reg, env.d.DB, env.engine, time.Hour, 20*time.Millisecond)
+
+	for i := 0; i < 3; i++ {
+		sup.CheckOnce()
+		time.Sleep(40 * time.Millisecond) // deja pasar el cooldown del slot
+	}
+
+	if got := env.ssh.count(); got != 3 {
+		t.Fatalf("quiero 3 reintentos SSH, tuve %d", got)
+	}
+	evs := env.engine.events()
+	fails := []alerts.AlertEvent{}
+	for _, ev := range evs {
+		if ev.Title == "Auto-rearme sin recuperación en patio" {
+			fails = append(fails, ev)
+		}
+	}
+	if len(fails) != 1 {
+		t.Fatalf("3 fallos debían consolidarse en 1 alerta de fallo, hay %d", len(fails))
+	}
+	if len(evs) > 0 && evs[0].Title == "Auto-rearme sin recuperación en patio" && evs[0].ID != fails[0].ID {
+		t.Fatalf("el ID de la alerta consolidada debe ser el del primer fallo: %s", fails[0].ID)
+	}
+}
+
+// TestSupervisorRecuperadoCierraIncidente (#271): al recuperarse el agente
+// (vuelve a empujar) se cierra el incidente; un fallo posterior crea una
+// alerta NUEVA (ID distinto), no actualiza la vieja.
+func TestSupervisorRecuperadoCierraIncidente(t *testing.T) {
+	env := makeRearmEnv(t, "patio")
+	env.pushViejo("patio")
+	env.expira(time.Minute)
+
+	env.arm.SetPollWait(50 * time.Millisecond)
+	env.arm.SetCooldown(5 * time.Millisecond)
+	sup := rearmer.NewSupervisor(env.arm, env.reg, env.d.DB, env.engine, time.Hour, 20*time.Millisecond)
+
+	// Incidente 1: fallo → 1 alerta.
+	sup.CheckOnce()
+	first := env.engine.events()
+	if len(first) != 1 || first[0].Title != "Auto-rearme sin recuperación en patio" {
+		t.Fatalf("incidente 1: quiero 1 alerta de fallo, hay %+v", first)
+	}
+
+	// El agente se recupera: vuelve a empujar (dentro del TTL).
+	env.reg.Ingest(&probe.Payload{Router: "patio", Ts: env.now.Unix(), Version: "2.3.0"})
+	sup.CheckOnce() // este tick ve el slug sano → cierra el incidente
+
+	// Incidente 2: el agente vuelve a expirar y falla → alerta NUEVA.
+	env.expira(time.Minute)
+	time.Sleep(40 * time.Millisecond)
+	sup.CheckOnce()
+
+	evs := env.engine.events()
+	fails := []alerts.AlertEvent{}
+	for _, ev := range evs {
+		if ev.Title == "Auto-rearme sin recuperación en patio" {
+			fails = append(fails, ev)
+		}
+	}
+	if len(fails) != 2 {
+		t.Fatalf("dos incidentes → 2 alertas de fallo (una por incidente), hay %d", len(fails))
+	}
+	if fails[0].ID == fails[1].ID {
+		t.Fatalf("incidentes distintos deben tener IDs distintos: %s == %s", fails[0].ID, fails[1].ID)
+	}
+}
+
 func TestSupervisorRecuperadoSinAlertaFallo(t *testing.T) {
 	env := makeRearmEnv(t, "patio")
 	env.pushViejo("patio")