agent.go 43 KB

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