agent.go 45 KB

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