agent.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. // agent.go — Adapter live-agent (SPEC-AGENTE-PILOTO §1): el último payload
  2. // empujado por el agente nativo a POST /api/ingest/agent ES el estado actual
  3. // del router. Si el agente deja de empujar (> AgentTTL, ~3 intervalos), el
  4. // router degrada a Tier 0 (SSH) con alerta category system urgent=false
  5. // ("Agente caído en <nombre> — volviendo a SSH"); al volver el agente se
  6. // retoma solo y se emite la alerta ok de recuperación.
  7. //
  8. // El registry guarda los payloads TAL CUAL llegan (shapes de agent/probe) y
  9. // Live los convierte a routerPolled con el mismo anti-parpadeo del pipeline
  10. // SSH (snapshot → SSE → persistencia sin cambios).
  11. package adapters
  12. import (
  13. "fmt"
  14. "sort"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gnacho/netpulse/agent/probe"
  19. "github.com/gnacho/netpulse/server-go/internal/alerts"
  20. "github.com/gnacho/netpulse/server-go/internal/vercmp"
  21. )
  22. // AgentTTLDefault: 3 intervalos de push de 15 s (default del agente) + margen.
  23. const AgentTTLDefault = 90 * time.Second
  24. // externalGraceFactor: los pushers externos declaran su cadencia en el
  25. // payload (Interval, segundos); su ventana efectiva es 3x esa cadencia
  26. // (#288). Un scraper que empuja cada 5 min declara 300 y queda fresco
  27. // hasta 15 min, en vez de expirar a los 90 s del default nativo.
  28. const externalGraceFactor = 3
  29. // AgentState es el último push conocido de un agente.
  30. type AgentState struct {
  31. Payload *probe.Payload
  32. LastSeen time.Time
  33. Version string
  34. Kind string // "" | "native" | "external" (#288)
  35. Interval int // cadencia declarada en segundos; 0 = default nativo
  36. // Host/BridgeMAC: última identidad conocida del agente (#852). Un push
  37. // wireless-only (evento nl80211, BuildWireless) no lleva sección system;
  38. // sin este recuerdo, MatchRouter perdería al agente hasta el próximo
  39. // push completo y cada roam de un cliente provocaría un "sin cliente"
  40. // transitorio en routers agent-only emparejados por hostname/MAC.
  41. Host string
  42. BridgeMAC string
  43. }
  44. // effectiveTTL devuelve la ventana de frescura del estado: el TTL base, o
  45. // 3x la cadencia declarada si es mayor (pushers externos lentos, #288).
  46. func (r *AgentRegistry) effectiveTTL(st *AgentState) time.Duration {
  47. if st != nil && st.Interval > 0 {
  48. if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > r.ttl {
  49. return d
  50. }
  51. }
  52. return r.ttl
  53. }
  54. // AgentRegistry guarda el último payload por slug (thread-safe: lo escribe el
  55. // handler de ingesta y lo lee el sondeo live).
  56. type AgentRegistry struct {
  57. mu sync.Mutex
  58. ttl time.Duration
  59. now func() time.Time
  60. states map[string]*AgentState
  61. }
  62. // NewAgentRegistry crea el registry con el TTL de expiración dado
  63. // (<= 0 → AgentTTLDefault).
  64. func NewAgentRegistry(ttl time.Duration) *AgentRegistry {
  65. if ttl <= 0 {
  66. ttl = AgentTTLDefault
  67. }
  68. return &AgentRegistry{ttl: ttl, now: time.Now, states: map[string]*AgentState{}}
  69. }
  70. // SetClock sustituye el reloj (solo tests).
  71. func (r *AgentRegistry) SetClock(f func() time.Time) {
  72. r.mu.Lock()
  73. defer r.mu.Unlock()
  74. r.now = f
  75. }
  76. // Ingest registra un push (último payload = estado actual del router).
  77. func (r *AgentRegistry) Ingest(p *probe.Payload) {
  78. r.mu.Lock()
  79. defer r.mu.Unlock()
  80. st := &AgentState{
  81. Payload: p, LastSeen: r.now(), Version: p.Version,
  82. Kind: p.Kind, Interval: p.Interval,
  83. }
  84. if sd := p.Data.System; sd != nil {
  85. if sd.Board != nil {
  86. st.Host = sd.Board.Hostname
  87. }
  88. st.BridgeMAC = sd.BridgeMAC
  89. }
  90. // #852: un push wireless-only no trae identidad; hereda la última
  91. // conocida para que MatchRouter siga emparejando al agente.
  92. if prev := r.states[p.Router]; prev != nil {
  93. if st.Host == "" {
  94. st.Host = prev.Host
  95. }
  96. if st.BridgeMAC == "" {
  97. st.BridgeMAC = prev.BridgeMAC
  98. }
  99. }
  100. r.states[p.Router] = st
  101. }
  102. // Info devuelve last_seen + versión + kind/interval para GET /api/agents
  103. // (sin exponer el payload).
  104. func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version, kind string, interval int, ok bool) {
  105. r.mu.Lock()
  106. defer r.mu.Unlock()
  107. st, found := r.states[slug]
  108. if !found {
  109. return time.Time{}, "", "", 0, false
  110. }
  111. return st.LastSeen, st.Version, st.Kind, st.Interval, true
  112. }
  113. // SelfExpose informa de si el router se expone él mismo a Home Assistant por
  114. // MQTT (#832), leyéndolo de la última muestra del agente. ok=false = el
  115. // agente no lo informa (standalone o embedder que no lo reporta).
  116. func (r *AgentRegistry) SelfExpose(slug string) (enabled bool, node string, ok bool) {
  117. r.mu.Lock()
  118. defer r.mu.Unlock()
  119. st, found := r.states[slug]
  120. if !found || st.Payload == nil || st.Payload.Data.MQTT == nil {
  121. return false, "", false
  122. }
  123. return st.Payload.Data.MQTT.Enabled, st.Payload.Data.MQTT.Node, true
  124. }
  125. // ExternalDownConfirm escala la ventana de confirmación de caída para un
  126. // pusher externo: max(confirm base, 3x su cadencia declarada) (#288). Con
  127. // la base a secas, un scraper de 5 min dispararía "agente caído" tras un
  128. // único push perdido.
  129. func (r *AgentRegistry) ExternalDownConfirm(slug string, base time.Duration) time.Duration {
  130. r.mu.Lock()
  131. defer r.mu.Unlock()
  132. st, ok := r.states[slug]
  133. if !ok || st.Interval <= 0 {
  134. return base
  135. }
  136. if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > base {
  137. return d
  138. }
  139. return base
  140. }
  141. // LocalBssids devuelve los BSSID que los agentes reportan como propios
  142. // (AP local=true en sus datos dawn/usteer). El channel-plan los usa de
  143. // semilla exacta para la detección de redes propias (#1082): casos como el
  144. // guest de un GL.iNet, cuya MAC no comparte prefijo con routers.mac.
  145. func (r *AgentRegistry) LocalBssids() []string {
  146. r.mu.Lock()
  147. defer r.mu.Unlock()
  148. seen := map[string]bool{}
  149. var out []string
  150. add := func(mac string) {
  151. mac = strings.ToUpper(strings.TrimSpace(mac))
  152. if mac == "" || seen[mac] {
  153. return
  154. }
  155. seen[mac] = true
  156. out = append(out, mac)
  157. }
  158. for _, st := range r.states {
  159. if st.Payload == nil {
  160. continue
  161. }
  162. // BSSIDs propios reportados por el agente (#1087): exactos, cubren
  163. // MACs aleatorizadas y guests fuera de dawn/usteer.
  164. if w := st.Payload.Data.Wireless; w != nil {
  165. for _, ob := range w.OwnBssids {
  166. add(ob.BSSID)
  167. }
  168. }
  169. if st.Payload.Data.Dawn != nil {
  170. for _, ssid := range st.Payload.Data.Dawn.SSIDs {
  171. for _, ap := range ssid.APs {
  172. if ap.Local {
  173. add(ap.BSSID)
  174. }
  175. }
  176. }
  177. }
  178. if st.Payload.Data.Usteer != nil {
  179. for _, ssid := range st.Payload.Data.Usteer.SSIDs {
  180. for _, ap := range ssid.APs {
  181. if ap.Local {
  182. add(ap.BSSID)
  183. }
  184. }
  185. }
  186. }
  187. }
  188. return out
  189. }
  190. // LocalSsids devuelve los SSID que los agentes reportan como propios
  191. // (#1358): OwnBssids con SSID no vacío + SSIDs con al menos un AP local en
  192. // dawn/usteer. Es la lista "auto-aprobada" para la detección de SSID
  193. // impostor: cualquier BSSID ajeno anunciando uno de estos nombres es
  194. // sospechoso. Dedup, ordenado para salida estable.
  195. func (r *AgentRegistry) LocalSsids() []string {
  196. r.mu.Lock()
  197. defer r.mu.Unlock()
  198. seen := map[string]bool{}
  199. var out []string
  200. add := func(ssid string) {
  201. if ssid == "" || seen[ssid] {
  202. return
  203. }
  204. seen[ssid] = true
  205. out = append(out, ssid)
  206. }
  207. for _, st := range r.states {
  208. if st.Payload == nil {
  209. continue
  210. }
  211. if w := st.Payload.Data.Wireless; w != nil {
  212. for _, ob := range w.OwnBssids {
  213. add(ob.SSID)
  214. }
  215. }
  216. if st.Payload.Data.Dawn != nil {
  217. for name, ssid := range st.Payload.Data.Dawn.SSIDs {
  218. for _, ap := range ssid.APs {
  219. if ap.Local {
  220. add(name)
  221. break
  222. }
  223. }
  224. }
  225. }
  226. if st.Payload.Data.Usteer != nil {
  227. for name, ssid := range st.Payload.Data.Usteer.SSIDs {
  228. for _, ap := range ssid.APs {
  229. if ap.Local {
  230. add(name)
  231. break
  232. }
  233. }
  234. }
  235. }
  236. }
  237. sort.Strings(out)
  238. return out
  239. }
  240. // Fresh devuelve el último payload si está dentro de su ventana de
  241. // frescura (TTL base o 3x cadencia declarada, #288).
  242. func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {
  243. r.mu.Lock()
  244. defer r.mu.Unlock()
  245. st, ok := r.states[slug]
  246. if !ok || r.now().Sub(st.LastSeen) > r.effectiveTTL(st) {
  247. return nil, false
  248. }
  249. return st.Payload, true
  250. }
  251. // Expired reporta si el slug tiene agente conocido pero su último push
  252. // expiró (candidato a degradar a SSH con aviso).
  253. func (r *AgentRegistry) Expired(slug string) bool {
  254. r.mu.Lock()
  255. defer r.mu.Unlock()
  256. st, ok := r.states[slug]
  257. return ok && r.now().Sub(st.LastSeen) > r.effectiveTTL(st)
  258. }
  259. // StalePayload devuelve el último payload del slug sin comprobar TTL.
  260. // Sirve para usar datos stale en routers agent-only (sin SSH).
  261. func (r *AgentRegistry) StalePayload(slug string) (*probe.Payload, bool) {
  262. r.mu.Lock()
  263. defer r.mu.Unlock()
  264. st, ok := r.states[slug]
  265. if !ok || st.Payload == nil {
  266. return nil, false
  267. }
  268. return st.Payload, true
  269. }
  270. // StaleFor reporta si el slug lleva más de threshold sin empujar datos.
  271. // Se usa para el Dead Man's Switch (P6): confirmar que un agente está
  272. // realmente caído antes de disparar la alerta, evitando spam en flapeos.
  273. func (r *AgentRegistry) StaleFor(slug string, threshold time.Duration) bool {
  274. r.mu.Lock()
  275. defer r.mu.Unlock()
  276. st, ok := r.states[slug]
  277. if !ok || st.LastSeen.IsZero() {
  278. return false
  279. }
  280. return r.now().Sub(st.LastSeen) > threshold
  281. }
  282. // ActiveCount devuelve cuántos agentes tienen su último push dentro del TTL
  283. // (métricas operativas de /api/health).
  284. func (r *AgentRegistry) ActiveCount() int {
  285. r.mu.Lock()
  286. defer r.mu.Unlock()
  287. n := 0
  288. for _, st := range r.states {
  289. if r.now().Sub(st.LastSeen) <= r.effectiveTTL(st) {
  290. n++
  291. }
  292. }
  293. return n
  294. }
  295. // Restore repuebla el estado de un slug desde el almacén persistente
  296. // (arranque del servidor). No revalida TTL: la expiración la decide el
  297. // reloj comparando contra el LastSeen restaurado. Sobrescribe cualquier
  298. // estado previo del slug. Los estados persistidos antes de #288 no traen
  299. // Kind/Interval y los de antes de #852 no traen Host/BridgeMAC: se
  300. // recuperan del payload si están ahí.
  301. func (r *AgentRegistry) Restore(slug string, st *AgentState) {
  302. r.mu.Lock()
  303. defer r.mu.Unlock()
  304. if st != nil && st.Payload != nil {
  305. if st.Interval == 0 {
  306. st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
  307. }
  308. if sd := st.Payload.Data.System; sd != nil {
  309. if st.Host == "" && sd.Board != nil {
  310. st.Host = sd.Board.Hostname
  311. }
  312. if st.BridgeMAC == "" {
  313. st.BridgeMAC = sd.BridgeMAC
  314. }
  315. }
  316. }
  317. r.states[slug] = st
  318. }
  319. // Snapshot devuelve una copia del estado de un slug (o nil si no existe).
  320. // Usado para persistir el último push sin exponer el map interno.
  321. func (r *AgentRegistry) Snapshot(slug string) *AgentState {
  322. r.mu.Lock()
  323. defer r.mu.Unlock()
  324. st, ok := r.states[slug]
  325. if !ok {
  326. return nil
  327. }
  328. cp := *st
  329. return &cp
  330. }
  331. // MatchRouter busca el agente asociado a un router: primero por slug exacto,
  332. // luego por hostname de board y finalmente por bridge MAC (#282). El match
  333. // por hostname/MAC usa la identidad retenida en el estado (#852), válida
  334. // aunque el último push sea wireless-only. Devuelve el slug real del
  335. // agente, su payload y si está fresco. Permite que un agente emparejado con
  336. // un slug elegido por el usuario alimente un router cuyo id autogenerado no
  337. // coincide con ese slug.
  338. func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (string, *probe.Payload, bool) {
  339. r.mu.Lock()
  340. defer r.mu.Unlock()
  341. norm := func(s string) string {
  342. return strings.ToLower(strings.TrimSpace(s))
  343. }
  344. hostNames := []string{}
  345. if cfg.Host != "" {
  346. hostNames = append(hostNames, norm(cfg.Host))
  347. }
  348. if cfg.Name != "" && norm(cfg.Name) != norm(cfg.Host) {
  349. hostNames = append(hostNames, norm(cfg.Name))
  350. }
  351. if cfg.ID != "" && norm(cfg.ID) != norm(cfg.Host) && norm(cfg.ID) != norm(cfg.Name) {
  352. hostNames = append(hostNames, norm(cfg.ID))
  353. }
  354. // #1334: la MAC de bridge persistida es la identidad física autoritativa
  355. // (los hostnames se duplican en APs puente idénticos). Se recogen TODOS
  356. // los candidatos por nivel y solo un match ÚNICO asocia: la ambigüedad no
  357. // inventa asociaciones (antes: primer match en orden aleatorio de mapa).
  358. targetMac := ""
  359. if macs != nil {
  360. targetMac = strings.ToUpper(strings.TrimSpace(macs[cfg.ID]))
  361. }
  362. var macMatch *AgentState
  363. var macMatchSlug string
  364. macMatchCount := 0
  365. var hostMatch *AgentState
  366. var hostMatchSlug string
  367. hostMatchCount := 0
  368. for slug, st := range r.states {
  369. if slug == cfg.ID {
  370. fresh := r.now().Sub(st.LastSeen) <= r.effectiveTTL(st)
  371. return slug, st.Payload, fresh
  372. }
  373. // #852: el match usa la identidad RETENIDA (Host/BridgeMAC), no la
  374. // del payload actual: el último push puede ser wireless-only (evento
  375. // nl80211, sin sección system) y aun así debe emparejar. Sin esto,
  376. // cada roam borraba la identidad hasta el próximo push completo.
  377. if st.Payload == nil {
  378. continue
  379. }
  380. if targetMac != "" && strings.EqualFold(st.BridgeMAC, targetMac) {
  381. macMatchCount++
  382. macMatch = st
  383. macMatchSlug = slug
  384. }
  385. if h := norm(st.Host); h != "" {
  386. for _, candidate := range hostNames {
  387. if h == candidate {
  388. hostMatchCount++
  389. hostMatch = st
  390. hostMatchSlug = slug
  391. break
  392. }
  393. }
  394. }
  395. }
  396. if macMatchCount == 1 {
  397. fresh := r.now().Sub(macMatch.LastSeen) <= r.effectiveTTL(macMatch)
  398. return macMatchSlug, macMatch.Payload, fresh
  399. }
  400. if macMatchCount > 1 {
  401. return "", nil, false
  402. }
  403. if hostMatchCount == 1 {
  404. fresh := r.now().Sub(hostMatch.LastSeen) <= r.effectiveTTL(hostMatch)
  405. return hostMatchSlug, hostMatch.Payload, fresh
  406. }
  407. return "", nil, false
  408. }
  409. // Forget borra el estado del slug (revocación de token).
  410. func (r *AgentRegistry) Forget(slug string) {
  411. r.mu.Lock()
  412. defer r.mu.Unlock()
  413. delete(r.states, slug)
  414. }
  415. // ---------------------------------------------------------------------------
  416. // Integración con Live
  417. // ---------------------------------------------------------------------------
  418. // SetAgents enchufa el registry de agentes al adapter live (nil = sin
  419. // soporte de agentes; todo va por SSH como antes).
  420. func (l *Live) SetAgents(r *AgentRegistry) {
  421. l.mu.Lock()
  422. l.agents = r
  423. l.mu.Unlock()
  424. }
  425. // SetAgentDownConfirm fija el periodo de confirmación del Dead Man's Switch
  426. // (P6): tiempo sin push tras el cual se confirma la caída de un agente.
  427. func (l *Live) SetAgentDownConfirm(d time.Duration) {
  428. l.mu.Lock()
  429. if d > 0 {
  430. l.agentDownConfirm = d
  431. }
  432. l.mu.Unlock()
  433. }
  434. // SetAgentLatestSource fija la fuente de la versión de referencia por kind
  435. // de agente (issue #400): native → binario embebido del server, netgrip →
  436. // última release pública de NetGrip, external → "" (nunca alerta). nil o
  437. // referencia vacía desactivan el check de agente desactualizado.
  438. func (l *Live) SetAgentLatestSource(fn func(kind string) string) {
  439. l.mu.Lock()
  440. l.agentLatest = fn
  441. l.mu.Unlock()
  442. }
  443. // agentName: nombre para las alertas (cfg.Name o Host como el resto).
  444. func agentName(cfg RouterConfig) string {
  445. if cfg.Name != "" {
  446. return cfg.Name
  447. }
  448. return cfg.Host
  449. }
  450. // pollRouterAgent: si un agente asociado al router está fresco, construye el
  451. // sondeo desde su payload (Tier 2). Si expiró, emite UNA vez la alerta de
  452. // caída y devuelve (false, nil) para que el caller siga por SSH (Tier 0).
  453. // El emparejamiento no exige slug == router.id: también usa hostname/MAC
  454. // (#282). Cuando el agente está vivo pero el SSH falla por clave no
  455. // autorizada, emite una alerta informativa en vez de dejar la tarjeta en
  456. // offline (#281).
  457. func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
  458. l.mu.Lock()
  459. reg := l.agents
  460. macs := make(map[string]string, len(l.routerMacs))
  461. for k, v := range l.routerMacs {
  462. macs[k] = v
  463. }
  464. l.mu.Unlock()
  465. if reg == nil {
  466. return false, nil
  467. }
  468. slug, p, fresh := reg.MatchRouter(cfg, macs)
  469. if fresh {
  470. // issue #400: versión del agente desactualizada (alerta consolidada).
  471. l.checkAgentVersion(cfg, p)
  472. l.mu.Lock()
  473. if l.agentDown[cfg.ID] {
  474. l.agentDown[cfg.ID] = false
  475. name := agentName(cfg)
  476. // #966: la alerta de caída es VOLÁTIL con ID estable por router:
  477. // al recuperarse el agente desaparece del feed (no acumula
  478. // historial). "Agente recuperado" SÍ persiste (registro positivo).
  479. l.engine.Remove("alert-agent-down-" + cfg.ID)
  480. l.engine.Emit(AlertEvent{
  481. ID: fmt.Sprintf("alert-agent-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
  482. Category: alerts.CatSystem, Urgent: false,
  483. Severity: "ok",
  484. Title: "Agent recovered on " + name,
  485. Description: fmt.Sprintf("The agent on %s is pushing data again - native polling resumed", name),
  486. Type: alerts.TypeAgentRecovered,
  487. Vars: map[string]string{"router": name},
  488. Time: "just now", RouterID: cfg.ID,
  489. })
  490. }
  491. // issue #281: SSH falla por clave no autorizada pero el agente sigue
  492. // vivo → avisa una sola vez. Se borra el flag cuando SSH vuelve.
  493. if l.lastErr[cfg.ID] != nil && isAccessError(l.lastErr[cfg.ID]) {
  494. if !l.sshAuthFailAlerted[cfg.ID] {
  495. l.sshAuthFailAlerted[cfg.ID] = true
  496. name := agentName(cfg)
  497. l.engine.Emit(AlertEvent{
  498. ID: fmt.Sprintf("alert-ssh-auth-%s-%d", cfg.ID, time.Now().UnixMilli()),
  499. Category: alerts.CatSystem, Urgent: false,
  500. Severity: "warn",
  501. Title: "SSH access lost on " + name,
  502. Description: fmt.Sprintf("%s does not accept the SSH key, but its agent keeps sending data. Check authorized_keys after a firmware upgrade.", name),
  503. Type: alerts.TypeSSHAccessLost,
  504. Vars: map[string]string{"router": name},
  505. Time: "just now", RouterID: cfg.ID,
  506. })
  507. }
  508. } else if l.sshAuthFailAlerted[cfg.ID] {
  509. delete(l.sshAuthFailAlerted, cfg.ID)
  510. name := agentName(cfg)
  511. l.engine.Emit(AlertEvent{
  512. ID: fmt.Sprintf("alert-ssh-auth-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
  513. Category: alerts.CatSystem, Urgent: false,
  514. Severity: "ok",
  515. Title: "SSH access recovered on " + name,
  516. Description: fmt.Sprintf("SSH access to %s is working again", name),
  517. Type: alerts.TypeSSHAccessRecovered,
  518. Vars: map[string]string{"router": name},
  519. Time: "just now", RouterID: cfg.ID,
  520. })
  521. }
  522. l.mu.Unlock()
  523. return true, l.polledFromAgent(cfg, p)
  524. }
  525. if slug != "" {
  526. // Dead Man's Switch (P6): el agente está stale, pero solo disparamos la
  527. // alerta de caída si lleva más de agentDownConfirm sin empujar. Entre
  528. // TTL y agentDownConfirm el router degrada a SSH silenciosamente.
  529. confirm := l.agentDownConfirm
  530. if confirm <= 0 {
  531. confirm = 3 * time.Minute
  532. }
  533. confirm = reg.ExternalDownConfirm(slug, confirm)
  534. if reg.StaleFor(slug, confirm) {
  535. l.mu.Lock()
  536. if !l.agentDown[cfg.ID] {
  537. l.agentDown[cfg.ID] = true
  538. name := agentName(cfg)
  539. // #850: para routers agent-only el agente ES la única vía
  540. // de datos (el poll sirve el payload cacheado y el router
  541. // nunca marca offline): su caída es un evento de router
  542. // urgente, comparable al offline, para que pase los filtros
  543. // de notificación "solo urgentes del topic router". Con SSH
  544. // disponible se degrada con gracia y sigue siendo system.
  545. // #966: la alerta de caída es VOLÁTIL y con ID estable por
  546. // router (alert-agent-down-<id>): no se persiste en
  547. // alert_log, no sobrevive reinicios y al recuperarse el
  548. // agente desaparece del feed (engine.Remove arriba).
  549. if cfg.AgentOnly {
  550. l.engine.EmitVolatile(AlertEvent{
  551. ID: "alert-agent-down-" + cfg.ID,
  552. Category: alerts.CatRouter, Urgent: true,
  553. Severity: "critical",
  554. Title: fmt.Sprintf("Agent down on %s", name),
  555. Description: fmt.Sprintf("No data from the agent on %s for more than %s - using cached data", name, confirm),
  556. Hint: alerts.HintFor(alerts.HintAgentDown),
  557. Type: alerts.HintAgentDown,
  558. Vars: map[string]string{"router": name, "confirm": confirm.String()},
  559. Time: "just now", RouterID: cfg.ID,
  560. })
  561. } else {
  562. l.engine.EmitVolatile(AlertEvent{
  563. ID: "alert-agent-down-" + cfg.ID,
  564. Category: alerts.CatSystem, Urgent: false,
  565. Severity: "warn",
  566. Title: fmt.Sprintf("Agent down on %s - falling back to SSH", name),
  567. Description: fmt.Sprintf("No data from the agent on %s for more than %s - SSH polling resumed", name, confirm),
  568. Hint: alerts.HintFor(alerts.HintAgentDownSSH),
  569. Type: alerts.HintAgentDownSSH,
  570. Vars: map[string]string{"router": name, "confirm": confirm.String()},
  571. Time: "just now", RouterID: cfg.ID,
  572. })
  573. }
  574. }
  575. l.mu.Unlock()
  576. }
  577. if cfg.AgentOnly {
  578. if p != nil {
  579. return true, l.polledFromAgent(cfg, p)
  580. }
  581. }
  582. }
  583. return false, nil
  584. }
  585. // agentIfSample: contadores por iface del último payload del agente (para
  586. // el delta de rates por boca, issue #305).
  587. type agentIfSample struct {
  588. at time.Time
  589. ifaces map[string]probe.IfCounters
  590. }
  591. // injectPortRates copia absolutos + rates de rates (keyed por iface física)
  592. // sobre las bocas: match por Iface si la boca la declara, si no por ID (en
  593. // DSA coinciden; en swconfig el ID es numérico y solo Iface casa).
  594. func injectPortRates(ports []EthPort, rates map[string]probe.IfRate) {
  595. for i := range ports {
  596. key := ports[i].Iface
  597. if key == "" {
  598. key = ports[i].ID
  599. }
  600. r, ok := rates[key]
  601. if !ok {
  602. continue
  603. }
  604. ports[i].Iface = key
  605. ports[i].RxBytes = r.Rx
  606. ports[i].TxBytes = r.Tx
  607. ports[i].RxErrs = r.RxErr
  608. ports[i].TxErrs = r.TxErr
  609. if r.RxBps != nil {
  610. ports[i].RxBps = *r.RxBps
  611. }
  612. if r.TxBps != nil {
  613. ports[i].TxBps = *r.TxBps
  614. }
  615. }
  616. }
  617. // polledFromAgent convierte el payload del agente en el routerPolled del
  618. // pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
  619. // que pollRouter: sección ausente en el payload = sonda fallida → conserva
  620. // el último dato bueno cacheado.
  621. func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled {
  622. l.mu.Lock()
  623. cached := l.extrasCache[cfg.ID]
  624. l.mu.Unlock()
  625. out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}, polledAt: time.Now().UnixMilli()}
  626. // #441: conservar el kind del agente: los pushers externos (beacon/
  627. // scraper) no llevan sección system y el router queda sin vitals.
  628. out.agentKind = p.Kind
  629. // #832: el equipo se expone él mismo a Home Assistant por MQTT (NetGrip
  630. // con su MQTT activado); el publisher de flota cede el paso.
  631. out.selfExpose = p.Data.MQTT != nil && p.Data.MQTT.Enabled
  632. sysInfo := &SysInfo{}
  633. ramPct := 0
  634. if sd := p.Data.System; sd != nil {
  635. if sd.SysInfo != nil {
  636. sysInfo = sd.SysInfo
  637. }
  638. out.board = sd.Board
  639. if sd.Board != nil {
  640. l.mu.Lock()
  641. l.boardCache[cfg.ID] = sd.Board
  642. l.mu.Unlock()
  643. }
  644. if sd.CPU != nil {
  645. out.cpu = *sd.CPU
  646. }
  647. if sd.Temp != nil {
  648. out.temp = *sd.Temp
  649. }
  650. out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
  651. out.latencyMs = sd.LatencyMs
  652. out.lossPct = sd.LossPct
  653. out.backhaul = sd.Backhaul
  654. out.brMac = sd.BridgeMAC
  655. out.flash = sd.Flash
  656. out.firmwareAvailable = sd.FirmwareAvailable
  657. } else if cached != nil && cached.system != nil {
  658. // #441: push event-driven (wireless-only) sin system → conserva las
  659. // últimas vitals buenas cacheadas en vez de pintar ceros falsos.
  660. // Solo vitals/uptime: net/latencia/backhaul no se reciclan (evita
  661. // duplicar tráfico con muestras viejas).
  662. sd := cached.system
  663. if sd.CPU != nil {
  664. out.cpu = *sd.CPU
  665. }
  666. if sd.Temp != nil {
  667. out.temp = *sd.Temp
  668. }
  669. if sd.SysInfo != nil {
  670. sysInfo = sd.SysInfo
  671. }
  672. }
  673. mem := sysInfo.Memory
  674. if mem.Total > 0 {
  675. ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
  676. }
  677. out.sysInfo = sysInfo
  678. out.ram = ramPct
  679. out.uptimeSec = sysInfo.Uptime
  680. // Secciones con anti-parpadeo (nil en el payload = sonda fallida).
  681. if wd := p.Data.Wireless; wd != nil {
  682. if wd.Clients != nil {
  683. out.wireless = wd.Clients
  684. }
  685. if len(wd.Radios) > 0 {
  686. out.radios = radiosToAdapter(wd.Radios)
  687. }
  688. }
  689. if dd := p.Data.DHCP; dd != nil {
  690. out.leases = dd.Leases
  691. // gl-clients del agente (GL.iNet): enriquece IPs igual que en la
  692. // ruta SSH (issue #5 bug 1).
  693. out.glClients = dd.GlClients
  694. }
  695. if p.Data.Arp != nil {
  696. out.arp = p.Data.Arp
  697. out.arpDevs = p.Data.ArpDevs
  698. // An agent old enough not to send arpStale leaves this empty, and
  699. // the whole table counts as presence, exactly as it used to.
  700. out.arpStale = make(map[string]bool, len(p.Data.ArpStale))
  701. for _, mac := range p.Data.ArpStale {
  702. out.arpStale[strings.ToUpper(mac)] = true
  703. }
  704. }
  705. // Wan (#276): el agente lo trae en el payload desde 2.28.24+. Antes solo
  706. // existía la sonda SSH del server, que en un router agent_only no corre
  707. // nunca -- y su panel de conexión se quedaba vacío.
  708. if w := p.Data.Wan; w != nil {
  709. out.wanInfo = *w
  710. }
  711. // MultiWan: the several internet connections and which one carries
  712. // traffic. Only a router whose own panel manages them reports it; an
  713. // event-driven push carries no section, so the last good one is kept
  714. // or the panel would blink out between full pushes.
  715. out.multiWan = normalizeMultiWan(p.Data.MultiWan)
  716. if out.multiWan == nil && cached != nil {
  717. out.multiWan = cached.multiWan
  718. }
  719. // Vlans travel in the payload too, and were being dropped here: a
  720. // router polled through its agent never reached the SSH path that is
  721. // the only other place they are read, so its VLAN panel stayed empty.
  722. if len(p.Data.Vlans) > 0 {
  723. out.vlans = p.Data.Vlans
  724. } else if cached != nil {
  725. out.vlans = cached.vlans
  726. }
  727. if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
  728. out.reservations = dh.Reservations
  729. }
  730. if fd := p.Data.FDB; fd != nil {
  731. if fd.MACs != nil {
  732. out.fdb = fd.MACs
  733. }
  734. // Sección FDB fresca: el hint wireless-side se pisa tal cual, incluso
  735. // vacío (nadie lo refresca ya: agente caído o pasado a SSH). Solo un
  736. // push SIN sección FDB (event-driven) recicla el cache, mismo contrato
  737. // anti-parpadeo que fdb.
  738. out.wirelessSide = fd.WirelessSide
  739. if len(fd.Ports) > 0 {
  740. out.ports = ethPortsToAdapter(fd.Ports)
  741. // #291: los pushers externos declaran el puerto del FDB como
  742. // número ("1") mientras sus bocas usan id "lan1". Normalizar
  743. // para que el enriquecimiento del detalle (MAC→nombre por boca)
  744. // y la topología casen ambas claves.
  745. ids := map[string]bool{}
  746. for _, ep := range out.ports {
  747. ids[ep.ID] = true
  748. }
  749. if len(ids) > 0 {
  750. for mac, port := range out.fdb {
  751. if port == "wan" || ids[port] {
  752. continue
  753. }
  754. if lan := "lan" + port; ids[lan] {
  755. out.fdb[mac] = lan
  756. }
  757. }
  758. }
  759. }
  760. }
  761. // LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de
  762. // topología. Best-effort: sección ausente → conserva la última buena.
  763. if p.Data.LuCI != nil {
  764. out.luci = p.Data.LuCI
  765. }
  766. // LLDP (#489): vecinos del payload del agente (antes solo llegaban por
  767. // la sonda SSH, muerta para routers con agente fresco). Resolución con
  768. // anti-parpadeo: manda la sección buena del payload; una sección
  769. // fallida (Available=true con Neighbors nil) o ausente (push
  770. // event-driven) recicla la última cacheada. Available=false explícito =
  771. // lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
  772. resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
  773. ld := p.Data.Lldp
  774. if ld == nil || (ld.Available && ld.Neighbors == nil) {
  775. ld = nil
  776. if cached != nil {
  777. ld = cached.lldp
  778. }
  779. }
  780. if ld == nil {
  781. return nil, false, ""
  782. }
  783. if !ld.Available {
  784. return nil, true, ""
  785. }
  786. return lldpFromProbe(ld.Neighbors), false, ld.Hint
  787. }
  788. out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
  789. // ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
  790. // LLDP: la sección buena del payload manda; una sección fallida
  791. // (Available=true con Hosts nil) o ausente (push event-driven) recicla
  792. // la última cacheada; Available=false explícito = nlbwmon no instalado
  793. // y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
  794. resolveClientBw := func() *probe.ClientBwData {
  795. cb := p.Data.ClientBw
  796. if cb == nil || (cb.Available && cb.Hosts == nil) {
  797. cb = nil
  798. if cached != nil {
  799. cb = cached.clientBw
  800. }
  801. }
  802. if cb == nil || !cb.Available {
  803. return nil
  804. }
  805. return cb
  806. }
  807. out.clientBw = resolveClientBw()
  808. // Discovery (#338): mDNS services + randomized MACs. Best-effort.
  809. if p.Data.Discovery != nil {
  810. out.discovery = p.Data.Discovery
  811. }
  812. out.dawnDetected = p.Data.Dawn != nil
  813. if cached == nil {
  814. cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
  815. wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
  816. }
  817. if out.ports == nil {
  818. out.ports = cached.ports
  819. }
  820. if out.radios == nil {
  821. out.radios = cached.radios
  822. }
  823. if out.wireless == nil {
  824. out.wireless = cached.wireless
  825. }
  826. if out.fdb == nil {
  827. out.fdb = cached.fdb
  828. }
  829. if out.wirelessSide == nil && p.Data.FDB == nil {
  830. out.wirelessSide = cached.wirelessSide
  831. }
  832. if out.luci == nil {
  833. out.luci = cached.luci
  834. }
  835. // NetIf (issue #305): rates por boca con el delta entre payloads del
  836. // agente. El payload trae contadores ABSOLUTOS por iface; el server
  837. // calcula bps con la muestra anterior (ts del propio payload, no el
  838. // reloj del server). Sección ausente → conserva los rates cacheados.
  839. // Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
  840. // snapshot para que el cache lleve los rates frescos.
  841. if p.Data.NetIf != nil {
  842. now := time.Unix(p.Ts, 0)
  843. l.mu.Lock()
  844. prev := l.lastAgentIf[cfg.ID]
  845. l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
  846. l.mu.Unlock()
  847. if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
  848. rates := probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
  849. injectPortRates(out.ports, rates)
  850. }
  851. }
  852. l.mu.Lock()
  853. freshPayload := p.Ts != l.lastObsTs[cfg.ID]
  854. if freshPayload {
  855. l.lastObsTs[cfg.ID] = p.Ts
  856. }
  857. // #441: el cache de system guarda la última sección BUENA (un push
  858. // wireless-only no la invalida).
  859. sysSnap := p.Data.System
  860. if sysSnap == nil && cached != nil {
  861. sysSnap = cached.system
  862. }
  863. lldpSnap := p.Data.Lldp
  864. if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
  865. lldpSnap = cached.lldp // conserva la última sección buena (#489)
  866. }
  867. l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
  868. wireless: out.wireless, fdb: out.fdb, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, lldp: lldpSnap,
  869. clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
  870. l.mu.Unlock()
  871. // Solo con un payload NUEVO alimentamos las series y el monitor de
  872. // puertos (issue #365): entre pushes, cada rebuild del overview vuelve
  873. // por aquí con el MISMO payload cacheado, y re-observar contadores
  874. // congelados dispara alertas fantasma ("zero bytes" que solo es espera
  875. // del siguiente push).
  876. if freshPayload {
  877. // Los pushers external/beacon persisten sus propias series con
  878. // contadores de tramas en recordBeaconPortSamples (httpapi/beacon.go);
  879. // los EthPort de su payload no llevan contadores, así que pasar por
  880. // recordPortSamples escribiría filas a 0 intercaladas con las buenas.
  881. if out.agentKind != "external" {
  882. l.recordPortSamples(cfg.ID, out.ports)
  883. }
  884. // #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
  885. // now = ts del payload (no el reloj del server) para que el dt del
  886. // delta sea el intervalo real entre pushes del agente.
  887. if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
  888. l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
  889. }
  890. l.portMon.Observe(cfg.ID, out.ports, l.engine)
  891. }
  892. if out.leases == nil {
  893. out.leases = []DhcpLease{}
  894. }
  895. return out
  896. }
  897. // checkAgentVersion (issue #400): alerta consolidada (no urgente, sistema)
  898. // cuando el agente fresh del router empuja una versión anterior a la de
  899. // referencia de su kind: native → binario de agente embebido en el server,
  900. // netgrip → última release pública de NetGrip, external → sin check. Al
  901. // volver a estar al día emite UNA alerta ok de recuperación (patrón
  902. // consolidación de portmonitor, issue #366).
  903. func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
  904. l.mu.Lock()
  905. src := l.agentLatest
  906. l.mu.Unlock()
  907. if src == nil || p == nil || p.Version == "" || p.Kind == "external" {
  908. return
  909. }
  910. ref := src(p.Kind)
  911. if ref == "" {
  912. return
  913. }
  914. name := agentName(cfg)
  915. kindLabel := "NetPulse"
  916. if p.Kind == "netgrip" {
  917. kindLabel = "NetGrip"
  918. }
  919. l.mu.Lock()
  920. alerted := l.agentOutdatedAlerted[cfg.ID]
  921. l.mu.Unlock()
  922. if vercmp.Cmp(ref, p.Version) > 0 {
  923. if !alerted {
  924. l.mu.Lock()
  925. l.agentOutdatedAlerted[cfg.ID] = true
  926. l.mu.Unlock()
  927. }
  928. // #910: EmitOrUpdate notifica en cada actualización en sitio; sin
  929. // este guard, cada push del agente (30 s) reenviaba la notificación
  930. // push y refrescaba el timestamp de la alerta. Solo se emite cuando
  931. // la versión observada o la de referencia cambian.
  932. key := p.Version + "|" + ref
  933. l.mu.Lock()
  934. unchanged := l.agentOutdatedKey[cfg.ID] == key
  935. if !unchanged {
  936. l.agentOutdatedKey[cfg.ID] = key
  937. }
  938. l.mu.Unlock()
  939. if unchanged {
  940. return
  941. }
  942. l.engine.EmitOrUpdate(AlertEvent{
  943. ID: fmt.Sprintf("alert-agent-outdated-%s", cfg.ID),
  944. Category: alerts.CatSystem, Urgent: false,
  945. Severity: "warn",
  946. Title: "Agent outdated on " + name,
  947. Description: fmt.Sprintf("%s pushes version %s; the latest available for the %s agent is %s", name, p.Version, kindLabel, ref),
  948. Hint: alerts.HintFor(alerts.HintAgentOutdated),
  949. Type: alerts.HintAgentOutdated,
  950. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
  951. Time: "just now", RouterID: cfg.ID,
  952. })
  953. } else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
  954. l.mu.Lock()
  955. delete(l.agentOutdatedAlerted, cfg.ID)
  956. l.mu.Unlock()
  957. // #833: la alerta de desactualizado DESAPARECE del feed al
  958. // actualizarse el agente (además del aviso ok de recuperación, que
  959. // solo se emite cuando el flag en memoria estaba activo).
  960. l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
  961. l.mu.Lock()
  962. delete(l.agentOutdatedKey, cfg.ID)
  963. l.mu.Unlock()
  964. if alerted {
  965. l.engine.Emit(AlertEvent{
  966. ID: fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
  967. Category: alerts.CatSystem, Urgent: false,
  968. Severity: "ok",
  969. Title: "Agent updated on " + name,
  970. Description: fmt.Sprintf("%s now pushes version %s of %s", name, p.Version, kindLabel),
  971. Type: alerts.TypeAgentUpdated,
  972. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
  973. // #1349: el evento de cierre referencia al que resuelve
  974. // (conservado en el log marcado, no borrado).
  975. Resolves: []string{fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)},
  976. Time: "just now", RouterID: cfg.ID,
  977. })
  978. }
  979. }
  980. }