agent.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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. out.hasUptime = true
  794. }
  795. out.board = sd.Board
  796. if sd.Board != nil {
  797. l.mu.Lock()
  798. l.boardCache[cfg.ID] = sd.Board
  799. l.mu.Unlock()
  800. }
  801. if sd.CPU != nil {
  802. out.cpu, out.hasCpu = *sd.CPU, true
  803. }
  804. if sd.Temp != nil {
  805. out.temp, out.hasTemp = *sd.Temp, true
  806. }
  807. out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
  808. out.latencyMs = sd.LatencyMs
  809. out.lossPct = sd.LossPct
  810. out.backhaul = sd.Backhaul
  811. out.brMac = sd.BridgeMAC
  812. // #1765: identidades propias del equipo. El agente manda las MACs de
  813. // todas sus interfaces; sin esto solo se absorbía la del bridge y el
  814. // resto (VLANs, puerto CPU de un switch DSA, radios) aparecía como
  815. // cliente desconocido cuando un vecino las aprendía en su FDB.
  816. out.selfMacs = sd.IfaceMACs
  817. out.flash = sd.Flash
  818. out.firmwareAvailable = sd.FirmwareAvailable
  819. } else if cached != nil && cached.system != nil && cached.systemKind == agentSourceClass(p.Kind) {
  820. // #441: push event-driven (wireless-only) sin system → conserva las
  821. // últimas vitals buenas cacheadas en vez de pintar ceros falsos.
  822. // Solo vitals/uptime: net/latencia/backhaul no se reciclan (evita
  823. // duplicar tráfico con muestras viejas).
  824. //
  825. // Solo dentro del mismo kind: extrasCache se clave únicamente por ID,
  826. // así que un payload external sin sección system heredaría las vitals
  827. // del agente nativo que alimentó al router antes. Como #1724 marca lo
  828. // que trae el payload de confirmado, esa herencia se publicaría como
  829. // lectura propia y acabaría en el histórico.
  830. sd := cached.system
  831. if sd.CPU != nil {
  832. out.cpu, out.hasCpu = *sd.CPU, true
  833. }
  834. if sd.Temp != nil {
  835. out.temp, out.hasTemp = *sd.Temp, true
  836. }
  837. if sd.SysInfo != nil {
  838. sysInfo = sd.SysInfo
  839. out.hasUptime = true
  840. }
  841. }
  842. mem := sysInfo.Memory
  843. // Con solo Mem.Total y ninguna cifra de uso no hay nada que derivar:
  844. // memUsagePct caería a "available = free + buffered = 0" y reportaría un
  845. // 100 % inventado. Eso es memoria desconocida, no memoria llena.
  846. if mem.Total > 0 && memUsageKnown(mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used) {
  847. ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
  848. // La memoria del payload es una lectura confirmada (los pushers de
  849. // RouterOS/AsusWRT la derivan de free/memory), no un hueco que haya
  850. // que pintar a cero.
  851. out.hasRam = true
  852. }
  853. out.sysInfo = sysInfo
  854. out.ram = ramPct
  855. out.uptimeSec = sysInfo.Uptime
  856. // Secciones con anti-parpadeo (nil en el payload = sonda fallida).
  857. if wd := p.Data.Wireless; wd != nil {
  858. if wd.Clients != nil {
  859. out.wireless = wd.Clients
  860. }
  861. if len(wd.Radios) > 0 {
  862. out.radios = radiosToAdapter(wd.Radios)
  863. }
  864. }
  865. if dd := p.Data.DHCP; dd != nil {
  866. out.leases = dd.Leases
  867. // gl-clients del agente (GL.iNet): enriquece IPs igual que en la
  868. // ruta SSH (issue #5 bug 1).
  869. out.glClients = dd.GlClients
  870. }
  871. if p.Data.Arp != nil {
  872. out.arp = p.Data.Arp
  873. out.arpDevs = p.Data.ArpDevs
  874. // An agent old enough not to send arpStale leaves this empty, and
  875. // the whole table counts as presence, exactly as it used to.
  876. out.arpStale = make(map[string]bool, len(p.Data.ArpStale))
  877. for _, mac := range p.Data.ArpStale {
  878. out.arpStale[strings.ToUpper(mac)] = true
  879. }
  880. }
  881. // Wan (#276): el agente lo trae en el payload desde 2.28.24+. Antes solo
  882. // existía la sonda SSH del server, que en un router agent_only no corre
  883. // nunca -- y su panel de conexión se quedaba vacío.
  884. if w := p.Data.Wan; w != nil {
  885. out.wanInfo = *w
  886. }
  887. // MultiWan: the several internet connections and which one carries
  888. // traffic. Only a router whose own panel manages them reports it; an
  889. // event-driven push carries no section, so the last good one is kept
  890. // or the panel would blink out between full pushes.
  891. out.multiWan = normalizeMultiWan(p.Data.MultiWan)
  892. if out.multiWan == nil && cached != nil {
  893. out.multiWan = cached.multiWan
  894. }
  895. // Vlans travel in the payload too, and were being dropped here: a
  896. // router polled through its agent never reached the SSH path that is
  897. // the only other place they are read, so its VLAN panel stayed empty.
  898. if len(p.Data.Vlans) > 0 {
  899. out.vlans = p.Data.Vlans
  900. } else if cached != nil {
  901. out.vlans = cached.vlans
  902. }
  903. // #1889: las redes UCI viajan en el mismo payload que las VLANs.
  904. if len(p.Data.Networks) > 0 {
  905. out.networks = p.Data.Networks
  906. } else if cached != nil {
  907. out.networks = cached.networks
  908. }
  909. // #1942: el mapa ifname -> red viaja en la seccion wireless del payload.
  910. if wm := wifiNetworkMap(dot11rIfacesFromPayload(p)); wm != nil {
  911. out.wifiNet = wm
  912. } else if cached != nil {
  913. out.wifiNet = cached.wifiNet
  914. }
  915. if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
  916. out.reservations = dh.Reservations
  917. }
  918. if fd := p.Data.FDB; fd != nil {
  919. if fd.MACs != nil {
  920. out.fdb = fd.MACs
  921. }
  922. // Sección FDB fresca: el hint wireless-side se pisa tal cual, incluso
  923. // vacío (nadie lo refresca ya: agente caído o pasado a SSH). Solo un
  924. // push SIN sección FDB (event-driven) recicla el cache, mismo contrato
  925. // anti-parpadeo que fdb.
  926. out.wirelessSide = fd.WirelessSide
  927. // #1757: VLAN real de cada cliente cableado, tal como el bridge la
  928. // aprendió. Se pisa tal cual (incluso vacío) por la misma razón que el
  929. // hint wireless-side: una sección fresca es la verdad del equipo.
  930. out.fdbVlans = fd.VLANs
  931. if len(fd.Ports) > 0 {
  932. out.ports = ethPortsToAdapter(fd.Ports)
  933. // #291: los pushers externos declaran el puerto del FDB como
  934. // número ("1") mientras sus bocas usan id "lan1". Normalizar
  935. // para que el enriquecimiento del detalle (MAC→nombre por boca)
  936. // y la topología casen ambas claves.
  937. ids := map[string]bool{}
  938. for _, ep := range out.ports {
  939. ids[ep.ID] = true
  940. }
  941. if len(ids) > 0 {
  942. for mac, port := range out.fdb {
  943. if port == "wan" || ids[port] {
  944. continue
  945. }
  946. if lan := "lan" + port; ids[lan] {
  947. out.fdb[mac] = lan
  948. }
  949. }
  950. }
  951. }
  952. }
  953. // LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de
  954. // topología. Best-effort: sección ausente → conserva la última buena.
  955. if p.Data.LuCI != nil {
  956. out.luci = p.Data.LuCI
  957. }
  958. // LLDP (#489): vecinos del payload del agente (antes solo llegaban por
  959. // la sonda SSH, muerta para routers con agente fresco). Resolución con
  960. // anti-parpadeo: manda la sección buena del payload; una sección
  961. // fallida (Available=true con Neighbors nil) o ausente (push
  962. // event-driven) recicla la última cacheada. Available=false explícito =
  963. // lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
  964. resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
  965. ld := p.Data.Lldp
  966. if ld == nil || (ld.Available && ld.Neighbors == nil) {
  967. ld = nil
  968. if cached != nil {
  969. ld = cached.lldp
  970. }
  971. }
  972. if ld == nil {
  973. return nil, false, ""
  974. }
  975. if !ld.Available {
  976. return nil, true, ""
  977. }
  978. return lldpFromProbe(ld.Neighbors), false, ld.Hint
  979. }
  980. out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
  981. // ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
  982. // LLDP: la sección buena del payload manda; una sección fallida
  983. // (Available=true con Hosts nil) o ausente (push event-driven) recicla
  984. // la última cacheada; Available=false explícito = nlbwmon no instalado
  985. // y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
  986. resolveClientBw := func() *probe.ClientBwData {
  987. cb := p.Data.ClientBw
  988. if cb == nil || (cb.Available && cb.Hosts == nil) {
  989. cb = nil
  990. if cached != nil {
  991. cb = cached.clientBw
  992. }
  993. }
  994. if cb == nil || !cb.Available {
  995. return nil
  996. }
  997. return cb
  998. }
  999. out.clientBw = resolveClientBw()
  1000. // Discovery (#338): mDNS services + randomized MACs. Best-effort.
  1001. if p.Data.Discovery != nil {
  1002. out.discovery = p.Data.Discovery
  1003. }
  1004. out.dawnDetected = p.Data.Dawn != nil
  1005. if cached == nil {
  1006. cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
  1007. wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
  1008. }
  1009. if out.ports == nil {
  1010. out.ports = cached.ports
  1011. }
  1012. if out.radios == nil {
  1013. out.radios = cached.radios
  1014. }
  1015. if out.wireless == nil {
  1016. out.wireless = cached.wireless
  1017. }
  1018. if out.fdb == nil {
  1019. out.fdb = cached.fdb
  1020. }
  1021. if out.wirelessSide == nil && p.Data.FDB == nil {
  1022. out.wirelessSide = cached.wirelessSide
  1023. }
  1024. if out.fdbVlans == nil && p.Data.FDB == nil {
  1025. out.fdbVlans = cached.fdbVlans
  1026. }
  1027. if out.luci == nil {
  1028. out.luci = cached.luci
  1029. }
  1030. // NetIf (issue #305): rates por boca con el delta entre payloads del
  1031. // agente. El payload trae contadores ABSOLUTOS por iface; el server
  1032. // calcula bps con la muestra anterior (ts del propio payload, no el
  1033. // reloj del server). Sección ausente → conserva los rates cacheados.
  1034. // Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
  1035. // snapshot para que el cache lleve los rates frescos.
  1036. if p.Data.NetIf != nil {
  1037. now := time.Unix(p.Ts, 0)
  1038. l.mu.Lock()
  1039. prev := l.lastAgentIf[cfg.ID]
  1040. l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
  1041. l.mu.Unlock()
  1042. var rates map[string]probe.IfRate
  1043. if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
  1044. rates = probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
  1045. injectPortRates(out.ports, rates)
  1046. }
  1047. // #1757: las interfaces que no son bocas físicas (vlan, bridge,
  1048. // bond, tun, wg) también cuentan. La página del router las lista
  1049. // aparte por su familia, con el tráfico que ya trae NetIf.
  1050. out.ports = appendVirtualPorts(out.ports, p.Data.NetIf, rates)
  1051. }
  1052. l.mu.Lock()
  1053. freshPayload := p.Ts != l.lastObsTs[cfg.ID]
  1054. if freshPayload {
  1055. l.lastObsTs[cfg.ID] = p.Ts
  1056. }
  1057. // #441: el cache de system guarda la última sección BUENA (un push
  1058. // wireless-only no la invalida).
  1059. sysSnap := p.Data.System
  1060. sysSnapKind := ""
  1061. if kind := agentSourceClass(p.Kind); sysSnap != nil {
  1062. sysSnapKind = kind
  1063. } else if cached != nil && cached.systemKind == kind {
  1064. sysSnap = cached.system
  1065. sysSnapKind = cached.systemKind
  1066. }
  1067. lldpSnap := p.Data.Lldp
  1068. if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
  1069. lldpSnap = cached.lldp // conserva la última sección buena (#489)
  1070. }
  1071. l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
  1072. 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,
  1073. clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
  1074. l.mu.Unlock()
  1075. // Solo con un payload NUEVO alimentamos las series y el monitor de
  1076. // puertos (issue #365): entre pushes, cada rebuild del overview vuelve
  1077. // por aquí con el MISMO payload cacheado, y re-observar contadores
  1078. // congelados dispara alertas fantasma ("zero bytes" que solo es espera
  1079. // del siguiente push).
  1080. if freshPayload {
  1081. // Los pushers external/beacon persisten sus propias series con
  1082. // contadores de tramas en recordBeaconPortSamples (httpapi/beacon.go)
  1083. // y sus EthPort no llevan contadores, así que pasar por
  1084. // recordPortSamples escribiría filas a 0 intercaladas con las buenas.
  1085. // #1741: un pusher que sí manda contadores o tasas por boca
  1086. // (RouterOS/AsusWRT) es una fuente válida y sin estas muestras su
  1087. // línea de 24 h no tiene de dónde salir, así que la puerta mira el
  1088. // dato, no el kind.
  1089. if out.agentKind != "external" || portsCarryTraffic(out.ports) {
  1090. l.recordPortSamples(cfg.ID, out.ports)
  1091. }
  1092. // #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
  1093. // now = ts del payload (no el reloj del server) para que el dt del
  1094. // delta sea el intervalo real entre pushes del agente.
  1095. if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
  1096. l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
  1097. }
  1098. l.portMon.Observe(cfg.ID, linkPorts(out.ports), l.engine)
  1099. }
  1100. if out.leases == nil {
  1101. out.leases = []DhcpLease{}
  1102. }
  1103. return out
  1104. }
  1105. // checkAgentVersion (issue #400): alerta consolidada (no urgente, sistema)
  1106. // cuando el agente fresh del router empuja una versión anterior a la de
  1107. // referencia de su kind: native → binario de agente embebido en el server,
  1108. // netgrip → última release pública de NetGrip, external → sin check. Al
  1109. // volver a estar al día emite UNA alerta ok de recuperación (patrón
  1110. // consolidación de portmonitor, issue #366).
  1111. func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
  1112. l.mu.Lock()
  1113. src := l.agentLatest
  1114. l.mu.Unlock()
  1115. if src == nil || p == nil || p.Version == "" || p.Kind == "external" {
  1116. return
  1117. }
  1118. ref := src(p.Kind)
  1119. if ref == "" {
  1120. return
  1121. }
  1122. name := agentName(cfg)
  1123. kindLabel := "NetPulse"
  1124. if p.Kind == "netgrip" {
  1125. kindLabel = "NetGrip"
  1126. }
  1127. l.mu.Lock()
  1128. alerted := l.agentOutdatedAlerted[cfg.ID]
  1129. l.mu.Unlock()
  1130. if vercmp.Cmp(ref, p.Version) > 0 {
  1131. if !alerted {
  1132. l.mu.Lock()
  1133. l.agentOutdatedAlerted[cfg.ID] = true
  1134. l.mu.Unlock()
  1135. }
  1136. // #910: EmitOrUpdate notifica en cada actualización en sitio; sin
  1137. // este guard, cada push del agente (30 s) reenviaba la notificación
  1138. // push y refrescaba el timestamp de la alerta. Solo se emite cuando
  1139. // la versión observada o la de referencia cambian.
  1140. key := p.Version + "|" + ref
  1141. l.mu.Lock()
  1142. unchanged := l.agentOutdatedKey[cfg.ID] == key
  1143. if !unchanged {
  1144. l.agentOutdatedKey[cfg.ID] = key
  1145. }
  1146. l.mu.Unlock()
  1147. if unchanged {
  1148. return
  1149. }
  1150. l.engine.EmitOrUpdate(AlertEvent{
  1151. ID: fmt.Sprintf("alert-agent-outdated-%s", cfg.ID),
  1152. Category: alerts.CatSystem, Urgent: false,
  1153. Severity: "warn",
  1154. Title: "Agent outdated on " + name,
  1155. Description: fmt.Sprintf("%s pushes version %s; the latest available for the %s agent is %s", name, p.Version, kindLabel, ref),
  1156. Hint: alerts.HintFor(alerts.HintAgentOutdated),
  1157. Type: alerts.HintAgentOutdated,
  1158. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
  1159. Time: "just now", RouterID: cfg.ID,
  1160. })
  1161. } else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
  1162. l.mu.Lock()
  1163. delete(l.agentOutdatedAlerted, cfg.ID)
  1164. l.mu.Unlock()
  1165. // #833: la alerta de desactualizado DESAPARECE del feed al
  1166. // actualizarse el agente (además del aviso ok de recuperación, que
  1167. // solo se emite cuando el flag en memoria estaba activo).
  1168. l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
  1169. l.mu.Lock()
  1170. delete(l.agentOutdatedKey, cfg.ID)
  1171. l.mu.Unlock()
  1172. if alerted {
  1173. l.engine.Emit(AlertEvent{
  1174. ID: fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
  1175. Category: alerts.CatSystem, Urgent: false,
  1176. Severity: "ok",
  1177. Title: "Agent updated on " + name,
  1178. Description: fmt.Sprintf("%s now pushes version %s of %s", name, p.Version, kindLabel),
  1179. Type: alerts.TypeAgentUpdated,
  1180. Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
  1181. // #1349: el evento de cierre referencia al que resuelve
  1182. // (conservado en el log marcado, no borrado).
  1183. Resolves: []string{fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)},
  1184. Time: "just now", RouterID: cfg.ID,
  1185. })
  1186. }
  1187. }
  1188. }