agent.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. // Un pusher externo puede mandar MAC en minúsculas o con guiones y el resto
  79. // del servidor compara las claves de forma exacta: se normaliza una vez aquí.
  80. normalizePayloadMACs(p)
  81. r.mu.Lock()
  82. defer r.mu.Unlock()
  83. st := &AgentState{
  84. Payload: p, LastSeen: r.now(), Version: p.Version,
  85. Kind: p.Kind, Interval: p.Interval,
  86. }
  87. if sd := p.Data.System; sd != nil {
  88. if sd.Board != nil {
  89. st.Host = sd.Board.Hostname
  90. }
  91. st.BridgeMAC = sd.BridgeMAC
  92. }
  93. // #852: un push wireless-only no trae identidad; hereda la última
  94. // conocida para que MatchRouter siga emparejando al agente.
  95. if prev := r.states[p.Router]; prev != nil {
  96. if st.Host == "" {
  97. st.Host = prev.Host
  98. }
  99. if st.BridgeMAC == "" {
  100. st.BridgeMAC = prev.BridgeMAC
  101. }
  102. }
  103. r.states[p.Router] = st
  104. }
  105. // Info devuelve last_seen + versión + kind/interval para GET /api/agents
  106. // (sin exponer el payload).
  107. func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version, kind string, interval int, ok bool) {
  108. r.mu.Lock()
  109. defer r.mu.Unlock()
  110. st, found := r.states[slug]
  111. if !found {
  112. return time.Time{}, "", "", 0, false
  113. }
  114. return st.LastSeen, st.Version, st.Kind, st.Interval, true
  115. }
  116. // Identity devuelve la identidad retenida del agente: hostname del board y
  117. // MAC del bridge, aunque el último push sea event-driven y no traiga sección
  118. // system (#852 los conserva en AgentState). La usa GET /api/agents para
  119. // asociar el agente con su router cuando el payload actual no lleva identidad
  120. // (#1874).
  121. func (r *AgentRegistry) Identity(slug string) (host, bridgeMAC string, ok bool) {
  122. r.mu.Lock()
  123. defer r.mu.Unlock()
  124. st, found := r.states[slug]
  125. if !found {
  126. return "", "", false
  127. }
  128. return st.Host, st.BridgeMAC, true
  129. }
  130. // SelfExpose informa de si el router se expone él mismo a Home Assistant por
  131. // MQTT (#832), leyéndolo de la última muestra del agente. ok=false = el
  132. // agente no lo informa (standalone o embedder que no lo reporta).
  133. func (r *AgentRegistry) SelfExpose(slug string) (enabled bool, node string, ok bool) {
  134. r.mu.Lock()
  135. defer r.mu.Unlock()
  136. st, found := r.states[slug]
  137. if !found || st.Payload == nil || st.Payload.Data.MQTT == nil {
  138. return false, "", false
  139. }
  140. return st.Payload.Data.MQTT.Enabled, st.Payload.Data.MQTT.Node, true
  141. }
  142. // ExternalDownConfirm escala la ventana de confirmación de caída para un
  143. // pusher externo: max(confirm base, 3x su cadencia declarada) (#288). Con
  144. // la base a secas, un scraper de 5 min dispararía "agente caído" tras un
  145. // único push perdido.
  146. func (r *AgentRegistry) ExternalDownConfirm(slug string, base time.Duration) time.Duration {
  147. r.mu.Lock()
  148. defer r.mu.Unlock()
  149. st, ok := r.states[slug]
  150. if !ok || st.Interval <= 0 {
  151. return base
  152. }
  153. if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > base {
  154. return d
  155. }
  156. return base
  157. }
  158. // LocalBssids devuelve los BSSID que los agentes reportan como propios
  159. // (AP local=true en sus datos dawn/usteer). El channel-plan los usa de
  160. // semilla exacta para la detección de redes propias (#1082): casos como el
  161. // guest de un GL.iNet, cuya MAC no comparte prefijo con routers.mac.
  162. func (r *AgentRegistry) LocalBssids() []string {
  163. r.mu.Lock()
  164. defer r.mu.Unlock()
  165. seen := map[string]bool{}
  166. var out []string
  167. add := func(mac string) {
  168. mac = strings.ToUpper(strings.TrimSpace(mac))
  169. if mac == "" || seen[mac] {
  170. return
  171. }
  172. seen[mac] = true
  173. out = append(out, mac)
  174. }
  175. for _, st := range r.states {
  176. if st.Payload == nil {
  177. continue
  178. }
  179. // BSSIDs propios reportados por el agente (#1087): exactos, cubren
  180. // MACs aleatorizadas y guests fuera de dawn/usteer.
  181. if w := st.Payload.Data.Wireless; w != nil {
  182. for _, ob := range w.OwnBssids {
  183. add(ob.BSSID)
  184. }
  185. }
  186. if st.Payload.Data.Dawn != nil {
  187. for _, ssid := range st.Payload.Data.Dawn.SSIDs {
  188. for _, ap := range ssid.APs {
  189. if ap.Local {
  190. add(ap.BSSID)
  191. }
  192. }
  193. }
  194. }
  195. if st.Payload.Data.Usteer != nil {
  196. for _, ssid := range st.Payload.Data.Usteer.SSIDs {
  197. for _, ap := range ssid.APs {
  198. if ap.Local {
  199. add(ap.BSSID)
  200. }
  201. }
  202. }
  203. }
  204. }
  205. return out
  206. }
  207. // LocalSsids devuelve los SSID que los agentes reportan como propios
  208. // (#1358): OwnBssids con SSID no vacío + SSIDs con al menos un AP local en
  209. // dawn/usteer. Es la lista "auto-aprobada" para la detección de SSID
  210. // impostor: cualquier BSSID ajeno anunciando uno de estos nombres es
  211. // sospechoso. Dedup, ordenado para salida estable.
  212. func (r *AgentRegistry) LocalSsids() []string {
  213. r.mu.Lock()
  214. defer r.mu.Unlock()
  215. seen := map[string]bool{}
  216. var out []string
  217. add := func(ssid string) {
  218. if ssid == "" || seen[ssid] {
  219. return
  220. }
  221. seen[ssid] = true
  222. out = append(out, ssid)
  223. }
  224. for _, st := range r.states {
  225. if st.Payload == nil {
  226. continue
  227. }
  228. if w := st.Payload.Data.Wireless; w != nil {
  229. for _, ob := range w.OwnBssids {
  230. add(ob.SSID)
  231. }
  232. }
  233. if st.Payload.Data.Dawn != nil {
  234. for name, ssid := range st.Payload.Data.Dawn.SSIDs {
  235. for _, ap := range ssid.APs {
  236. if ap.Local {
  237. add(name)
  238. break
  239. }
  240. }
  241. }
  242. }
  243. if st.Payload.Data.Usteer != nil {
  244. for name, ssid := range st.Payload.Data.Usteer.SSIDs {
  245. for _, ap := range ssid.APs {
  246. if ap.Local {
  247. add(name)
  248. break
  249. }
  250. }
  251. }
  252. }
  253. }
  254. sort.Strings(out)
  255. return out
  256. }
  257. // Fresh devuelve el último payload si está dentro de su ventana de
  258. // frescura (TTL base o 3x cadencia declarada, #288).
  259. func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {
  260. r.mu.Lock()
  261. defer r.mu.Unlock()
  262. st, ok := r.states[slug]
  263. if !ok || r.now().Sub(st.LastSeen) > r.effectiveTTL(st) {
  264. return nil, false
  265. }
  266. return st.Payload, true
  267. }
  268. // Expired reporta si el slug tiene agente conocido pero su último push
  269. // expiró (candidato a degradar a SSH con aviso).
  270. func (r *AgentRegistry) Expired(slug string) bool {
  271. r.mu.Lock()
  272. defer r.mu.Unlock()
  273. st, ok := r.states[slug]
  274. return ok && r.now().Sub(st.LastSeen) > r.effectiveTTL(st)
  275. }
  276. // StalePayload devuelve el último payload del slug sin comprobar TTL.
  277. // Sirve para usar datos stale en routers agent-only (sin SSH).
  278. func (r *AgentRegistry) StalePayload(slug string) (*probe.Payload, bool) {
  279. r.mu.Lock()
  280. defer r.mu.Unlock()
  281. st, ok := r.states[slug]
  282. if !ok || st.Payload == nil {
  283. return nil, false
  284. }
  285. return st.Payload, true
  286. }
  287. // StaleFor reporta si el slug lleva más de threshold sin empujar datos.
  288. // Se usa para el Dead Man's Switch (P6): confirmar que un agente está
  289. // realmente caído antes de disparar la alerta, evitando spam en flapeos.
  290. func (r *AgentRegistry) StaleFor(slug string, threshold time.Duration) bool {
  291. r.mu.Lock()
  292. defer r.mu.Unlock()
  293. st, ok := r.states[slug]
  294. if !ok || st.LastSeen.IsZero() {
  295. return false
  296. }
  297. return r.now().Sub(st.LastSeen) > threshold
  298. }
  299. // ActiveCount devuelve cuántos agentes tienen su último push dentro del TTL
  300. // (métricas operativas de /api/health).
  301. func (r *AgentRegistry) ActiveCount() int {
  302. r.mu.Lock()
  303. defer r.mu.Unlock()
  304. n := 0
  305. for _, st := range r.states {
  306. if r.now().Sub(st.LastSeen) <= r.effectiveTTL(st) {
  307. n++
  308. }
  309. }
  310. return n
  311. }
  312. // Restore repuebla el estado de un slug desde el almacén persistente
  313. // (arranque del servidor). No revalida TTL: la expiración la decide el
  314. // reloj comparando contra el LastSeen restaurado. Sobrescribe cualquier
  315. // estado previo del slug. Los estados persistidos antes de #288 no traen
  316. // Kind/Interval y los de antes de #852 no traen Host/BridgeMAC: se
  317. // recuperan del payload si están ahí.
  318. func (r *AgentRegistry) Restore(slug string, st *AgentState) {
  319. r.mu.Lock()
  320. defer r.mu.Unlock()
  321. if st != nil && st.Payload != nil {
  322. if st.Interval == 0 {
  323. st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
  324. }
  325. if sd := st.Payload.Data.System; sd != nil {
  326. if st.Host == "" && sd.Board != nil {
  327. st.Host = sd.Board.Hostname
  328. }
  329. if st.BridgeMAC == "" {
  330. st.BridgeMAC = sd.BridgeMAC
  331. }
  332. }
  333. }
  334. r.states[slug] = st
  335. }
  336. // Snapshot devuelve una copia del estado de un slug (o nil si no existe).
  337. // Usado para persistir el último push sin exponer el map interno.
  338. func (r *AgentRegistry) Snapshot(slug string) *AgentState {
  339. r.mu.Lock()
  340. defer r.mu.Unlock()
  341. st, ok := r.states[slug]
  342. if !ok {
  343. return nil
  344. }
  345. cp := *st
  346. return &cp
  347. }
  348. // MatchRouter busca el agente asociado a un router: primero por slug exacto,
  349. // luego por hostname de board y finalmente por bridge MAC (#282). El match
  350. // por hostname/MAC usa la identidad retenida en el estado (#852), válida
  351. // aunque el último push sea wireless-only. Devuelve el slug real del
  352. // agente, su payload y si está fresco. Permite que un agente emparejado con
  353. // un slug elegido por el usuario alimente un router cuyo id autogenerado no
  354. // coincide con ese slug.
  355. func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (string, *probe.Payload, bool) {
  356. r.mu.Lock()
  357. defer r.mu.Unlock()
  358. norm := func(s string) string {
  359. return strings.ToLower(strings.TrimSpace(s))
  360. }
  361. hostNames := []string{}
  362. if cfg.Host != "" {
  363. hostNames = append(hostNames, norm(cfg.Host))
  364. }
  365. if cfg.Name != "" && norm(cfg.Name) != norm(cfg.Host) {
  366. hostNames = append(hostNames, norm(cfg.Name))
  367. }
  368. if cfg.ID != "" && norm(cfg.ID) != norm(cfg.Host) && norm(cfg.ID) != norm(cfg.Name) {
  369. hostNames = append(hostNames, norm(cfg.ID))
  370. }
  371. // #1334: la MAC de bridge persistida es la identidad física autoritativa
  372. // (los hostnames se duplican en APs puente idénticos). Se recogen TODOS
  373. // los candidatos por nivel y solo un match ÚNICO asocia: la ambigüedad no
  374. // inventa asociaciones (antes: primer match en orden aleatorio de mapa).
  375. targetMac := ""
  376. if macs != nil {
  377. targetMac = strings.ToUpper(strings.TrimSpace(macs[cfg.ID]))
  378. }
  379. var macMatch *AgentState
  380. var macMatchSlug string
  381. macMatchCount := 0
  382. var hostMatch *AgentState
  383. var hostMatchSlug string
  384. hostMatchCount := 0
  385. for slug, st := range r.states {
  386. if slug == cfg.ID {
  387. fresh := r.now().Sub(st.LastSeen) <= r.effectiveTTL(st)
  388. return slug, st.Payload, fresh
  389. }
  390. // #852: el match usa la identidad RETENIDA (Host/BridgeMAC), no la
  391. // del payload actual: el último push puede ser wireless-only (evento
  392. // nl80211, sin sección system) y aun así debe emparejar. Sin esto,
  393. // cada roam borraba la identidad hasta el próximo push completo.
  394. if st.Payload == nil {
  395. continue
  396. }
  397. if targetMac != "" && strings.EqualFold(st.BridgeMAC, targetMac) {
  398. macMatchCount++
  399. macMatch = st
  400. macMatchSlug = slug
  401. }
  402. if h := norm(st.Host); h != "" {
  403. for _, candidate := range hostNames {
  404. if h == candidate {
  405. hostMatchCount++
  406. hostMatch = st
  407. hostMatchSlug = slug
  408. break
  409. }
  410. }
  411. }
  412. }
  413. if macMatchCount == 1 {
  414. fresh := r.now().Sub(macMatch.LastSeen) <= r.effectiveTTL(macMatch)
  415. return macMatchSlug, macMatch.Payload, fresh
  416. }
  417. if macMatchCount > 1 {
  418. return "", nil, false
  419. }
  420. if hostMatchCount == 1 {
  421. fresh := r.now().Sub(hostMatch.LastSeen) <= r.effectiveTTL(hostMatch)
  422. return hostMatchSlug, hostMatch.Payload, fresh
  423. }
  424. return "", nil, false
  425. }
  426. // Forget borra el estado del slug (revocación de token).
  427. func (r *AgentRegistry) Forget(slug string) {
  428. r.mu.Lock()
  429. defer r.mu.Unlock()
  430. delete(r.states, slug)
  431. }
  432. // ---------------------------------------------------------------------------
  433. // Integración con Live
  434. // ---------------------------------------------------------------------------
  435. // SetAgents enchufa el registry de agentes al adapter live (nil = sin
  436. // soporte de agentes; todo va por SSH como antes).
  437. func (l *Live) SetAgents(r *AgentRegistry) {
  438. l.mu.Lock()
  439. l.agents = r
  440. l.mu.Unlock()
  441. }
  442. // SetAgentDownConfirm fija el periodo de confirmación del Dead Man's Switch
  443. // (P6): tiempo sin push tras el cual se confirma la caída de un agente.
  444. func (l *Live) SetAgentDownConfirm(d time.Duration) {
  445. l.mu.Lock()
  446. if d > 0 {
  447. l.agentDownConfirm = d
  448. }
  449. l.mu.Unlock()
  450. }
  451. // SetAgentLatestSource fija la fuente de la versión de referencia por kind
  452. // de agente (issue #400): native → binario embebido del server, netgrip →
  453. // última release pública de NetGrip, external → "" (nunca alerta). nil o
  454. // referencia vacía desactivan el check de agente desactualizado.
  455. func (l *Live) SetAgentLatestSource(fn func(kind string) string) {
  456. l.mu.Lock()
  457. l.agentLatest = fn
  458. l.mu.Unlock()
  459. }
  460. // agentName: nombre para las alertas (cfg.Name o Host como el resto).
  461. func agentName(cfg RouterConfig) string {
  462. if cfg.Name != "" {
  463. return cfg.Name
  464. }
  465. return cfg.Host
  466. }
  467. // pollRouterAgent: si un agente asociado al router está fresco, construye el
  468. // sondeo desde su payload (Tier 2). Si expiró, emite UNA vez la alerta de
  469. // caída y devuelve (false, nil) para que el caller siga por SSH (Tier 0).
  470. // El emparejamiento no exige slug == router.id: también usa hostname/MAC
  471. // (#282). Cuando el agente está vivo pero el SSH falla por clave no
  472. // autorizada, emite una alerta informativa en vez de dejar la tarjeta en
  473. // offline (#281).
  474. func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
  475. l.mu.Lock()
  476. reg := l.agents
  477. macs := make(map[string]string, len(l.routerMacs))
  478. for k, v := range l.routerMacs {
  479. macs[k] = v
  480. }
  481. l.mu.Unlock()
  482. if reg == nil {
  483. return false, nil
  484. }
  485. slug, p, fresh := reg.MatchRouter(cfg, macs)
  486. if fresh {
  487. // issue #400: versión del agente desactualizada (alerta consolidada).
  488. l.checkAgentVersion(cfg, p)
  489. l.mu.Lock()
  490. if l.agentDown[cfg.ID] {
  491. l.agentDown[cfg.ID] = false
  492. name := agentName(cfg)
  493. // #966: la alerta de caída es VOLÁTIL con ID estable por router:
  494. // al recuperarse el agente desaparece del feed (no acumula
  495. // historial). "Agente recuperado" SÍ persiste (registro positivo).
  496. l.engine.Remove("alert-agent-down-" + cfg.ID)
  497. l.engine.Emit(AlertEvent{
  498. ID: fmt.Sprintf("alert-agent-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
  499. Category: alerts.CatSystem, Urgent: false,
  500. Severity: "ok",
  501. Title: "Agent recovered on " + name,
  502. Description: fmt.Sprintf("The agent on %s is pushing data again - native polling resumed", name),
  503. Type: alerts.TypeAgentRecovered,
  504. Vars: map[string]string{"router": name},
  505. Time: "just now", RouterID: cfg.ID,
  506. })
  507. }
  508. // issue #281: SSH falla por clave no autorizada pero el agente sigue
  509. // vivo → avisa una sola vez. Se borra el flag cuando SSH vuelve.
  510. if l.lastErr[cfg.ID] != nil && isAccessError(l.lastErr[cfg.ID]) {
  511. if !l.sshAuthFailAlerted[cfg.ID] {
  512. l.sshAuthFailAlerted[cfg.ID] = true
  513. name := agentName(cfg)
  514. l.engine.Emit(AlertEvent{
  515. ID: fmt.Sprintf("alert-ssh-auth-%s-%d", cfg.ID, time.Now().UnixMilli()),
  516. Category: alerts.CatSystem, Urgent: false,
  517. Severity: "warn",
  518. Title: "SSH access lost on " + name,
  519. Description: fmt.Sprintf("%s does not accept the SSH key, but its agent keeps sending data. Check authorized_keys after a firmware upgrade.", name),
  520. Type: alerts.TypeSSHAccessLost,
  521. Vars: map[string]string{"router": name},
  522. Time: "just now", RouterID: cfg.ID,
  523. })
  524. }
  525. } else if l.sshAuthFailAlerted[cfg.ID] {
  526. delete(l.sshAuthFailAlerted, cfg.ID)
  527. name := agentName(cfg)
  528. l.engine.Emit(AlertEvent{
  529. ID: fmt.Sprintf("alert-ssh-auth-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
  530. Category: alerts.CatSystem, Urgent: false,
  531. Severity: "ok",
  532. Title: "SSH access recovered on " + name,
  533. Description: fmt.Sprintf("SSH access to %s is working again", name),
  534. Type: alerts.TypeSSHAccessRecovered,
  535. Vars: map[string]string{"router": name},
  536. Time: "just now", RouterID: cfg.ID,
  537. })
  538. }
  539. l.mu.Unlock()
  540. return true, l.polledFromAgent(cfg, p)
  541. }
  542. if slug != "" {
  543. // Dead Man's Switch (P6): el agente está stale, pero solo disparamos la
  544. // alerta de caída si lleva más de agentDownConfirm sin empujar. Entre
  545. // TTL y agentDownConfirm el router degrada a SSH silenciosamente.
  546. confirm := l.agentDownConfirm
  547. if confirm <= 0 {
  548. confirm = 3 * time.Minute
  549. }
  550. confirm = reg.ExternalDownConfirm(slug, confirm)
  551. if reg.StaleFor(slug, confirm) {
  552. l.mu.Lock()
  553. // #1917: en una unidad con inventory_mode "ssh" el agente no se
  554. // espera nunca, asi que su ausencia no es un evento: nada de
  555. // alerta, ni urgente ni warn.
  556. if !l.agentDown[cfg.ID] && cfg.InventoryMode != "ssh" {
  557. l.agentDown[cfg.ID] = true
  558. name := agentName(cfg)
  559. // #850: para routers agent-only el agente ES la única vía
  560. // de datos (el poll sirve el payload cacheado y el router
  561. // nunca marca offline): su caída es un evento de router
  562. // urgente, comparable al offline, para que pase los filtros
  563. // de notificación "solo urgentes del topic router". Con SSH
  564. // disponible se degrada con gracia y sigue siendo system.
  565. // #966: la alerta de caída es VOLÁTIL y con ID estable por
  566. // router (alert-agent-down-<id>): no se persiste en
  567. // alert_log, no sobrevive reinicios y al recuperarse el
  568. // agente desaparece del feed (engine.Remove arriba).
  569. if cfg.AgentOnly {
  570. l.engine.EmitVolatile(AlertEvent{
  571. ID: "alert-agent-down-" + cfg.ID,
  572. Category: alerts.CatRouter, Urgent: true,
  573. Severity: "critical",
  574. Title: fmt.Sprintf("Agent down on %s", name),
  575. Description: fmt.Sprintf("No data from the agent on %s for more than %s - using cached data", name, confirm),
  576. Hint: alerts.HintFor(alerts.HintAgentDown),
  577. Type: alerts.HintAgentDown,
  578. Vars: map[string]string{"router": name, "confirm": confirm.String()},
  579. Time: "just now", RouterID: cfg.ID,
  580. })
  581. } else {
  582. l.engine.EmitVolatile(AlertEvent{
  583. ID: "alert-agent-down-" + cfg.ID,
  584. Category: alerts.CatSystem, Urgent: false,
  585. Severity: "warn",
  586. Title: fmt.Sprintf("Agent down on %s - falling back to SSH", name),
  587. Description: fmt.Sprintf("No data from the agent on %s for more than %s - SSH polling resumed", name, confirm),
  588. Hint: alerts.HintFor(alerts.HintAgentDownSSH),
  589. Type: alerts.HintAgentDownSSH,
  590. Vars: map[string]string{"router": name, "confirm": confirm.String()},
  591. Time: "just now", RouterID: cfg.ID,
  592. })
  593. }
  594. }
  595. l.mu.Unlock()
  596. }
  597. if cfg.AgentOnly {
  598. if p != nil {
  599. rp := l.polledFromAgent(cfg, p)
  600. // #850 keeps serving cached data so the card never goes blank,
  601. // but a pusher dead past the down-confirm window is not
  602. // "online": flag it so buildRouter reads offline while keeping
  603. // the last readings. Same window as the agent-down alert, so
  604. // the status does not flap on a momentary blip.
  605. rp.agentStale = reg.StaleFor(slug, confirm)
  606. return true, rp
  607. }
  608. }
  609. }
  610. return false, nil
  611. }
  612. // agentIfSample: contadores por iface del último payload del agente (para
  613. // el delta de rates por boca, issue #305).
  614. type agentIfSample struct {
  615. at time.Time
  616. ifaces map[string]probe.IfCounters
  617. }
  618. // injectPortRates copia absolutos + rates de rates (keyed por iface física)
  619. // sobre las bocas: match por Iface si la boca la declara, si no por ID (en
  620. // DSA coinciden; en swconfig el ID es numérico y solo Iface casa).
  621. // appendVirtualPorts turns the interfaces NetIf carries that are not physical
  622. // ports into EthPorts, so the router page can list them with their traffic
  623. // (#1757). The agent path never built them: NetIf only fed the rates of the
  624. // physical ports. Up means "has carried traffic", because /proc/net/dev has no
  625. // link state and inventing one would be worse than saying nothing.
  626. func appendVirtualPorts(ports []EthPort, ifaces map[string]probe.IfCounters, rates map[string]probe.IfRate) []EthPort {
  627. if len(ifaces) == 0 {
  628. return ports
  629. }
  630. seen := make(map[string]bool, len(ports))
  631. for _, p := range ports {
  632. if p.Iface != "" {
  633. seen[p.Iface] = true
  634. }
  635. if p.ID != "" {
  636. seen[p.ID] = true
  637. }
  638. }
  639. names := make([]string, 0, len(ifaces))
  640. for name := range ifaces {
  641. if name == "lo" || seen[name] {
  642. continue
  643. }
  644. names = append(names, name)
  645. }
  646. if len(names) == 0 {
  647. return ports
  648. }
  649. sort.Strings(names)
  650. for _, name := range names {
  651. c := ifaces[name]
  652. p := EthPort{
  653. ID: "if-" + name,
  654. Label: name,
  655. Iface: name,
  656. Up: c.Rx+c.Tx > 0,
  657. Family: virtualIfaceFamily(name),
  658. RxBytes: c.Rx,
  659. TxBytes: c.Tx,
  660. RxErrs: c.RxErr,
  661. TxErrs: c.TxErr,
  662. }
  663. if r, ok := rates[name]; ok {
  664. if r.RxBps != nil {
  665. p.RxBps = *r.RxBps
  666. }
  667. if r.TxBps != nil {
  668. p.TxBps = *r.TxBps
  669. }
  670. }
  671. ports = append(ports, p)
  672. }
  673. return ports
  674. }
  675. // virtualIfaceFamily names the family the router page groups by, the same
  676. // values the SNMP path gets from ifType.
  677. func virtualIfaceFamily(name string) string {
  678. switch {
  679. case strings.Contains(name, "."), strings.HasPrefix(name, "vlan"):
  680. return "vlan"
  681. case strings.HasPrefix(name, "br"), name == "bridge":
  682. return "bridge"
  683. // #1757: las interfaces AP no tienen ifType en /proc/net/dev. En OpenWrt
  684. // son phy<N>-ap<N> (hostapd sobre mac80211) y en otras plataformas
  685. // wlan<N>: verlas como "virtual" a secas esconde que son el WiFi, que es
  686. // justo lo que se quiere leer por interfaz.
  687. case strings.HasPrefix(name, "phy") && strings.Contains(name, "-ap"),
  688. strings.HasPrefix(name, "wlan"):
  689. return "wifi"
  690. case strings.HasPrefix(name, "bond"), strings.HasPrefix(name, "lag"):
  691. return "lag"
  692. case strings.HasPrefix(name, "tun"), strings.HasPrefix(name, "tap"), strings.HasPrefix(name, "wg"),
  693. strings.HasPrefix(name, "pppoe"), strings.HasPrefix(name, "gre"), strings.HasPrefix(name, "sit"),
  694. strings.HasPrefix(name, "vti"), strings.HasPrefix(name, "ip6tnl"):
  695. return "tunnel"
  696. }
  697. return "virtual"
  698. }
  699. // linkPorts drops the interfaces that are not physical links: they have no
  700. // link state to watch, so the port monitor has nothing to say about them
  701. // (#1757).
  702. func linkPorts(ports []EthPort) []EthPort {
  703. n := 0
  704. for _, p := range ports {
  705. if p.Family != "" && p.Family != "ethernet" {
  706. n++
  707. }
  708. }
  709. if n == 0 {
  710. return ports
  711. }
  712. out := make([]EthPort, 0, len(ports)-n)
  713. for _, p := range ports {
  714. if p.Family != "" && p.Family != "ethernet" {
  715. continue
  716. }
  717. out = append(out, p)
  718. }
  719. return out
  720. }
  721. func injectPortRates(ports []EthPort, rates map[string]probe.IfRate) {
  722. for i := range ports {
  723. key := ports[i].Iface
  724. if key == "" {
  725. key = ports[i].ID
  726. }
  727. r, ok := rates[key]
  728. if !ok {
  729. continue
  730. }
  731. ports[i].Iface = key
  732. ports[i].RxBytes = r.Rx
  733. ports[i].TxBytes = r.Tx
  734. ports[i].RxErrs = r.RxErr
  735. ports[i].TxErrs = r.TxErr
  736. if r.RxBps != nil {
  737. ports[i].RxBps = *r.RxBps
  738. }
  739. if r.TxBps != nil {
  740. ports[i].TxBps = *r.TxBps
  741. }
  742. }
  743. }
  744. // agentSourceClass: la documentación de probe.Payload.Kind declara "" y
  745. // "native" como el mismo agente nativo, así que el cache de system los trata
  746. // como una sola fuente; cada kind restante (external, netgrip…) es la suya
  747. // propia.
  748. func agentSourceClass(kind string) string {
  749. if kind == "" || kind == "native" {
  750. return "native"
  751. }
  752. return kind
  753. }
  754. // isPusherType: tipos de router que no corren el agente nativo, así que su
  755. // push llega de un scraper o de una integración (#1871). "" se trata como
  756. // nativo para no inventar un kind cuando la fila no está cargada.
  757. func isPusherType(t string) bool {
  758. switch t {
  759. case "", "openwrt", "glinet":
  760. return false
  761. }
  762. return true
  763. }
  764. // portsCarryTraffic: el payload trae contadores o tasas por boca. Un beacon
  765. // solo publica estado de enlace y FDB, así que no entra (#1741).
  766. func portsCarryTraffic(ports []EthPort) bool {
  767. for _, p := range ports {
  768. if p.RxBytes > 0 || p.TxBytes > 0 || p.RxBps > 0 || p.TxBps > 0 {
  769. return true
  770. }
  771. }
  772. return false
  773. }
  774. // polledFromAgent convierte el payload del agente en el routerPolled del
  775. // pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
  776. // que pollRouter: sección ausente en el payload = sonda fallida → conserva
  777. // el último dato bueno cacheado.
  778. func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled {
  779. l.mu.Lock()
  780. cached := l.extrasCache[cfg.ID]
  781. l.mu.Unlock()
  782. out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}, polledAt: time.Now().UnixMilli()}
  783. // #441: conservar el kind del agente: los pushers externos (beacon/
  784. // scraper) no llevan sección system y el router queda sin vitals.
  785. out.agentKind = p.Kind
  786. // #1871: el kind del payload es opcional y las integraciones que empujan
  787. // no lo rellenan, pero el registro ya sabe que la unidad no corre el
  788. // agente nativo. Se sella en el polled y no en el payload a propósito:
  789. // checkAgentVersion y el cache anti-parpadeo leen p.Kind, y un agente
  790. // nativo en una fila external (migración 2.49.x) debe seguir comprobando
  791. // su versión y heredando sus propias vitals.
  792. if out.agentKind == "" && isPusherType(cfg.Type) {
  793. out.agentKind = "external"
  794. }
  795. // #832: el equipo se expone él mismo a Home Assistant por MQTT (NetGrip
  796. // con su MQTT activado); el publisher de flota cede el paso.
  797. out.selfExpose = p.Data.MQTT != nil && p.Data.MQTT.Enabled
  798. sysInfo := &SysInfo{}
  799. ramPct := 0
  800. if sd := p.Data.System; sd != nil {
  801. if sd.SysInfo != nil {
  802. sysInfo = sd.SysInfo
  803. out.hasUptime = true
  804. }
  805. out.board = sd.Board
  806. if sd.Board != nil {
  807. l.mu.Lock()
  808. l.boardCache[cfg.ID] = sd.Board
  809. l.mu.Unlock()
  810. }
  811. if sd.CPU != nil {
  812. out.cpu, out.hasCpu = *sd.CPU, true
  813. }
  814. if sd.Temp != nil {
  815. out.temp, out.hasTemp = *sd.Temp, true
  816. }
  817. out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
  818. out.latencyMs = sd.LatencyMs
  819. out.lossPct = sd.LossPct
  820. out.backhaul = sd.Backhaul
  821. out.brMac = sd.BridgeMAC
  822. // #1765: identidades propias del equipo. El agente manda las MACs de
  823. // todas sus interfaces; sin esto solo se absorbía la del bridge y el
  824. // resto (VLANs, puerto CPU de un switch DSA, radios) aparecía como
  825. // cliente desconocido cuando un vecino las aprendía en su FDB.
  826. out.selfMacs = sd.IfaceMACs
  827. out.flash = sd.Flash
  828. out.firmwareAvailable = sd.FirmwareAvailable
  829. } else if cached != nil && cached.system != nil && cached.systemKind == agentSourceClass(p.Kind) {
  830. // #441: push event-driven (wireless-only) sin system → conserva las
  831. // últimas vitals buenas cacheadas en vez de pintar ceros falsos.
  832. // Solo vitals/uptime: net/latencia/backhaul no se reciclan (evita
  833. // duplicar tráfico con muestras viejas).
  834. //
  835. // Solo dentro del mismo kind: extrasCache se clave únicamente por ID,
  836. // así que un payload external sin sección system heredaría las vitals
  837. // del agente nativo que alimentó al router antes. Como #1724 marca lo
  838. // que trae el payload de confirmado, esa herencia se publicaría como
  839. // lectura propia y acabaría en el histórico.
  840. sd := cached.system
  841. if sd.CPU != nil {
  842. out.cpu, out.hasCpu = *sd.CPU, true
  843. }
  844. if sd.Temp != nil {
  845. out.temp, out.hasTemp = *sd.Temp, true
  846. }
  847. if sd.SysInfo != nil {
  848. sysInfo = sd.SysInfo
  849. out.hasUptime = true
  850. }
  851. }
  852. mem := sysInfo.Memory
  853. // Con solo Mem.Total y ninguna cifra de uso no hay nada que derivar:
  854. // memUsagePct caería a "available = free + buffered = 0" y reportaría un
  855. // 100 % inventado. Eso es memoria desconocida, no memoria llena.
  856. if mem.Total > 0 && memUsageKnown(mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used) {
  857. ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
  858. // La memoria del payload es una lectura confirmada (los pushers de
  859. // RouterOS/AsusWRT la derivan de free/memory), no un hueco que haya
  860. // que pintar a cero.
  861. out.hasRam = true
  862. }
  863. out.sysInfo = sysInfo
  864. out.ram = ramPct
  865. out.uptimeSec = sysInfo.Uptime
  866. // Secciones con anti-parpadeo (nil en el payload = sonda fallida).
  867. if wd := p.Data.Wireless; wd != nil {
  868. if wd.Clients != nil {
  869. out.wireless = wd.Clients
  870. }
  871. if len(wd.Radios) > 0 {
  872. out.radios = radiosToAdapter(wd.Radios)
  873. }
  874. }
  875. if dd := p.Data.DHCP; dd != nil {
  876. out.leases = dd.Leases
  877. // gl-clients del agente (GL.iNet): enriquece IPs igual que en la
  878. // ruta SSH (issue #5 bug 1).
  879. out.glClients = dd.GlClients
  880. }
  881. if p.Data.Arp != nil {
  882. out.arp = p.Data.Arp
  883. out.arpDevs = p.Data.ArpDevs
  884. // An agent old enough not to send arpStale leaves this empty, and
  885. // the whole table counts as presence, exactly as it used to.
  886. out.arpStale = make(map[string]bool, len(p.Data.ArpStale))
  887. for _, mac := range p.Data.ArpStale {
  888. out.arpStale[strings.ToUpper(mac)] = true
  889. }
  890. }
  891. // Wan (#276): el agente lo trae en el payload desde 2.28.24+. Antes solo
  892. // existía la sonda SSH del server, que en un router agent_only no corre
  893. // nunca -- y su panel de conexión se quedaba vacío.
  894. if w := p.Data.Wan; w != nil {
  895. out.wanInfo = *w
  896. }
  897. // MultiWan: the several internet connections and which one carries
  898. // traffic. Only a router whose own panel manages them reports it; an
  899. // event-driven push carries no section, so the last good one is kept
  900. // or the panel would blink out between full pushes.
  901. out.multiWan = normalizeMultiWan(p.Data.MultiWan)
  902. if out.multiWan == nil && cached != nil {
  903. out.multiWan = cached.multiWan
  904. }
  905. // Vlans travel in the payload too, and were being dropped here: a
  906. // router polled through its agent never reached the SSH path that is
  907. // the only other place they are read, so its VLAN panel stayed empty.
  908. if len(p.Data.Vlans) > 0 {
  909. out.vlans = p.Data.Vlans
  910. } else if cached != nil {
  911. out.vlans = cached.vlans
  912. }
  913. // #1889: las redes UCI viajan en el mismo payload que las VLANs.
  914. if len(p.Data.Networks) > 0 {
  915. out.networks = p.Data.Networks
  916. } else if cached != nil {
  917. out.networks = cached.networks
  918. }
  919. // #1942: el mapa ifname -> red viaja en la seccion wireless del payload.
  920. if wm := wifiNetworkMap(dot11rIfacesFromPayload(p)); wm != nil {
  921. out.wifiNet = wm
  922. } else if cached != nil {
  923. out.wifiNet = cached.wifiNet
  924. }
  925. if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
  926. out.reservations = dh.Reservations
  927. }
  928. if fd := p.Data.FDB; fd != nil {
  929. if fd.MACs != nil {
  930. out.fdb = fd.MACs
  931. }
  932. // Sección FDB fresca: el hint wireless-side se pisa tal cual, incluso
  933. // vacío (nadie lo refresca ya: agente caído o pasado a SSH). Solo un
  934. // push SIN sección FDB (event-driven) recicla el cache, mismo contrato
  935. // anti-parpadeo que fdb.
  936. out.wirelessSide = fd.WirelessSide
  937. // #1757: VLAN real de cada cliente cableado, tal como el bridge la
  938. // aprendió. Se pisa tal cual (incluso vacío) por la misma razón que el
  939. // hint wireless-side: una sección fresca es la verdad del equipo.
  940. out.fdbVlans = fd.VLANs
  941. if len(fd.Ports) > 0 {
  942. out.ports = ethPortsToAdapter(fd.Ports)
  943. // #291: los pushers externos declaran el puerto del FDB como
  944. // número ("1") mientras sus bocas usan id "lan1". Normalizar
  945. // para que el enriquecimiento del detalle (MAC→nombre por boca)
  946. // y la topología casen ambas claves.
  947. ids := map[string]bool{}
  948. for _, ep := range out.ports {
  949. ids[ep.ID] = true
  950. }
  951. if len(ids) > 0 {
  952. for mac, port := range out.fdb {
  953. if port == "wan" || ids[port] {
  954. continue
  955. }
  956. if lan := "lan" + port; ids[lan] {
  957. out.fdb[mac] = lan
  958. }
  959. }
  960. }
  961. }
  962. }
  963. // LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de
  964. // topología. Best-effort: sección ausente → conserva la última buena.
  965. if p.Data.LuCI != nil {
  966. out.luci = p.Data.LuCI
  967. }
  968. // LLDP (#489): vecinos del payload del agente (antes solo llegaban por
  969. // la sonda SSH, muerta para routers con agente fresco). Resolución con
  970. // anti-parpadeo: manda la sección buena del payload; una sección
  971. // fallida (Available=true con Neighbors nil) o ausente (push
  972. // event-driven) recicla la última cacheada. Available=false explícito =
  973. // lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
  974. resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
  975. ld := p.Data.Lldp
  976. if ld == nil || (ld.Available && ld.Neighbors == nil) {
  977. ld = nil
  978. if cached != nil {
  979. ld = cached.lldp
  980. }
  981. }
  982. if ld == nil {
  983. return nil, false, ""
  984. }
  985. if !ld.Available {
  986. return nil, true, ""
  987. }
  988. return lldpFromProbe(ld.Neighbors), false, ld.Hint
  989. }
  990. out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
  991. // ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
  992. // LLDP: la sección buena del payload manda; una sección fallida
  993. // (Available=true con Hosts nil) o ausente (push event-driven) recicla
  994. // la última cacheada; Available=false explícito = nlbwmon no instalado
  995. // y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
  996. resolveClientBw := func() *probe.ClientBwData {
  997. cb := p.Data.ClientBw
  998. if cb == nil || (cb.Available && cb.Hosts == nil) {
  999. cb = nil
  1000. if cached != nil {
  1001. cb = cached.clientBw
  1002. }
  1003. }
  1004. if cb == nil || !cb.Available {
  1005. return nil
  1006. }
  1007. return cb
  1008. }
  1009. out.clientBw = resolveClientBw()
  1010. // Discovery (#338): mDNS services + randomized MACs. Best-effort.
  1011. if p.Data.Discovery != nil {
  1012. out.discovery = p.Data.Discovery
  1013. }
  1014. out.dawnDetected = p.Data.Dawn != nil
  1015. if cached == nil {
  1016. cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
  1017. wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
  1018. }
  1019. if out.ports == nil {
  1020. out.ports = cached.ports
  1021. }
  1022. if out.radios == nil {
  1023. out.radios = cached.radios
  1024. }
  1025. if out.wireless == nil {
  1026. out.wireless = cached.wireless
  1027. }
  1028. if out.fdb == nil {
  1029. out.fdb = cached.fdb
  1030. }
  1031. if out.wirelessSide == nil && p.Data.FDB == nil {
  1032. out.wirelessSide = cached.wirelessSide
  1033. }
  1034. if out.fdbVlans == nil && p.Data.FDB == nil {
  1035. out.fdbVlans = cached.fdbVlans
  1036. }
  1037. if out.luci == nil {
  1038. out.luci = cached.luci
  1039. }
  1040. // NetIf (issue #305): rates por boca con el delta entre payloads del
  1041. // agente. El payload trae contadores ABSOLUTOS por iface; el server
  1042. // calcula bps con la muestra anterior (ts del propio payload, no el
  1043. // reloj del server). Sección ausente → conserva los rates cacheados.
  1044. // Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
  1045. // snapshot para que el cache lleve los rates frescos.
  1046. if p.Data.NetIf != nil {
  1047. now := time.Unix(p.Ts, 0)
  1048. l.mu.Lock()
  1049. prev := l.lastAgentIf[cfg.ID]
  1050. l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
  1051. l.mu.Unlock()
  1052. var rates map[string]probe.IfRate
  1053. if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
  1054. rates = probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
  1055. injectPortRates(out.ports, rates)
  1056. }
  1057. // #1757: las interfaces que no son bocas físicas (vlan, bridge,
  1058. // bond, tun, wg) también cuentan. La página del router las lista
  1059. // aparte por su familia, con el tráfico que ya trae NetIf.
  1060. out.ports = appendVirtualPorts(out.ports, p.Data.NetIf, rates)
  1061. }
  1062. l.mu.Lock()
  1063. freshPayload := p.Ts != l.lastObsTs[cfg.ID]
  1064. if freshPayload {
  1065. l.lastObsTs[cfg.ID] = p.Ts
  1066. }
  1067. // #441: el cache de system guarda la última sección BUENA (un push
  1068. // wireless-only no la invalida).
  1069. sysSnap := p.Data.System
  1070. sysSnapKind := ""
  1071. if kind := agentSourceClass(p.Kind); sysSnap != nil {
  1072. sysSnapKind = kind
  1073. } else if cached != nil && cached.systemKind == kind {
  1074. sysSnap = cached.system
  1075. sysSnapKind = cached.systemKind
  1076. }
  1077. lldpSnap := p.Data.Lldp
  1078. if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
  1079. lldpSnap = cached.lldp // conserva la última sección buena (#489)
  1080. }
  1081. l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
  1082. wireless: out.wireless, fdb: out.fdb, fdbVlans: out.fdbVlans, networks: out.networks, wifiNet: out.wifiNet, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
  1083. clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
  1084. l.mu.Unlock()
  1085. // Solo con un payload NUEVO alimentamos las series y el monitor de
  1086. // puertos (issue #365): entre pushes, cada rebuild del overview vuelve
  1087. // por aquí con el MISMO payload cacheado, y re-observar contadores
  1088. // congelados dispara alertas fantasma ("zero bytes" que solo es espera
  1089. // del siguiente push).
  1090. if freshPayload {
  1091. // Los pushers external/beacon persisten sus propias series con
  1092. // contadores de tramas en recordBeaconPortSamples (httpapi/beacon.go)
  1093. // y sus EthPort no llevan contadores, así que pasar por
  1094. // recordPortSamples escribiría filas a 0 intercaladas con las buenas.
  1095. // #1741: un pusher que sí manda contadores o tasas por boca
  1096. // (RouterOS/AsusWRT) es una fuente válida y sin estas muestras su
  1097. // línea de 24 h no tiene de dónde salir, así que la puerta mira el
  1098. // dato, no el kind.
  1099. if out.agentKind != "external" || portsCarryTraffic(out.ports) {
  1100. l.recordPortSamples(cfg.ID, out.ports)
  1101. }
  1102. // #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
  1103. // now = ts del payload (no el reloj del server) para que el dt del
  1104. // delta sea el intervalo real entre pushes del agente.
  1105. if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
  1106. l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
  1107. }
  1108. l.portMon.Observe(cfg.ID, linkPorts(out.ports), l.engine)
  1109. }
  1110. if out.leases == nil {
  1111. out.leases = []DhcpLease{}
  1112. }
  1113. // #1818: el FDB de un bridge con batman-adv aprende las tramas LOOP
  1114. // DETECT (BA:BE:xx:xx:xx:xx). Fuera antes de que el FDB alimente clientes,
  1115. // topología o hints de rack.
  1116. out.fdb = withoutBatadvBla(out.fdb)
  1117. return out
  1118. }
  1119. // checkAgentVersion (issue #400): alerta consolidada (no urgente, sistema)
  1120. // cuando el agente fresh del router empuja una versión anterior a la de
  1121. // referencia de su kind: native → binario de agente embebido en el server,
  1122. // netgrip → última release pública de NetGrip, external → sin check. Al
  1123. // volver a estar al día emite UNA alerta ok de recuperación (patrón
  1124. // consolidación de portmonitor, issue #366).
  1125. func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
  1126. l.mu.Lock()
  1127. src := l.agentLatest
  1128. l.mu.Unlock()
  1129. if src == nil || p == nil || p.Version == "" || p.Kind == "external" {
  1130. return
  1131. }
  1132. ref := src(p.Kind)
  1133. if ref == "" {
  1134. return
  1135. }
  1136. name := agentName(cfg)
  1137. kindLabel := "NetPulse"
  1138. if p.Kind == "netgrip" {
  1139. kindLabel = "NetGrip"
  1140. }
  1141. l.mu.Lock()
  1142. alerted := l.agentOutdatedAlerted[cfg.ID]
  1143. l.mu.Unlock()
  1144. if vercmp.Cmp(ref, p.Version) > 0 {
  1145. if !alerted {
  1146. l.mu.Lock()
  1147. l.agentOutdatedAlerted[cfg.ID] = true
  1148. l.mu.Unlock()
  1149. }
  1150. // #910: EmitOrUpdate notifica en cada actualización en sitio; sin
  1151. // este guard, cada push del agente (30 s) reenviaba la notificación
  1152. // push y refrescaba el timestamp de la alerta. Solo se emite cuando
  1153. // la versión observada o la de referencia cambian.
  1154. key := p.Version + "|" + ref
  1155. l.mu.Lock()
  1156. unchanged := l.agentOutdatedKey[cfg.ID] == key
  1157. if !unchanged {
  1158. l.agentOutdatedKey[cfg.ID] = key
  1159. }
  1160. l.mu.Unlock()
  1161. if unchanged {
  1162. return
  1163. }
  1164. l.engine.EmitOrUpdate(AlertEvent{
  1165. ID: fmt.Sprintf("alert-agent-outdated-%s", cfg.ID),
  1166. Category: alerts.CatSystem, Urgent: false,
  1167. Severity: "warn",
  1168. Title: "Agent outdated on " + name,
  1169. Description: fmt.Sprintf("%s pushes version %s; the latest available for the %s agent is %s", name, p.Version, kindLabel, ref),
  1170. Hint: alerts.HintFor(alerts.HintAgentOutdated),
  1171. Type: alerts.HintAgentOutdated,
  1172. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
  1173. Time: "just now", RouterID: cfg.ID,
  1174. })
  1175. } else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
  1176. l.mu.Lock()
  1177. delete(l.agentOutdatedAlerted, cfg.ID)
  1178. l.mu.Unlock()
  1179. // #833: la alerta de desactualizado DESAPARECE del feed al
  1180. // actualizarse el agente (además del aviso ok de recuperación, que
  1181. // solo se emite cuando el flag en memoria estaba activo).
  1182. l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
  1183. l.mu.Lock()
  1184. delete(l.agentOutdatedKey, cfg.ID)
  1185. l.mu.Unlock()
  1186. if alerted {
  1187. l.engine.Emit(AlertEvent{
  1188. ID: fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
  1189. Category: alerts.CatSystem, Urgent: false,
  1190. Severity: "ok",
  1191. Title: "Agent updated on " + name,
  1192. Description: fmt.Sprintf("%s now pushes version %s of %s", name, p.Version, kindLabel),
  1193. Type: alerts.TypeAgentUpdated,
  1194. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
  1195. // #1349: el evento de cierre referencia al que resuelve
  1196. // (conservado en el log marcado, no borrado).
  1197. Resolves: []string{fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)},
  1198. Time: "just now", RouterID: cfg.ID,
  1199. })
  1200. }
  1201. }
  1202. }