alerts.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. // Package alerts — motor de alertas (SPEC-ALERTAS §1-3): dueño de la lista
  2. // de eventos (máx 100, más recientes primero), config por categoría con 3
  3. // niveles (none/urgent/all) aplicada EN CREACIÓN, dedup de 5 min por
  4. // (category,title,routerId), read-state en servidor y hook Notifier para el
  5. // push (Bloque C; nil = no-op).
  6. //
  7. // Persistencia: tabla kv (misma DB que el resto del servidor):
  8. // - alerts.config.v1: JSON {"router":"urgent",...} (6 claves, defaults).
  9. // - alerts.read.v1: JSON array de IDs leídos (cap 200, FIFO).
  10. package alerts
  11. import (
  12. "encoding/json"
  13. "fmt"
  14. "sort"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/db"
  19. )
  20. // Categorías (taxonomía exacta del SPEC §1).
  21. const (
  22. CatRouter = "router"
  23. CatInternet = "internet"
  24. CatClients = "clients"
  25. CatSignal = "signal"
  26. CatVPN = "vpn"
  27. CatSystem = "system"
  28. )
  29. // Categories lista las 6 categorías válidas (orden estable para mensajes).
  30. var Categories = []string{CatRouter, CatInternet, CatClients, CatSignal, CatVPN, CatSystem}
  31. // Niveles de configuración por categoría (SPEC §2).
  32. const (
  33. LevelNone = "none" // el evento se descarta (no se guarda, no cuenta, no empuja)
  34. LevelUrgent = "urgent" // solo pasan eventos Urgent=true
  35. LevelAll = "all" // pasan todos (los urgentes además notifican)
  36. )
  37. var levels = map[string]bool{LevelNone: true, LevelUrgent: true, LevelAll: true}
  38. // Claves kv y límites (SPEC §2-3).
  39. const (
  40. configKey = "alerts.config.v1"
  41. readKey = "alerts.read.v1"
  42. silenceKey = "alerts.silence.v1"
  43. dismissKey = "alerts.dismissed.v1"
  44. MaxEvents = 100
  45. MaxReadIDs = 200
  46. DedupWindow = 5 * time.Minute
  47. )
  48. // AlertEvent (máx 100 en memoria, más recientes primero).
  49. type AlertEvent struct {
  50. ID string `json:"id"`
  51. Category string `json:"category"` // taxonomía SPEC §1
  52. Urgent bool `json:"urgent"` // "rompe silencio" (push + badge)
  53. Severity string `json:"severity"` // display: "warn"|"critical"|"info"|"ok"
  54. Title string `json:"title"`
  55. Description string `json:"description"`
  56. // Hint is an actionable suggestion per alert type (issue #310).
  57. // Filled at emission time from the Hints map; absent when not applicable.
  58. Hint string `json:"hint,omitempty"`
  59. Time string `json:"time"` // LEGADO display; se sigue rellenando
  60. Ts int64 `json:"ts"` // unix SEGUNDOS; el frontend calcula el relativo
  61. Read bool `json:"read"`
  62. RouterID string `json:"routerId"`
  63. // Type: slug estable del tipo de alerta (issue #310). Cuando viaja
  64. // (#671), el frontend traduce título/descripción/hint por clave i18n
  65. // (alerts.types.<slug>.title/.description y alerts.hints.<slug>) en el
  66. // idioma del usuario; los literales Title/Description/Hint siguen en el
  67. // evento como fallback (servidores viejos, demo, claves sin traducir).
  68. Type string `json:"type,omitempty"`
  69. // Vars: valores de interpolación para esas claves (router, mac, temp…).
  70. Vars map[string]string `json:"vars,omitempty"`
  71. // SuppressedBy is the routerId of the parent router whose offline alert
  72. // is suppressing this one (issue #332). Empty when not suppressed.
  73. SuppressedBy string `json:"suppressedBy,omitempty"`
  74. // ResolvedTs (#1349): unix SEGUNDOS de cuándo se resolvió la condición.
  75. // 0/ausente = activa. El evento resuelto NO se borra del log: queda
  76. // marcado para revisión posterior (pestaña Resueltas) y una
  77. // reincidencia con el mismo ID estable lo des-resuelve (upsert).
  78. ResolvedTs int64 `json:"resolvedTs,omitempty"`
  79. // Resolves (#1349): IDs de los eventos que este evento CIERRA (p. ej.
  80. // "Agent updated" resuelve "alert-agent-outdated-<id>"). La UI los
  81. // muestra al expandir el evento de cierre.
  82. Resolves []string `json:"resolves,omitempty"`
  83. // Resolved (#1466): datos de los eventos que este evento cerró (título,
  84. // ts de disparo, tipo y vars para traducir). El feed se pagina (20 por
  85. // página): el evento resuelto puede NO estar en la página que el cliente
  86. // tiene cargada, así que el payload va autocontenido y la UI no depende
  87. // de buscarlo en su feed local.
  88. Resolved []ResolvedEvent `json:"resolved,omitempty"`
  89. // Volatile (#966): la alerta vive SOLO en memoria (no se persiste en
  90. // alert_log ni sobrevive a reinicios) y desaparece del feed cuando su
  91. // condicion se resuelve (engine.Remove). Uso: caida de agente, cuya
  92. // semantica es "viva por router", no un historico de incidentes.
  93. Volatile bool `json:"-"`
  94. // seeded: fixture del dataset demo (Seed). No lo somete el filtro de
  95. // nivel "none" (#1659): la historia canónica del demo se sirve completa
  96. // aunque su config deje la categoría en "none".
  97. seeded bool
  98. }
  99. // ResolvedEvent (#1466): datos mínimos del evento que un cierre resolvió.
  100. // Type+Vars permiten traducir el título en el front; Title/Ts son el
  101. // fallback literal y el instante del disparo original.
  102. type ResolvedEvent struct {
  103. ID string `json:"id"`
  104. Title string `json:"title,omitempty"`
  105. Ts int64 `json:"ts"`
  106. Type string `json:"type,omitempty"`
  107. Vars map[string]string `json:"vars,omitempty"`
  108. }
  109. // Stable alert-type slugs (issue #310): keys of the Hints map.
  110. const (
  111. HintAgentDown = "agent-down"
  112. HintAgentDownSSH = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
  113. HintGatewayUnrch = "gateway-unreachable"
  114. HintHighTemp = "high-temperature"
  115. HintPortFlapping = "port-flapping"
  116. HintDeviceOffline = "device-offline"
  117. HintUnknownDevice = "unknown-device"
  118. HintSsidImpostor = "wifi-ssid-impostor"
  119. HintNewNeighborSsid = "new-neighbor-ssid"
  120. HintNewClient = "new-client"
  121. HintFirmware = "firmware-outdated"
  122. // #1412: el target configurado es MÁS VIEJO que lo instalado (posible
  123. // downgrade, casi siempre un target mal puesto).
  124. HintFirmwareDowngrade = "firmware-downgrade-target"
  125. // #1444: el target configurado NO figura entre los releases publicados
  126. // de OpenWrt (chequeo periódico contra downloads.openwrt.org). Es un
  127. // aviso de configuración, no una alerta de firmware desactualizado.
  128. HintFirmwareUnknownTarget = "firmware-target-unknown"
  129. HintWanDown = "wan-down"
  130. HintWifiWeak = "wifi-weak"
  131. HintGhostPort = "ghost-port"
  132. HintDegradedLink = "degraded-link"
  133. HintAgentOutdated = "agent-outdated"
  134. HintWanSlow = "wan-slow"
  135. HintUplinkSwitch = "uplink-switched"
  136. HintSnmpFailing = "snmp-failing"
  137. )
  138. // Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
  139. // types emitted without Type/Vars in #671. They carry no hint.
  140. const (
  141. TypeAgentRecovered = "agent-recovered"
  142. TypeSSHAccessLost = "ssh-access-lost"
  143. TypeSSHAccessRecovered = "ssh-access-recovered"
  144. TypeAgentUpdated = "agent-updated"
  145. TypeRouterRecovered = "router-recovered"
  146. TypeWireguardHandshake = "wireguard-handshake"
  147. TypeWireguardDisconnect = "wireguard-disconnect"
  148. TypePortStable = "port-stable"
  149. TypeGhostPortRecovered = "ghost-port-recovered"
  150. TypeLinkRecovered = "link-recovered"
  151. TypeSwitchLoop = "switch-loop"
  152. TypePortDisabled = "port-disabled"
  153. TypePortRecovered = "port-recovered"
  154. TypeLinkDown = "link-down"
  155. TypeLinkUp = "link-up"
  156. TypeSfpRxLow = "sfp-rx-low"
  157. TypeSfpTempHigh = "sfp-temp-high"
  158. TypeSwitchRebooted = "switch-rebooted"
  159. TypeAgentRearmed = "agent-rearmed"
  160. TypeAgentReinstalled = "agent-reinstalled"
  161. TypeAutoRearmFailed = "auto-rearm-failed"
  162. TypeUplinkRestored = "uplink-restored"
  163. TypeSnmpRecovered = "snmp-recovered"
  164. // #1354: router offline (was reused from HintDeviceOffline, now its own slug)
  165. // and client device offline (opt-in, volatile).
  166. TypeRouterOffline = "router-offline"
  167. TypeDeviceOffline = "device-offline"
  168. // #1452: cierre automático de la alerta de señal débil (episodio
  169. // resuelto con valor de recuperación y duración).
  170. TypeWifiWeakRecovered = "wifi-weak-recovered"
  171. // #1873: una MAC que solo aparece en una tabla de reenvío, sin lease,
  172. // ARP, ND ni mDNS, y que sigue ahí mucho rato. Informativa, no urgente.
  173. TypeUnverifiedMac = "unverified-mac"
  174. // TypeWiFiNoIP: cliente asociado por WiFi que no tiene dirección (#2111).
  175. // Informativa, no urgente: es una marca visible, no un problema.
  176. TypeWiFiNoIP = "wifi-no-ip"
  177. )
  178. // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
  179. // the value into AlertEvent.Hint; the feed and push render it as a helper line.
  180. // The canonical language is English (#1014): alertlang and the web feed swap
  181. // it for the catalog wording when the target language is Spanish.
  182. var Hints = map[string]string{
  183. HintAgentDown: "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
  184. HintAgentDownSSH: "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
  185. HintGatewayUnrch: "Check the connection between the gateway and the rest of the network.",
  186. HintHighTemp: "Improve ventilation and keep the router away from heat sources.",
  187. HintPortFlapping: "Check the cable or switch port: an unstable link is usually the culprit.",
  188. HintDeviceOffline: "Verify the device power and network cable.",
  189. HintUnknownDevice: "If you do not recognize it, block it or mark it as trusted in Settings.",
  190. HintSsidImpostor: "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
  191. HintNewNeighborSsid: "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
  192. HintNewClient: "A device just joined the network for the first time. If you recognize it, name it or mark it as trusted in Settings; if not, check what it is.",
  193. HintFirmware: "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
  194. HintFirmwareDowngrade: "The configured target is older than the installed firmware; fix the target version in the fleet unit settings.",
  195. HintWanDown: "Check the modem/ONT and contact your ISP if the outage persists.",
  196. HintWifiWeak: "Move the device closer to an access point or relocate the AP.",
  197. HintGhostPort: "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
  198. HintDegradedLink: "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
  199. HintAgentOutdated: "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
  200. HintUplinkSwitch: "Check the line that dropped: the router goes back to it on its own once it recovers.",
  201. HintWanSlow: "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
  202. HintSnmpFailing: "Check the SNMP community string and switch port: the device answers ping but not polling.",
  203. }
  204. // HintFor returns the suggestion for a slug, or "" when it does not exist.
  205. func HintFor(slug string) string { return Hints[slug] }
  206. // Notifier es el hook de notificación externa (push/webhook/telegram/ntfy).
  207. // El engine lo dispara solo para eventos cuya categoría permite notificación
  208. // según el nivel configurado (#1413): none nunca, urgent solo Urgent, all
  209. // siempre. La decisión de urgencia fina por canal sigue en cada integración
  210. // (#874, urgencyGate). Los eventos suprimidos topológicamente se guardan con
  211. // SuppressedBy y nunca notifican.
  212. type Notifier interface {
  213. Notify(ev AlertEvent)
  214. }
  215. // DefaultConfig devuelve una copia de los defaults del SPEC §2.
  216. // clients=all desde issue #196: "dispositivo desconocido" ya no es urgente
  217. // pero debe seguir siendo visible (con clients:urgent se descartaría entero).
  218. func DefaultConfig() map[string]string {
  219. return map[string]string{
  220. CatRouter: LevelUrgent,
  221. CatInternet: LevelUrgent,
  222. CatClients: LevelAll,
  223. CatSignal: LevelNone,
  224. CatVPN: LevelNone,
  225. CatSystem: LevelAll,
  226. }
  227. }
  228. // Engine es el motor: aplica config/dedup/cap en Emit y guarda el read-state.
  229. // Seguro para uso concurrente (los adapters emiten desde varios goroutines).
  230. type Engine struct {
  231. mu sync.Mutex
  232. db *db.DB // nil → solo memoria (tests)
  233. notifier Notifier
  234. // startedAt: arranque de ESTA instancia. Las alertas con Ts anterior a
  235. // startedAt vienen de una sesión previa: si se re-emiten (update), es
  236. // un episodio nuevo tras el reinicio y vuelven a no-leídas (#1094).
  237. startedAt time.Time
  238. now func() time.Time
  239. cfg map[string]string
  240. list []AlertEvent
  241. dedup map[string]int64 // key (cat|title|routerId) → último emit (unix ms)
  242. readSet map[string]bool
  243. readOrd []string // FIFO de IDs (cap 200) para podar readSet
  244. silenceMap map[string]int64 // dedup key → expiry (unix seconds); 0 = forever
  245. // dismissed: IDs de alertas limpiadas por el usuario (issue #833). Se
  246. // filtran del feed y del unread; si el mismo ID se vuelve a emitir (la
  247. // condición se re-dispara), sale del conjunto y reaparece.
  248. dismissed map[string]bool
  249. // suppression: grafo de dependencias topológicas (issue #332).
  250. // nil = sin supresión (tests o arranque sin topología).
  251. suppression *SuppressionGraph
  252. // persistLog: volcar el log a alert_log y restaurarlo al arranque
  253. // (issue #798). false solo en el dataset demo, que es sintético y se
  254. // regenera en cada arranque (cargar/re-guardar duplicaría las semillas).
  255. persistLog bool
  256. // onChange (#1434): callback invocado SIN e.mu tras una mutación que
  257. // altera la lista servida o el read-state (mark-read, dismiss, resolve,
  258. // silence). El server lo usa para reemitir el estado del feed por SSE
  259. // al instante; el poller ya no es el único camino de actualización.
  260. onChange func()
  261. }
  262. // PersistMaxEvents es la cota de filas del log persistido (issue #798): la
  263. // lista en memoria se queda en MaxEvents, pero en disco se conservan más
  264. // para restaurarlas tras un reinicio (p. ej. el del self-update).
  265. const PersistMaxEvents = 500
  266. // New crea el motor cargando config, read-state y el log persistido (si db).
  267. func New(d *db.DB, n Notifier) *Engine { return newEngine(d, n, true) }
  268. // NewVolatile crea el motor SIN persistencia del log de alertas. El dataset
  269. // demo es sintético y se regenera en cada arranque: cargar el log traería
  270. // entradas ajenas al canon y re-guardarlo duplicaría las semillas.
  271. func NewVolatile(d *db.DB, n Notifier) *Engine { return newEngine(d, n, false) }
  272. func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
  273. e := &Engine{
  274. db: d,
  275. notifier: n,
  276. now: time.Now,
  277. startedAt: time.Now(),
  278. cfg: DefaultConfig(),
  279. dedup: map[string]int64{},
  280. readSet: map[string]bool{},
  281. silenceMap: map[string]int64{},
  282. dismissed: map[string]bool{},
  283. persistLog: persistLog,
  284. }
  285. if d != nil {
  286. var raw string
  287. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", configKey).Scan(&raw); err == nil {
  288. saved := map[string]string{}
  289. if json.Unmarshal([]byte(raw), &saved) == nil {
  290. for _, cat := range Categories {
  291. if lv, ok := saved[cat]; ok && levels[lv] {
  292. e.cfg[cat] = lv
  293. }
  294. }
  295. }
  296. }
  297. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", readKey).Scan(&raw); err == nil {
  298. ids := []string{}
  299. if json.Unmarshal([]byte(raw), &ids) == nil {
  300. for _, id := range ids {
  301. if id != "" && !e.readSet[id] {
  302. e.readSet[id] = true
  303. e.readOrd = append(e.readOrd, id)
  304. }
  305. }
  306. }
  307. }
  308. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", silenceKey).Scan(&raw); err == nil {
  309. _ = json.Unmarshal([]byte(raw), &e.silenceMap)
  310. }
  311. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", dismissKey).Scan(&raw); err == nil {
  312. ids := []string{}
  313. if json.Unmarshal([]byte(raw), &ids) == nil {
  314. for _, id := range ids {
  315. if id != "" {
  316. e.dismissed[id] = true
  317. }
  318. }
  319. }
  320. }
  321. e.purgeVolatileHistoryLocked()
  322. e.purgeSupersededWeakClosures()
  323. e.loadPersistedLocked()
  324. // #1034: poda por antigüedad al arrancar (además de la horaria de
  325. // main): una retención bajada mientras el daemon estaba parado se
  326. // aplica en el primer arranque posterior.
  327. e.PruneLogByRetention()
  328. }
  329. return e
  330. }
  331. // purgeVolatileHistoryLocked: purga one-shot al arrancar (#966). Las alertas
  332. // de caida de agente AHORA son volatiles (no se persisten), pero las
  333. // instalaciones previas acumularon un historico de agent-down* en alert_log
  334. // que seguiria reapareciendo tras cada reinicio. Se borran ANTES de cargar
  335. // el log, para que ni siquiera el primer arranque tras actualizar lo muestre.
  336. func (e *Engine) purgeVolatileHistoryLocked() {
  337. if e.db == nil || !e.persistLog {
  338. return
  339. }
  340. _, _ = e.db.Exec(
  341. `DELETE FROM alert_log WHERE id LIKE 'alert-agent-down-%'
  342. OR type IN ('agent-down', 'agent-down-ssh')`)
  343. }
  344. // purgeSupersededWeakClosures: purga one-shot al arrancar (#1518). Los
  345. // cierres de señal débil ANTERIORES al ID estable llevaban timestamp en el ID
  346. // (alert-weak-<mac>-ok-<ts>): cada episodio dejaba una "resuelta" idéntica en
  347. // el log. Se borran de alert_log ANTES de cargar (el ID estable nuevo las
  348. // reemplaza en adelante); los avisos originales resueltos no se tocan.
  349. func (e *Engine) purgeSupersededWeakClosures() {
  350. if e.db == nil || !e.persistLog {
  351. return
  352. }
  353. _, _ = e.db.Exec(`DELETE FROM alert_log WHERE id LIKE 'alert-weak-%-ok-%'`)
  354. }
  355. // loadPersistedLocked restaura el log desde alert_log (issue #798): los
  356. // últimos MaxEvents eventos (más recientes primero), reconstruyendo el mapa
  357. // de dedup (para no re-notificar dentro de la ventana tras un reinicio) y
  358. // sembrando el read-set desde la columna read espejada.
  359. func (e *Engine) loadPersistedLocked() {
  360. if !e.persistLog {
  361. return
  362. }
  363. rows, err := e.db.Query(
  364. `SELECT id, ts, category, type, severity, urgent, title, description, hint,
  365. router_id, suppressed_by, vars, read_flag, resolved_ts, resolves
  366. FROM alert_log ORDER BY ts DESC LIMIT ?`, MaxEvents)
  367. if err != nil {
  368. return
  369. }
  370. defer rows.Close()
  371. type row struct {
  372. ev AlertEvent
  373. read bool
  374. }
  375. loaded := []row{}
  376. for rows.Next() {
  377. var ev AlertEvent
  378. var typ, sev, hint, routerID, suppressedBy, varsRaw, resolvesRaw string
  379. var urgent, read int
  380. if err := rows.Scan(&ev.ID, &ev.Ts, &ev.Category, &typ, &sev, &urgent,
  381. &ev.Title, &ev.Description, &hint, &routerID, &suppressedBy, &varsRaw, &read, &ev.ResolvedTs, &resolvesRaw); err != nil {
  382. return
  383. }
  384. // #833: una alerta limpiada no vuelve a aparecer tras un reinicio.
  385. if e.dismissed[ev.ID] {
  386. continue
  387. }
  388. // #1349: un evento resuelto vuelve al feed MARCADO (historia
  389. // consultable en Resueltas) y nunca como pendiente de leer.
  390. if ev.ResolvedTs > 0 {
  391. read = 1
  392. }
  393. ev.Type = typ
  394. ev.Severity = sev
  395. ev.Urgent = urgent != 0
  396. ev.Hint = hint
  397. ev.RouterID = routerID
  398. ev.SuppressedBy = suppressedBy
  399. if varsRaw != "" {
  400. vars := map[string]string{}
  401. if json.Unmarshal([]byte(varsRaw), &vars) == nil {
  402. ev.Vars = vars
  403. }
  404. }
  405. // #1466: referencias del cierre (qué eventos resolvió).
  406. if resolvesRaw != "" {
  407. var ids []string
  408. if json.Unmarshal([]byte(resolvesRaw), &ids) == nil && len(ids) > 0 {
  409. ev.Resolves = ids
  410. }
  411. }
  412. loaded = append(loaded, row{ev: ev, read: read != 0})
  413. }
  414. // rows.Next() consumió las filas de más reciente a más antigua; la lista
  415. // interna ya va en ese orden (append al frente en insertaLocked).
  416. for _, r := range loaded {
  417. e.list = append(e.list, r.ev)
  418. key := r.ev.Category + "|" + r.ev.Title + "|" + r.ev.RouterID
  419. // Las filas vienen de más reciente a más antigua: solo la primera por
  420. // clave es el timestamp de dedup válido (no pisar con la más vieja).
  421. // #1349: un RESUELTO no siembra dedup - su condición está cerrada y
  422. // una reincidencia tras reinicio debe alertar de inmediato (mismo
  423. // criterio que Resolve en caliente, que borra la clave de dedup).
  424. if r.ev.ResolvedTs == 0 {
  425. if _, ok := e.dedup[key]; !ok {
  426. e.dedup[key] = r.ev.Ts * 1000
  427. }
  428. }
  429. if r.read && r.ev.ID != "" && !e.readSet[r.ev.ID] {
  430. e.readSet[r.ev.ID] = true
  431. e.readOrd = append(e.readOrd, r.ev.ID)
  432. }
  433. }
  434. }
  435. // SetNotifier sustituye el hook Notifier (wiring de Bloque C desde main;
  436. // nil = no-op). Seguro en caliente: Emit lo lee bajo el mismo mutex.
  437. func (e *Engine) SetNotifier(n Notifier) {
  438. e.mu.Lock()
  439. defer e.mu.Unlock()
  440. e.notifier = n
  441. }
  442. // SetClock sustituye el reloj (solo tests).
  443. func (e *Engine) SetClock(f func() time.Time) {
  444. e.mu.Lock()
  445. defer e.mu.Unlock()
  446. e.now = f
  447. }
  448. // SetSuppression wirea el grafo de dependencias topológicas (issue #332).
  449. // nil desactiva la supresión (tests o arranque sin topología).
  450. func (e *Engine) SetSuppression(g *SuppressionGraph) {
  451. e.mu.Lock()
  452. defer e.mu.Unlock()
  453. e.suppression = g
  454. }
  455. // SetOnChange (#1434) fija el callback de mutación del feed. Se invoca DESPUÉS
  456. // de soltar e.mu, así que el receptor puede leer el engine (List/UnreadCount)
  457. // sin riesgo de deadlock; solo hay que evitar mutar el engine desde dentro
  458. // (recursión de notificaciones).
  459. func (e *Engine) SetOnChange(f func()) {
  460. e.mu.Lock()
  461. defer e.mu.Unlock()
  462. e.onChange = f
  463. }
  464. // Config devuelve una copia de la config efectiva (siempre las 6 claves).
  465. func (e *Engine) Config() map[string]string {
  466. e.mu.Lock()
  467. defer e.mu.Unlock()
  468. out := make(map[string]string, len(e.cfg))
  469. for k, v := range e.cfg {
  470. out[k] = v
  471. }
  472. return out
  473. }
  474. // SetConfig aplica un parche parcial {"signal":"all"}: valida categorías y
  475. // niveles (error → 400 en la API), fusiona y persiste en kv.
  476. func (e *Engine) SetConfig(patch map[string]string) error {
  477. badCats, badVals := []string{}, []string{}
  478. for k, v := range patch {
  479. if !contains(Categories, k) {
  480. badCats = append(badCats, k)
  481. } else if !levels[v] {
  482. badVals = append(badVals, fmt.Sprintf("%s=%q", k, v))
  483. }
  484. }
  485. if len(badCats) > 0 || len(badVals) > 0 {
  486. sort.Strings(badCats)
  487. sort.Strings(badVals)
  488. parts := []string{}
  489. if len(badCats) > 0 {
  490. parts = append(parts, "categorías desconocidas: "+strings.Join(badCats, ", "))
  491. }
  492. if len(badVals) > 0 {
  493. parts = append(parts, "niveles inválidos: "+strings.Join(badVals, ", "))
  494. }
  495. return fmt.Errorf("invalid config (%s)", strings.Join(parts, "; "))
  496. }
  497. e.mu.Lock()
  498. defer e.mu.Unlock()
  499. for k, v := range patch {
  500. e.cfg[k] = v
  501. }
  502. e.saveConfigLocked()
  503. return nil
  504. }
  505. // notificaLocked: ¿la config de la categoría permite NOTIFICAR este evento?
  506. // (issue #1413: los niveles son política de notificación, no de ingesta:
  507. // todo se guarda en el log y el feed; el nivel solo gobierna el Notifier).
  508. // none = nunca; urgent = solo eventos Urgent; all = siempre. Categoría
  509. // desconocida: notifica (la validación estricta es de SetConfig).
  510. // Requiere e.mu ya tomado.
  511. func (e *Engine) notificaLocked(ev AlertEvent) bool {
  512. level, known := e.cfg[ev.Category]
  513. if known {
  514. if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
  515. return false
  516. }
  517. }
  518. return true
  519. }
  520. // hiddenByLevelLocked: una categoría en nivel "none" no existe para el
  521. // operador. No entra al feed, no cuenta en la campana y no se persiste
  522. // (issue #1659). El nivel "urgent" sigue siendo solo política de
  523. // notificación (#1413): sus eventos se registran y solo silencian el aviso.
  524. // Los fixtures del demo (Seed) quedan exentos para servir el canon completo.
  525. func (e *Engine) hiddenByLevelLocked(ev AlertEvent) bool {
  526. return !ev.seeded && e.cfg[ev.Category] == LevelNone
  527. }
  528. // insertaLocked inserta un evento nuevo al frente con dedup y cap.
  529. // Requiere e.mu ya tomado. Devuelve true si se guardó. skipDedup omite la
  530. // ventana de dedup de 5 min (issue #846: los incidentes con estado propio,
  531. // p.ej. offline de router, se trackean fuera del engine y su alerta debe
  532. // entrar aunque la ventana cubra la emisión de un incidente ya cerrado).
  533. func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) bool {
  534. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  535. if e.isSilencedLocked(key) {
  536. return false
  537. }
  538. // #1659: el nivel "none" oculta la categoría por completo (feed, campana
  539. // y alert_log). Se descarta antes del dedup para no consumir la ventana.
  540. if e.hiddenByLevelLocked(ev) {
  541. return false
  542. }
  543. if !skipDedup {
  544. if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
  545. return false
  546. }
  547. e.dedup[key] = now.UnixMilli()
  548. }
  549. // #833: si el ID estaba limpiado y la condición se re-dispara, la alerta
  550. // vuelve al feed (dismissed solo oculta el histórico, no el presente).
  551. if _, was := e.dismissed[ev.ID]; was {
  552. delete(e.dismissed, ev.ID)
  553. e.saveDismissedLocked()
  554. }
  555. if ev.Ts == 0 {
  556. ev.Ts = now.Unix()
  557. }
  558. if ev.Time == "" {
  559. ev.Time = "just now"
  560. }
  561. ev.Read = false
  562. e.list = append([]AlertEvent{ev}, e.list...)
  563. if len(e.list) > MaxEvents {
  564. e.list = e.list[:MaxEvents]
  565. }
  566. e.persistLocked(ev)
  567. return true
  568. }
  569. // persistLocked escribe (o actualiza) el evento en alert_log y poda la tabla
  570. // a PersistMaxEvents filas (issue #798). El read NO se toca aquí: la fuente
  571. // de verdad del leído es el read-set de kv y se espeja aparte en MarkRead.
  572. // Best-effort: un fallo de BD nunca debe romper el camino de alertado.
  573. func (e *Engine) persistLocked(ev AlertEvent) {
  574. if e.db == nil || !e.persistLog || ev.ID == "" || ev.Volatile {
  575. return
  576. }
  577. varsRaw := ""
  578. if len(ev.Vars) > 0 {
  579. if raw, err := json.Marshal(ev.Vars); err == nil {
  580. varsRaw = string(raw)
  581. }
  582. }
  583. // #1466: las referencias del cierre se persisten; si no, tras un reinicio
  584. // el evento de cierre queda sin saber qué resolvió.
  585. resolvesRaw := ""
  586. if len(ev.Resolves) > 0 {
  587. if raw, err := json.Marshal(ev.Resolves); err == nil {
  588. resolvesRaw = string(raw)
  589. }
  590. }
  591. urgent := 0
  592. if ev.Urgent {
  593. urgent = 1
  594. }
  595. _, _ = e.db.Exec(
  596. `INSERT INTO alert_log (id, ts, category, type, severity, urgent, title, description, hint, router_id, suppressed_by, vars, resolved_ts, resolves)
  597. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  598. ON CONFLICT(id) DO UPDATE SET ts=excluded.ts, category=excluded.category,
  599. type=excluded.type, severity=excluded.severity, urgent=excluded.urgent,
  600. title=excluded.title, description=excluded.description, hint=excluded.hint,
  601. router_id=excluded.router_id, suppressed_by=excluded.suppressed_by, vars=excluded.vars,
  602. resolved_ts=excluded.resolved_ts, resolves=excluded.resolves`,
  603. ev.ID, ev.Ts, ev.Category, ev.Type, ev.Severity, urgent,
  604. ev.Title, ev.Description, ev.Hint, ev.RouterID, ev.SuppressedBy, varsRaw, ev.ResolvedTs, resolvesRaw)
  605. _, _ = e.db.Exec(
  606. `DELETE FROM alert_log WHERE id NOT IN
  607. (SELECT id FROM alert_log ORDER BY ts DESC LIMIT ?)`, PersistMaxEvents)
  608. }
  609. // Emit aplica el dedup de 5 min y el cap de 100; devuelve true si el evento
  610. // se guardó. El nivel de la categoría gobierna qué se registra: "none" no
  611. // entra al feed ni se persiste (#1659), "urgent" sí se registra y solo
  612. // silencia el aviso (#1413).
  613. // El filtro por URGENCIA fino vive en cada canal (#874): cada transporte
  614. // decide si lleva solo urgentes (default) o todo.
  615. // Supresión topológica (#332): si el router tiene un padre offline en el
  616. // grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
  617. func (e *Engine) Emit(ev AlertEvent) bool {
  618. e.mu.Lock()
  619. if e.suppression != nil && ev.RouterID != "" {
  620. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  621. ev.SuppressedBy = parent
  622. }
  623. }
  624. // #914: default de Ts/Time ANTES de insertar y notificar. Hasta ahora el
  625. // default vivía solo en insertaLocked, cuya copia local no propagaba a
  626. // esta `ev`: el notifier (ntfy/Telegram/webhook) recibía Ts=0 y pintaba
  627. // la hora estática 16:00:00 (epoch en zona UTC-8).
  628. if ev.Ts == 0 {
  629. ev.Ts = e.now().Unix()
  630. }
  631. if ev.Time == "" {
  632. ev.Time = "just now"
  633. }
  634. now := e.now()
  635. ok := e.insertaLocked(ev, now, false)
  636. n := e.notifier
  637. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  638. e.mu.Unlock()
  639. if ok && notify {
  640. n.Notify(ev)
  641. }
  642. return ok
  643. }
  644. // EmitNoDedup es Emit sin la ventana de dedup de 5 min (silencio, cap,
  645. // supresión y política de notificación por categoría SÍ aplican; issue #1413:
  646. // la config ya no filtra la ingesta, solo la notificación). Uso:
  647. // alertas cuya condición se trackea por estado fuera del engine (issue #846,
  648. // offline de router): al ABRIR incidente la alerta debe entrar siempre,
  649. // porque el cierre del incidente anterior ya retiró la suya del feed y el
  650. // dedup la bloquearía — el "una alerta por outage" lo garantiza el tracking
  651. // de incidente (offlineOpen), no la ventana.
  652. func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
  653. e.mu.Lock()
  654. if e.suppression != nil && ev.RouterID != "" {
  655. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  656. ev.SuppressedBy = parent
  657. }
  658. }
  659. // #914: mismo default de Ts/Time que en Emit antes de notificar.
  660. if ev.Ts == 0 {
  661. ev.Ts = e.now().Unix()
  662. }
  663. if ev.Time == "" {
  664. ev.Time = "just now"
  665. }
  666. now := e.now()
  667. ok := e.insertaLocked(ev, now, true)
  668. n := e.notifier
  669. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  670. e.mu.Unlock()
  671. if ok && notify {
  672. n.Notify(ev)
  673. }
  674. return ok
  675. }
  676. // EmitOrUpdate: como Emit, pero si YA existe una alerta con el mismo ID, la
  677. // actualiza en sitio (ts, título, descripción, severidad, urgent, router) y
  678. // la mueve al frente de la lista (más reciente) en vez de insertar una copia.
  679. // Diseñado para alertas "en curso" que se actualizan (p.ej. auto-rearme sin
  680. // recuperación: un incidente = una sola alerta, issue #271). El update NO
  681. // pasa por el dedup (consolida, no duplica); la inserción de un ID nuevo sí.
  682. // Devuelve true si se insertó o actualizó. La notificación obedece la
  683. // política de nivel de la categoría (#1413).
  684. func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
  685. e.mu.Lock()
  686. // #1074: mismo default de Ts/Time que en Emit (#914) ANTES de insertar y
  687. // notificar. La rama de inserción pasaba la `ev` original a Notify: si el
  688. // emisor no fijaba Ts (p. ej. agent-outdated), el notifier recibía Ts=0
  689. // y el push pintaba la hora estática 16:00:00 (epoch en zona UTC-8).
  690. if ev.Ts == 0 {
  691. ev.Ts = e.now().Unix()
  692. }
  693. if ev.Time == "" {
  694. ev.Time = "just now"
  695. }
  696. now := e.now()
  697. for i := range e.list {
  698. if e.list[i].ID == ev.ID {
  699. old := e.list[i]
  700. ev.Ts = now.Unix()
  701. ev.Time = "just now"
  702. // #1094: episodio nuevo tras reinicio (la alerta no se había
  703. // refrescado desde el arranque): vuelve a no-leída, que el
  704. // humano la vea. Un refresh de episodio en curso (p. ej. port
  705. // flapping, que re-emite cada ciclo) conserva su read.
  706. if old.Ts >= e.startedAt.Unix() {
  707. ev.Read = old.Read
  708. } else {
  709. // #1094: Read se DERIVA de readSet en List(), y el kv guarda
  710. // readOrd: hay que purgar ambos (y el espejo en alert_log)
  711. // o la alerta reviviría leída.
  712. ev.Read = false
  713. delete(e.readSet, ev.ID)
  714. for j, rid := range e.readOrd {
  715. if rid == ev.ID {
  716. e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
  717. break
  718. }
  719. }
  720. e.saveReadLocked()
  721. if e.db != nil {
  722. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 0 WHERE id = ?", ev.ID)
  723. }
  724. }
  725. if ev.RouterID == "" {
  726. ev.RouterID = old.RouterID
  727. }
  728. e.list = append(e.list[:i], e.list[i+1:]...)
  729. e.list = append([]AlertEvent{ev}, e.list...)
  730. e.persistLocked(ev)
  731. n := e.notifier
  732. notify := n != nil && e.notificaLocked(ev)
  733. e.mu.Unlock()
  734. if notify {
  735. n.Notify(ev)
  736. }
  737. return true
  738. }
  739. }
  740. ok := e.insertaLocked(ev, now, false)
  741. n := e.notifier
  742. notify := n != nil && e.notificaLocked(ev)
  743. e.mu.Unlock()
  744. if ok && notify {
  745. n.Notify(ev)
  746. }
  747. return ok
  748. }
  749. // EmitVolatile (#966): emite una alerta VOLÁTIL (caída de agente): NUNCA se
  750. // persiste en alert_log y, si ya existe una alerta con el mismo ID, se
  751. // actualiza en sitio y se mueve al frente (semántica "viva por router": un
  752. // incidente abierto = una alerta con ID estable). Si quedara una copia
  753. // persistida antigua con ese ID, se borra. Silencio y supresión
  754. // topológica aplican como en Emit; la notificación obedece el nivel de la
  755. // categoría (#1413). El dedup de 5 min NO aplica (el tracking del incidente
  756. // vive en el emisor, patrón #846). Devuelve true siempre (la volátil nunca
  757. // se descarta por config).
  758. func (e *Engine) EmitVolatile(ev AlertEvent) bool {
  759. ev.Volatile = true
  760. e.mu.Lock()
  761. if e.suppression != nil && ev.RouterID != "" {
  762. if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
  763. ev.SuppressedBy = parent
  764. }
  765. }
  766. now := e.now()
  767. if ev.Ts == 0 {
  768. ev.Ts = now.Unix()
  769. }
  770. if ev.Time == "" {
  771. ev.Time = "just now"
  772. }
  773. replaced := false
  774. for i := range e.list {
  775. if e.list[i].ID == ev.ID {
  776. ev.Read = e.readSet[ev.ID]
  777. e.list = append(e.list[:i], e.list[i+1:]...)
  778. e.list = append([]AlertEvent{ev}, e.list...)
  779. replaced = true
  780. break
  781. }
  782. }
  783. if !replaced {
  784. // #833: si el ID estaba limpiado y la condición se re-dispara, la
  785. // alerta vuelve al feed (igual que en insertaLocked).
  786. if _, was := e.dismissed[ev.ID]; was {
  787. delete(e.dismissed, ev.ID)
  788. e.saveDismissedLocked()
  789. }
  790. ev.Read = false
  791. e.list = append([]AlertEvent{ev}, e.list...)
  792. if len(e.list) > MaxEvents {
  793. e.list = e.list[:MaxEvents]
  794. }
  795. }
  796. // Defensa en profundidad: ninguna copia persistida de una volátil debe
  797. // sobrevivir (la purga de arranque cubre el histórico, esto el presente).
  798. if e.db != nil && ev.ID != "" {
  799. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", ev.ID)
  800. }
  801. n := e.notifier
  802. notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
  803. e.mu.Unlock()
  804. if notify {
  805. n.Notify(ev)
  806. }
  807. return true
  808. }
  809. // Seed inserta un evento histórico (arranque del modo demo) SIN disparar el
  810. // Notifier (son historia). Mantiene dedup, cap y Read=false.
  811. // Devuelve true si se guardó.
  812. func (e *Engine) Seed(ev AlertEvent) bool {
  813. e.mu.Lock()
  814. defer e.mu.Unlock()
  815. now := e.now()
  816. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  817. if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
  818. return false
  819. }
  820. e.dedup[key] = now.UnixMilli()
  821. if ev.Ts == 0 {
  822. ev.Ts = now.Unix()
  823. }
  824. if ev.Time == "" {
  825. ev.Time = "just now"
  826. }
  827. ev.Read = false
  828. // #1659: fixture de demo, exento del filtro de nivel.
  829. ev.seeded = true
  830. e.list = append([]AlertEvent{ev}, e.list...)
  831. if len(e.list) > MaxEvents {
  832. e.list = e.list[:MaxEvents]
  833. }
  834. return true
  835. }
  836. // List devuelve copia de los eventos (más recientes primero) con Read
  837. // aplicado desde el read-set del servidor.
  838. func (e *Engine) List() []AlertEvent {
  839. e.mu.Lock()
  840. defer e.mu.Unlock()
  841. e.pruneSilenceLocked()
  842. // #1466: índice id → evento para resolver los cierres con datos propios.
  843. byID := make(map[string]*AlertEvent, len(e.list))
  844. for i := range e.list {
  845. byID[e.list[i].ID] = &e.list[i]
  846. }
  847. out := make([]AlertEvent, 0, len(e.list))
  848. // #1518: con el ajuste activo, los cierres informativos (severity ok) no
  849. // se sirven; los avisos resueltos (resolvedTs, otra severidad) siguen.
  850. hideOK := e.hideRecoveryLocked()
  851. for _, ev := range e.list {
  852. if e.dismissed[ev.ID] {
  853. continue
  854. }
  855. // #1659: los eventos de una categoría en nivel "none" no se sirven,
  856. // aunque estuvieran ya persistidos de antes del cambio de nivel.
  857. if e.hiddenByLevelLocked(ev) {
  858. continue
  859. }
  860. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  861. if e.isSilencedLocked(key) {
  862. continue
  863. }
  864. if hideOK && ev.Severity == "ok" {
  865. continue
  866. }
  867. ev.Read = e.readSet[ev.ID]
  868. if len(ev.Resolves) > 0 {
  869. ev.Resolved = make([]ResolvedEvent, 0, len(ev.Resolves))
  870. var missing []int
  871. for _, rid := range ev.Resolves {
  872. ref := ResolvedEvent{ID: rid}
  873. if orig, ok := byID[rid]; ok {
  874. ref.Title = orig.Title
  875. ref.Ts = orig.Ts
  876. ref.Type = orig.Type
  877. ref.Vars = orig.Vars
  878. } else {
  879. missing = append(missing, len(ev.Resolved))
  880. }
  881. ev.Resolved = append(ev.Resolved, ref)
  882. }
  883. // #1466: el evento resuelto casi nunca está en la lista viva,
  884. // porque Resolve() lo retira de ella. Sin este respaldo el cierre
  885. // se quedaba con el id suelto, que es lo que se reportaba.
  886. e.fillResolvedFromDBLocked(ev.Resolved, missing)
  887. }
  888. out = append(out, ev)
  889. }
  890. return out
  891. }
  892. // fillResolvedFromDBLocked completa los datos de los eventos resueltos que ya
  893. // no están en memoria (#1466). Resolve() retira el evento de la lista viva y
  894. // lo conserva en alert_log marcado con resolved_ts, así que la fila sigue
  895. // teniendo título, instante, tipo y vars. Sin esto, el cierre mostraba solo
  896. // el id interno. Se llama con e.mu tomado.
  897. func (e *Engine) fillResolvedFromDBLocked(refs []ResolvedEvent, missing []int) {
  898. if e.db == nil || len(missing) == 0 {
  899. return
  900. }
  901. ids := make([]string, 0, len(missing))
  902. for _, i := range missing {
  903. ids = append(ids, refs[i].ID)
  904. }
  905. args := make([]any, len(ids))
  906. for i, id := range ids {
  907. args[i] = id
  908. }
  909. marks := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
  910. rows, err := e.db.Query(
  911. "SELECT id, title, ts, type, vars FROM alert_log WHERE id IN ("+marks+")", args...)
  912. if err != nil {
  913. return
  914. }
  915. defer rows.Close()
  916. byID := make(map[string]ResolvedEvent, len(ids))
  917. for rows.Next() {
  918. var ref ResolvedEvent
  919. var varsRaw string
  920. if rows.Scan(&ref.ID, &ref.Title, &ref.Ts, &ref.Type, &varsRaw) != nil {
  921. continue
  922. }
  923. if varsRaw != "" {
  924. _ = json.Unmarshal([]byte(varsRaw), &ref.Vars)
  925. }
  926. byID[ref.ID] = ref
  927. }
  928. for _, i := range missing {
  929. if got, ok := byID[refs[i].ID]; ok {
  930. refs[i] = got
  931. }
  932. }
  933. }
  934. // UnreadCount cuenta eventos almacenados (ya pasaron config) no leídos.
  935. // Es la fuente de Overview.UnreadAlerts (server truth, SPEC §4).
  936. func (e *Engine) UnreadCount() int {
  937. e.mu.Lock()
  938. defer e.mu.Unlock()
  939. n := 0
  940. // #1518: los eventos ocultos por el ajuste de recuperación no cuentan.
  941. hideOK := e.hideRecoveryLocked()
  942. for _, ev := range e.list {
  943. if e.dismissed[ev.ID] {
  944. continue
  945. }
  946. if e.hiddenByLevelLocked(ev) {
  947. continue
  948. }
  949. key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
  950. if e.isSilencedLocked(key) {
  951. continue
  952. }
  953. if hideOK && ev.Severity == "ok" {
  954. continue
  955. }
  956. if !e.readSet[ev.ID] {
  957. n++
  958. }
  959. }
  960. return n
  961. }
  962. // MarkRead marca IDs como leídos (persiste; cap 200 FIFO sobre los IDs que
  963. // ya NO son visibles; una alerta visible leída nunca vuelve a no-leída).
  964. // #1434: si algo cambió, avisa a OnChange (el server re-emite el estado del
  965. // feed por SSE para que Resumen/campana se actualicen al instante).
  966. func (e *Engine) MarkRead(ids ...string) {
  967. e.mu.Lock()
  968. changed := false
  969. for _, id := range ids {
  970. if id == "" || e.readSet[id] {
  971. continue
  972. }
  973. // La notificación solo cuenta cuando la alerta existe en el feed:
  974. // marcar leído un ID ajeno (o de un episodio ya cerrado) persiste
  975. // el leído como siempre, pero no cambia nada visible que reemitir.
  976. if e.idInListLocked(id) {
  977. changed = true
  978. }
  979. e.readSet[id] = true
  980. e.readOrd = append(e.readOrd, id)
  981. // Espejo en alert_log para restaurar el leído tras un reinicio (#798).
  982. if e.db != nil {
  983. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
  984. }
  985. }
  986. e.pruneReadOrdLocked()
  987. e.saveReadLocked()
  988. cb := e.onChange
  989. e.mu.Unlock()
  990. if changed && cb != nil {
  991. cb()
  992. }
  993. }
  994. // pruneReadOrdLocked poda el FIFO del read-set, PERO sin expulsar IDs que
  995. // siguen en la lista (#966): con la poda FIFO a ciegas, marcar muchas
  996. // alertas como leídas podía expulsar del read-set una alerta AÚN VISIBLE,
  997. // que reaparecía como no leída (el badge volvía a subir tras "marcar todo
  998. // como leído"). Lo visible leído se queda leído; el cap aplica al resto.
  999. func (e *Engine) pruneReadOrdLocked() {
  1000. visible := 0
  1001. for _, id := range e.readOrd {
  1002. if e.idInListLocked(id) {
  1003. visible++
  1004. }
  1005. }
  1006. budget := len(e.readOrd) - visible - MaxReadIDs
  1007. if budget <= 0 {
  1008. return
  1009. }
  1010. kept := e.readOrd[:0]
  1011. for _, id := range e.readOrd {
  1012. if budget > 0 && !e.idInListLocked(id) {
  1013. delete(e.readSet, id)
  1014. budget--
  1015. continue
  1016. }
  1017. kept = append(kept, id)
  1018. }
  1019. e.readOrd = kept
  1020. }
  1021. // idInListLocked: ¿el ID sigue en la lista (potencialmente visible)?
  1022. // Requiere e.mu ya tomado.
  1023. func (e *Engine) idInListLocked(id string) bool {
  1024. for _, ev := range e.list {
  1025. if ev.ID == id {
  1026. return true
  1027. }
  1028. }
  1029. return false
  1030. }
  1031. // MarkAllRead marca leídas todas las alertas actuales (#1034): SOLO toca el
  1032. // read-set (persistido en kv y espejado en alert_log.read_flag). NO borra
  1033. // nada de alert_log ni del conjunto dismissed: el feed sigue mostrando las
  1034. // alertas como leídas y el toggle "Solo no leídas" es lo que limpia la vista.
  1035. // Vaciar el log es la acción destructiva aparte (DismissAll).
  1036. func (e *Engine) MarkAllRead() {
  1037. e.mu.Lock()
  1038. ids := make([]string, 0, len(e.list))
  1039. for _, ev := range e.list {
  1040. ids = append(ids, ev.ID)
  1041. }
  1042. e.mu.Unlock()
  1043. e.MarkRead(ids...)
  1044. }
  1045. // Dismiss limpia alertas del feed (issue #833, botón "limpiar alerta"): las
  1046. // quita de la lista y del log persistido, las marca leídas y guarda el ID en
  1047. // el conjunto dismissed (kv) para que no reaparezcan tras un reinicio. Si la
  1048. // condición se re-dispara, el mismo ID se vuelve a emitir y sale del
  1049. // conjunto (ver insertaLocked). IDs desconocidos se ignoran.
  1050. func (e *Engine) Dismiss(ids ...string) {
  1051. e.mu.Lock()
  1052. changed := false
  1053. seen := false
  1054. drop := map[string]bool{}
  1055. for _, id := range ids {
  1056. if id == "" {
  1057. continue
  1058. }
  1059. seen = true
  1060. if !e.dismissed[id] {
  1061. e.dismissed[id] = true
  1062. changed = true
  1063. }
  1064. drop[id] = true
  1065. if !e.readSet[id] {
  1066. e.readSet[id] = true
  1067. e.readOrd = append(e.readOrd, id)
  1068. }
  1069. if e.db != nil {
  1070. _, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
  1071. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
  1072. }
  1073. }
  1074. e.pruneReadOrdLocked()
  1075. if changed {
  1076. e.saveDismissedLocked()
  1077. e.saveReadLocked()
  1078. }
  1079. kept := e.list[:0]
  1080. droppedAny := false
  1081. for _, ev := range e.list {
  1082. if !drop[ev.ID] {
  1083. kept = append(kept, ev)
  1084. } else {
  1085. droppedAny = true
  1086. }
  1087. }
  1088. e.list = kept
  1089. cb := e.onChange
  1090. e.mu.Unlock()
  1091. // #1434: el feed cambió -> el server re-emite el estado por SSE.
  1092. if seen && (changed || droppedAny) && cb != nil {
  1093. cb()
  1094. }
  1095. }
  1096. // DismissAll limpia TODAS las alertas del feed: equivale a Dismiss sobre
  1097. // cada ID presente en la lista. Es la acción destructiva "Vaciar registro"
  1098. // (#1034; antes el botón "Marcar todo como leído" la invocaba, #971). Las
  1099. // persistentes se borran de alert_log y su ID queda en el conjunto
  1100. // dismissed (kv), así que el feed vacío sobrevive a un reload; las volátiles
  1101. // (agent-down) también salen, pero si su condición sigue viva el emisor las
  1102. // re-emite con el mismo ID y vuelven (semántica "alerta viva": lo que no
  1103. // vuelve es el histórico, no el presente).
  1104. func (e *Engine) DismissAll() {
  1105. e.mu.Lock()
  1106. ids := make([]string, 0, len(e.list))
  1107. for _, ev := range e.list {
  1108. ids = append(ids, ev.ID)
  1109. }
  1110. e.mu.Unlock()
  1111. e.Dismiss(ids...)
  1112. }
  1113. // Has informa si un ID de alerta está actualmente en la lista (persistida
  1114. // incluida). Lo usa el agent-outdated check tras un reinicio, cuando el flag
  1115. // en memoria (agentOutdatedAlerted) no sobrevive pero la alerta sí (#833).
  1116. func (e *Engine) Has(id string) bool {
  1117. e.mu.Lock()
  1118. defer e.mu.Unlock()
  1119. for _, ev := range e.list {
  1120. if ev.ID == id {
  1121. return true
  1122. }
  1123. }
  1124. return false
  1125. }
  1126. // Resolve elimina una alerta cuya condición dejó de cumplirse (issue #833:
  1127. // agent-outdated desaparece del feed cuando el agente se actualiza). A
  1128. // diferencia de Dismiss NO guarda el ID en dismissed: si la condición vuelve,
  1129. // la alerta se re-emite con normalidad. El dedup se conserva para no
  1130. // re-notificar dentro de la ventana de 5 min.
  1131. func (e *Engine) Resolve(id string) {
  1132. if id == "" {
  1133. return
  1134. }
  1135. e.mu.Lock()
  1136. found := false
  1137. for i, ev := range e.list {
  1138. if ev.ID == id {
  1139. e.list = append(e.list[:i], e.list[i+1:]...)
  1140. // La condición se resolvió: una reincidencia es un incidente
  1141. // nuevo y debe poder alertar de inmediato (sin esperar al
  1142. // expirar la ventana de dedup de 5 min).
  1143. delete(e.dedup, ev.Category+"|"+ev.Title+"|"+ev.RouterID)
  1144. found = true
  1145. break
  1146. }
  1147. }
  1148. // #1107: la alerta resuelta es un episodio CERRADO. El read-set es
  1149. // append-only (kv readOrd) y sobrevivía al Resolve: si la condición se
  1150. // re-dispara con el mismo ID estable (p. ej. "Agent outdated" tras
  1151. // actualizar el server y quedar otra vez desactualizado), el episodio
  1152. // nuevo heredaba el leído viejo en List()/UnreadCount(). Mismo criterio
  1153. // que Remove (#846): al cerrarse, se olvida el leído.
  1154. delete(e.readSet, id)
  1155. for j, rid := range e.readOrd {
  1156. if rid == id {
  1157. e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
  1158. break
  1159. }
  1160. }
  1161. e.saveReadLocked()
  1162. if e.db != nil {
  1163. // #1349: el evento resuelto se CONSERVA en el log (marcado con su ts
  1164. // de cierre) en vez de borrarse: el registro de actividad mantiene
  1165. // qué pasó y cuándo se cerró. La pestaña Resueltas de la UI lo lista.
  1166. // read_flag=0: el resuelto se muestra leído por la regla de carga
  1167. // (resolved_ts>0 → leído), y si la condición REINCIDE con el mismo
  1168. // ID estable, el upsert (resolved_ts=0) no puede heredar un leído
  1169. // viejo de la fila conservada (#1107 sigue valiendo).
  1170. _, _ = e.db.Exec("UPDATE alert_log SET resolved_ts = ?, read_flag = 0 WHERE id = ?", time.Now().Unix(), id)
  1171. }
  1172. cb := e.onChange
  1173. e.mu.Unlock()
  1174. // #1434: la lista del feed cambió -> el server re-emite el estado por
  1175. // SSE para que Resumen/campana se actualicen al instante.
  1176. if found && cb != nil {
  1177. cb()
  1178. }
  1179. }
  1180. // Remove elimina eventos por ID: los retira de la lista en memoria, de su
  1181. // espejo en alert_log y del read-set (issue #846). Sirve para retirar alertas
  1182. // "en curso" cuya condición ya no existe, p.ej. la caída de un router que
  1183. // vuelve online: el feed no acumula incidentes cerrados.
  1184. func (e *Engine) Remove(ids ...string) {
  1185. e.mu.Lock()
  1186. defer e.mu.Unlock()
  1187. drop := map[string]bool{}
  1188. for _, id := range ids {
  1189. if id != "" {
  1190. drop[id] = true
  1191. }
  1192. }
  1193. if len(drop) == 0 {
  1194. return
  1195. }
  1196. out := make([]AlertEvent, 0, len(e.list))
  1197. for _, ev := range e.list {
  1198. if !drop[ev.ID] {
  1199. out = append(out, ev)
  1200. }
  1201. }
  1202. e.list = out
  1203. for id := range drop {
  1204. delete(e.readSet, id)
  1205. for i, rid := range e.readOrd {
  1206. if rid == id {
  1207. e.readOrd = append(e.readOrd[:i], e.readOrd[i+1:]...)
  1208. break
  1209. }
  1210. }
  1211. if e.db != nil {
  1212. _, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
  1213. }
  1214. }
  1215. e.saveReadLocked()
  1216. }
  1217. // Silence silences alerts matching the dedup key of the given alert ID for the
  1218. // specified duration. Duration 0 means forever. Returns the dedup key that was
  1219. // silenced, or empty string if the alert ID was not found.
  1220. func (e *Engine) Silence(id string, dur time.Duration) string {
  1221. e.mu.Lock()
  1222. var dedupKey string
  1223. for _, ev := range e.list {
  1224. if ev.ID == id {
  1225. dedupKey = ev.Category + "|" + ev.Title + "|" + ev.RouterID
  1226. break
  1227. }
  1228. }
  1229. if dedupKey == "" {
  1230. e.mu.Unlock()
  1231. return ""
  1232. }
  1233. var expiry int64
  1234. if dur > 0 {
  1235. expiry = e.now().Add(dur).Unix()
  1236. }
  1237. e.silenceMap[dedupKey] = expiry
  1238. e.saveSilenceLocked()
  1239. cb := e.onChange
  1240. e.mu.Unlock()
  1241. // #1434: la lista servida cambia (la alerta queda filtrada).
  1242. if cb != nil {
  1243. cb()
  1244. }
  1245. return dedupKey
  1246. }
  1247. // Unsilence removes the silence for a dedup key.
  1248. func (e *Engine) Unsilence(dedupKey string) {
  1249. e.mu.Lock()
  1250. delete(e.silenceMap, dedupKey)
  1251. e.saveSilenceLocked()
  1252. cb := e.onChange
  1253. e.mu.Unlock()
  1254. if cb != nil {
  1255. cb()
  1256. }
  1257. }
  1258. // Silenced returns all currently silenced dedup keys with their expiry times.
  1259. func (e *Engine) Silenced() map[string]int64 {
  1260. e.mu.Lock()
  1261. defer e.mu.Unlock()
  1262. e.pruneSilenceLocked()
  1263. out := make(map[string]int64, len(e.silenceMap))
  1264. for k, v := range e.silenceMap {
  1265. out[k] = v
  1266. }
  1267. return out
  1268. }
  1269. func (e *Engine) isSilencedLocked(key string) bool {
  1270. expiry, ok := e.silenceMap[key]
  1271. if !ok {
  1272. return false
  1273. }
  1274. if expiry == 0 {
  1275. return true // forever
  1276. }
  1277. if e.now().Unix() >= expiry {
  1278. delete(e.silenceMap, key)
  1279. return false
  1280. }
  1281. return true
  1282. }
  1283. func (e *Engine) pruneSilenceLocked() {
  1284. now := e.now().Unix()
  1285. for k, expiry := range e.silenceMap {
  1286. if expiry > 0 && now >= expiry {
  1287. delete(e.silenceMap, k)
  1288. }
  1289. }
  1290. }
  1291. func (e *Engine) saveConfigLocked() {
  1292. if e.db == nil {
  1293. return
  1294. }
  1295. raw, err := json.Marshal(e.cfg)
  1296. if err != nil {
  1297. return
  1298. }
  1299. _, _ = e.db.Exec(
  1300. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1301. configKey, string(raw))
  1302. }
  1303. func (e *Engine) saveReadLocked() {
  1304. if e.db == nil {
  1305. return
  1306. }
  1307. raw, err := json.Marshal(e.readOrd)
  1308. if err != nil {
  1309. return
  1310. }
  1311. _, _ = e.db.Exec(
  1312. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1313. readKey, string(raw))
  1314. }
  1315. func (e *Engine) saveSilenceLocked() {
  1316. if e.db == nil {
  1317. return
  1318. }
  1319. raw, err := json.Marshal(e.silenceMap)
  1320. if err != nil {
  1321. return
  1322. }
  1323. _, _ = e.db.Exec(
  1324. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1325. silenceKey, string(raw))
  1326. }
  1327. func (e *Engine) saveDismissedLocked() {
  1328. if e.db == nil {
  1329. return
  1330. }
  1331. ids := make([]string, 0, len(e.dismissed))
  1332. for id := range e.dismissed {
  1333. ids = append(ids, id)
  1334. }
  1335. sort.Strings(ids)
  1336. raw, err := json.Marshal(ids)
  1337. if err != nil {
  1338. return
  1339. }
  1340. _, _ = e.db.Exec(
  1341. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  1342. dismissKey, string(raw))
  1343. }
  1344. func contains(list []string, v string) bool {
  1345. for _, x := range list {
  1346. if x == v {
  1347. return true
  1348. }
  1349. }
  1350. return false
  1351. }
  1352. // IsCategory reporta si v es una categoría válida (validación de query).
  1353. func IsCategory(v string) bool { return contains(Categories, v) }