agent.go 42 KB

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