agent.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. }
  901. // MultiWan: the several internet connections and which one carries
  902. // traffic. Only a router whose own panel manages them reports it; an
  903. // event-driven push carries no section, so the last good one is kept
  904. // or the panel would blink out between full pushes.
  905. out.multiWan = normalizeMultiWan(p.Data.MultiWan)
  906. if out.multiWan == nil && cached != nil {
  907. out.multiWan = cached.multiWan
  908. }
  909. // Vlans travel in the payload too, and were being dropped here: a
  910. // router polled through its agent never reached the SSH path that is
  911. // the only other place they are read, so its VLAN panel stayed empty.
  912. if len(p.Data.Vlans) > 0 {
  913. out.vlans = p.Data.Vlans
  914. } else if cached != nil {
  915. out.vlans = cached.vlans
  916. }
  917. // #1889: las redes UCI viajan en el mismo payload que las VLANs.
  918. if len(p.Data.Networks) > 0 {
  919. out.networks = p.Data.Networks
  920. } else if cached != nil {
  921. out.networks = cached.networks
  922. }
  923. // #1942: el mapa ifname -> red viaja en la seccion wireless del payload.
  924. if wm := wifiNetworkMap(dot11rIfacesFromPayload(p)); wm != nil {
  925. out.wifiNet = wm
  926. } else if cached != nil {
  927. out.wifiNet = cached.wifiNet
  928. }
  929. if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
  930. out.reservations = dh.Reservations
  931. }
  932. if fd := p.Data.FDB; fd != nil {
  933. if fd.MACs != nil {
  934. out.fdb = fd.MACs
  935. }
  936. // Sección FDB fresca: el hint wireless-side se pisa tal cual, incluso
  937. // vacío (nadie lo refresca ya: agente caído o pasado a SSH). Solo un
  938. // push SIN sección FDB (event-driven) recicla el cache, mismo contrato
  939. // anti-parpadeo que fdb.
  940. out.wirelessSide = fd.WirelessSide
  941. // #1757: VLAN real de cada cliente cableado, tal como el bridge la
  942. // aprendió. Se pisa tal cual (incluso vacío) por la misma razón que el
  943. // hint wireless-side: una sección fresca es la verdad del equipo.
  944. out.fdbVlans = fd.VLANs
  945. if len(fd.Ports) > 0 {
  946. out.ports = ethPortsToAdapter(fd.Ports)
  947. // #291: los pushers externos declaran el puerto del FDB como
  948. // número ("1") mientras sus bocas usan id "lan1". Normalizar
  949. // para que el enriquecimiento del detalle (MAC→nombre por boca)
  950. // y la topología casen ambas claves.
  951. // fd.MACs es el mapa del payload publicado en AgentRegistry, que
  952. // otras goroutines leen (persistAgentState, el beacon periódico):
  953. // se reescribe sobre una copia, hecha solo si hay algo que cambiar.
  954. ids := map[string]bool{}
  955. for _, ep := range out.ports {
  956. ids[ep.ID] = true
  957. }
  958. if len(ids) > 0 {
  959. copied := false
  960. for mac, port := range fd.MACs {
  961. if port == "wan" || ids[port] {
  962. continue
  963. }
  964. if lan := "lan" + port; ids[lan] {
  965. if !copied {
  966. out.fdb = maps.Clone(fd.MACs)
  967. copied = true
  968. }
  969. out.fdb[mac] = lan
  970. }
  971. }
  972. }
  973. }
  974. }
  975. // LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de
  976. // topología. Best-effort: sección ausente → conserva la última buena.
  977. if p.Data.LuCI != nil {
  978. out.luci = p.Data.LuCI
  979. }
  980. // LLDP (#489): vecinos del payload del agente (antes solo llegaban por
  981. // la sonda SSH, muerta para routers con agente fresco). Resolución con
  982. // anti-parpadeo: manda la sección buena del payload; una sección
  983. // fallida (Available=true con Neighbors nil) o ausente (push
  984. // event-driven) recicla la última cacheada. Available=false explícito =
  985. // lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
  986. resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
  987. ld := p.Data.Lldp
  988. if ld == nil || (ld.Available && ld.Neighbors == nil) {
  989. ld = nil
  990. if cached != nil {
  991. ld = cached.lldp
  992. }
  993. }
  994. if ld == nil {
  995. return nil, false, ""
  996. }
  997. if !ld.Available {
  998. return nil, true, ""
  999. }
  1000. return lldpFromProbe(ld.Neighbors), false, ld.Hint
  1001. }
  1002. out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
  1003. // ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
  1004. // LLDP: la sección buena del payload manda; una sección fallida
  1005. // (Available=true con Hosts nil) o ausente (push event-driven) recicla
  1006. // la última cacheada; Available=false explícito = nlbwmon no instalado
  1007. // y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
  1008. resolveClientBw := func() *probe.ClientBwData {
  1009. cb := p.Data.ClientBw
  1010. if cb == nil || (cb.Available && cb.Hosts == nil) {
  1011. cb = nil
  1012. if cached != nil {
  1013. cb = cached.clientBw
  1014. }
  1015. }
  1016. if cb == nil || !cb.Available {
  1017. return nil
  1018. }
  1019. return cb
  1020. }
  1021. out.clientBw = resolveClientBw()
  1022. // Discovery (#338): mDNS services + randomized MACs. Best-effort.
  1023. if p.Data.Discovery != nil {
  1024. out.discovery = p.Data.Discovery
  1025. }
  1026. out.dawnDetected = p.Data.Dawn != nil
  1027. if cached == nil {
  1028. cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
  1029. wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
  1030. }
  1031. if out.ports == nil {
  1032. // Copia: cached.ports es el slice de un routerPolled ya publicado en
  1033. // lastPolled, e injectPortRates/appendVirtualPorts escriben en él. La
  1034. // copia es segura porque solo buildOverview llega aquí y el singleflight
  1035. // de GetOverview no deja que dos builds se solapen: applySNMPSurface, que
  1036. // escribe en el slice cacheado, ya terminó en el build anterior.
  1037. out.ports = slices.Clone(cached.ports)
  1038. }
  1039. if out.radios == nil {
  1040. out.radios = cached.radios
  1041. }
  1042. if out.wireless == nil {
  1043. out.wireless = cached.wireless
  1044. }
  1045. if out.fdb == nil {
  1046. out.fdb = cached.fdb
  1047. }
  1048. if out.wirelessSide == nil && p.Data.FDB == nil {
  1049. out.wirelessSide = cached.wirelessSide
  1050. }
  1051. if out.fdbVlans == nil && p.Data.FDB == nil {
  1052. out.fdbVlans = cached.fdbVlans
  1053. }
  1054. if out.luci == nil {
  1055. out.luci = cached.luci
  1056. }
  1057. // NetIf (issue #305): rates por boca con el delta entre payloads del
  1058. // agente. El payload trae contadores ABSOLUTOS por iface; el server
  1059. // calcula bps con la muestra anterior (ts del propio payload, no el
  1060. // reloj del server). Sección ausente → conserva los rates cacheados.
  1061. // Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
  1062. // snapshot para que el cache lleve los rates frescos.
  1063. if p.Data.NetIf != nil {
  1064. now := time.Unix(p.Ts, 0)
  1065. l.mu.Lock()
  1066. prev := l.lastAgentIf[cfg.ID]
  1067. l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
  1068. l.mu.Unlock()
  1069. var rates map[string]probe.IfRate
  1070. if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
  1071. rates = probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
  1072. injectPortRates(out.ports, rates)
  1073. }
  1074. // #1757: las interfaces que no son bocas físicas (vlan, bridge,
  1075. // bond, tun, wg) también cuentan. La página del router las lista
  1076. // aparte por su familia, con el tráfico que ya trae NetIf.
  1077. out.ports = appendVirtualPorts(out.ports, p.Data.NetIf, rates)
  1078. }
  1079. l.mu.Lock()
  1080. freshPayload := p.Ts != l.lastObsTs[cfg.ID]
  1081. if freshPayload {
  1082. l.lastObsTs[cfg.ID] = p.Ts
  1083. }
  1084. // #441: el cache de system guarda la última sección BUENA (un push
  1085. // wireless-only no la invalida).
  1086. sysSnap := p.Data.System
  1087. sysSnapKind := ""
  1088. if kind := agentSourceClass(p.Kind); sysSnap != nil {
  1089. sysSnapKind = kind
  1090. } else if cached != nil && cached.systemKind == kind {
  1091. sysSnap = cached.system
  1092. sysSnapKind = cached.systemKind
  1093. }
  1094. lldpSnap := p.Data.Lldp
  1095. if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
  1096. lldpSnap = cached.lldp // conserva la última sección buena (#489)
  1097. }
  1098. l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
  1099. 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,
  1100. clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
  1101. l.mu.Unlock()
  1102. // Solo con un payload NUEVO alimentamos las series y el monitor de
  1103. // puertos (issue #365): entre pushes, cada rebuild del overview vuelve
  1104. // por aquí con el MISMO payload cacheado, y re-observar contadores
  1105. // congelados dispara alertas fantasma ("zero bytes" que solo es espera
  1106. // del siguiente push).
  1107. if freshPayload {
  1108. // Los pushers external/beacon persisten sus propias series con
  1109. // contadores de tramas en recordBeaconPortSamples (httpapi/beacon.go)
  1110. // y sus EthPort no llevan contadores, así que pasar por
  1111. // recordPortSamples escribiría filas a 0 intercaladas con las buenas.
  1112. // #1741: un pusher que sí manda contadores o tasas por boca
  1113. // (RouterOS/AsusWRT) es una fuente válida y sin estas muestras su
  1114. // línea de 24 h no tiene de dónde salir, así que la puerta mira el
  1115. // dato, no el kind.
  1116. if out.agentKind != "external" || portsCarryTraffic(out.ports) {
  1117. l.recordPortSamples(cfg.ID, out.ports)
  1118. }
  1119. // #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
  1120. // now = ts del payload (no el reloj del server) para que el dt del
  1121. // delta sea el intervalo real entre pushes del agente.
  1122. if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
  1123. l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
  1124. }
  1125. l.portMon.Observe(cfg.ID, linkPorts(out.ports), l.engine)
  1126. }
  1127. if out.leases == nil {
  1128. out.leases = []DhcpLease{}
  1129. }
  1130. // #1818: el FDB de un bridge con batman-adv aprende las tramas LOOP
  1131. // DETECT (BA:BE:xx:xx:xx:xx). Fuera antes de que el FDB alimente clientes,
  1132. // topología o hints de rack.
  1133. out.fdb = withoutBatadvBla(out.fdb)
  1134. return out
  1135. }
  1136. // checkAgentVersion (issue #400): alerta consolidada (no urgente, sistema)
  1137. // cuando el agente fresh del router empuja una versión anterior a la de
  1138. // referencia de su kind: native → binario de agente embebido en el server,
  1139. // netgrip → última release pública de NetGrip, external → sin check. Al
  1140. // volver a estar al día emite UNA alerta ok de recuperación (patrón
  1141. // consolidación de portmonitor, issue #366).
  1142. func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
  1143. l.mu.Lock()
  1144. src := l.agentLatest
  1145. l.mu.Unlock()
  1146. if src == nil || p == nil || p.Version == "" || p.Kind == "external" {
  1147. return
  1148. }
  1149. ref := src(p.Kind)
  1150. if ref == "" {
  1151. return
  1152. }
  1153. name := agentName(cfg)
  1154. kindLabel := "NetPulse"
  1155. if p.Kind == "netgrip" {
  1156. kindLabel = "NetGrip"
  1157. }
  1158. l.mu.Lock()
  1159. alerted := l.agentOutdatedAlerted[cfg.ID]
  1160. l.mu.Unlock()
  1161. if vercmp.Cmp(ref, p.Version) > 0 {
  1162. if !alerted {
  1163. l.mu.Lock()
  1164. l.agentOutdatedAlerted[cfg.ID] = true
  1165. l.mu.Unlock()
  1166. }
  1167. // #910: EmitOrUpdate notifica en cada actualización en sitio; sin
  1168. // este guard, cada push del agente (30 s) reenviaba la notificación
  1169. // push y refrescaba el timestamp de la alerta. Solo se emite cuando
  1170. // la versión observada o la de referencia cambian.
  1171. key := p.Version + "|" + ref
  1172. l.mu.Lock()
  1173. unchanged := l.agentOutdatedKey[cfg.ID] == key
  1174. if !unchanged {
  1175. l.agentOutdatedKey[cfg.ID] = key
  1176. }
  1177. l.mu.Unlock()
  1178. if unchanged {
  1179. return
  1180. }
  1181. l.engine.EmitOrUpdate(AlertEvent{
  1182. ID: fmt.Sprintf("alert-agent-outdated-%s", cfg.ID),
  1183. Category: alerts.CatSystem, Urgent: false,
  1184. Severity: "warn",
  1185. Title: "Agent outdated on " + name,
  1186. Description: fmt.Sprintf("%s pushes version %s; the latest available for the %s agent is %s", name, p.Version, kindLabel, ref),
  1187. Hint: alerts.HintFor(alerts.HintAgentOutdated),
  1188. Type: alerts.HintAgentOutdated,
  1189. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
  1190. Time: "just now", RouterID: cfg.ID,
  1191. })
  1192. } else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
  1193. l.mu.Lock()
  1194. delete(l.agentOutdatedAlerted, cfg.ID)
  1195. l.mu.Unlock()
  1196. // #833: la alerta de desactualizado DESAPARECE del feed al
  1197. // actualizarse el agente (además del aviso ok de recuperación, que
  1198. // solo se emite cuando el flag en memoria estaba activo).
  1199. l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
  1200. l.mu.Lock()
  1201. delete(l.agentOutdatedKey, cfg.ID)
  1202. l.mu.Unlock()
  1203. if alerted {
  1204. l.engine.Emit(AlertEvent{
  1205. ID: fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
  1206. Category: alerts.CatSystem, Urgent: false,
  1207. Severity: "ok",
  1208. Title: "Agent updated on " + name,
  1209. Description: fmt.Sprintf("%s now pushes version %s of %s", name, p.Version, kindLabel),
  1210. Type: alerts.TypeAgentUpdated,
  1211. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
  1212. // #1349: el evento de cierre referencia al que resuelve
  1213. // (conservado en el log marcado, no borrado).
  1214. Resolves: []string{fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)},
  1215. Time: "just now", RouterID: cfg.ID,
  1216. })
  1217. }
  1218. }
  1219. }