| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 |
- // agent.go — Adapter live-agent (SPEC-AGENTE-PILOTO §1): el último payload
- // empujado por el agente nativo a POST /api/ingest/agent ES el estado actual
- // del router. Si el agente deja de empujar (> AgentTTL, ~3 intervalos), el
- // router degrada a Tier 0 (SSH) con alerta category system urgent=false
- // ("Agente caído en <nombre> — volviendo a SSH"); al volver el agente se
- // retoma solo y se emite la alerta ok de recuperación.
- //
- // El registry guarda los payloads TAL CUAL llegan (shapes de agent/probe) y
- // Live los convierte a routerPolled con el mismo anti-parpadeo del pipeline
- // SSH (snapshot → SSE → persistencia sin cambios).
- package adapters
- import (
- "fmt"
- "sort"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/agent/probe"
- "github.com/gnacho/netpulse/server-go/internal/alerts"
- "github.com/gnacho/netpulse/server-go/internal/vercmp"
- )
- // AgentTTLDefault: 3 intervalos de push de 15 s (default del agente) + margen.
- const AgentTTLDefault = 90 * time.Second
- // externalGraceFactor: los pushers externos declaran su cadencia en el
- // payload (Interval, segundos); su ventana efectiva es 3x esa cadencia
- // (#288). Un scraper que empuja cada 5 min declara 300 y queda fresco
- // hasta 15 min, en vez de expirar a los 90 s del default nativo.
- const externalGraceFactor = 3
- // AgentState es el último push conocido de un agente.
- type AgentState struct {
- Payload *probe.Payload
- LastSeen time.Time
- Version string
- Kind string // "" | "native" | "external" (#288)
- Interval int // cadencia declarada en segundos; 0 = default nativo
- // Host/BridgeMAC: última identidad conocida del agente (#852). Un push
- // wireless-only (evento nl80211, BuildWireless) no lleva sección system;
- // sin este recuerdo, MatchRouter perdería al agente hasta el próximo
- // push completo y cada roam de un cliente provocaría un "sin cliente"
- // transitorio en routers agent-only emparejados por hostname/MAC.
- Host string
- BridgeMAC string
- }
- // effectiveTTL devuelve la ventana de frescura del estado: el TTL base, o
- // 3x la cadencia declarada si es mayor (pushers externos lentos, #288).
- func (r *AgentRegistry) effectiveTTL(st *AgentState) time.Duration {
- if st != nil && st.Interval > 0 {
- if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > r.ttl {
- return d
- }
- }
- return r.ttl
- }
- // AgentRegistry guarda el último payload por slug (thread-safe: lo escribe el
- // handler de ingesta y lo lee el sondeo live).
- type AgentRegistry struct {
- mu sync.Mutex
- ttl time.Duration
- now func() time.Time
- states map[string]*AgentState
- }
- // NewAgentRegistry crea el registry con el TTL de expiración dado
- // (<= 0 → AgentTTLDefault).
- func NewAgentRegistry(ttl time.Duration) *AgentRegistry {
- if ttl <= 0 {
- ttl = AgentTTLDefault
- }
- return &AgentRegistry{ttl: ttl, now: time.Now, states: map[string]*AgentState{}}
- }
- // SetClock sustituye el reloj (solo tests).
- func (r *AgentRegistry) SetClock(f func() time.Time) {
- r.mu.Lock()
- defer r.mu.Unlock()
- r.now = f
- }
- // Ingest registra un push (último payload = estado actual del router).
- func (r *AgentRegistry) Ingest(p *probe.Payload) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st := &AgentState{
- Payload: p, LastSeen: r.now(), Version: p.Version,
- Kind: p.Kind, Interval: p.Interval,
- }
- if sd := p.Data.System; sd != nil {
- if sd.Board != nil {
- st.Host = sd.Board.Hostname
- }
- st.BridgeMAC = sd.BridgeMAC
- }
- // #852: un push wireless-only no trae identidad; hereda la última
- // conocida para que MatchRouter siga emparejando al agente.
- if prev := r.states[p.Router]; prev != nil {
- if st.Host == "" {
- st.Host = prev.Host
- }
- if st.BridgeMAC == "" {
- st.BridgeMAC = prev.BridgeMAC
- }
- }
- r.states[p.Router] = st
- }
- // Info devuelve last_seen + versión + kind/interval para GET /api/agents
- // (sin exponer el payload).
- func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version, kind string, interval int, ok bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, found := r.states[slug]
- if !found {
- return time.Time{}, "", "", 0, false
- }
- return st.LastSeen, st.Version, st.Kind, st.Interval, true
- }
- // Identity devuelve la identidad retenida del agente: hostname del board y
- // MAC del bridge, aunque el último push sea event-driven y no traiga sección
- // system (#852 los conserva en AgentState). La usa GET /api/agents para
- // asociar el agente con su router cuando el payload actual no lleva identidad
- // (#1874).
- func (r *AgentRegistry) Identity(slug string) (host, bridgeMAC string, ok bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, found := r.states[slug]
- if !found {
- return "", "", false
- }
- return st.Host, st.BridgeMAC, true
- }
- // SelfExpose informa de si el router se expone él mismo a Home Assistant por
- // MQTT (#832), leyéndolo de la última muestra del agente. ok=false = el
- // agente no lo informa (standalone o embedder que no lo reporta).
- func (r *AgentRegistry) SelfExpose(slug string) (enabled bool, node string, ok bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, found := r.states[slug]
- if !found || st.Payload == nil || st.Payload.Data.MQTT == nil {
- return false, "", false
- }
- return st.Payload.Data.MQTT.Enabled, st.Payload.Data.MQTT.Node, true
- }
- // ExternalDownConfirm escala la ventana de confirmación de caída para un
- // pusher externo: max(confirm base, 3x su cadencia declarada) (#288). Con
- // la base a secas, un scraper de 5 min dispararía "agente caído" tras un
- // único push perdido.
- func (r *AgentRegistry) ExternalDownConfirm(slug string, base time.Duration) time.Duration {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- if !ok || st.Interval <= 0 {
- return base
- }
- if d := time.Duration(st.Interval*externalGraceFactor) * time.Second; d > base {
- return d
- }
- return base
- }
- // LocalBssids devuelve los BSSID que los agentes reportan como propios
- // (AP local=true en sus datos dawn/usteer). El channel-plan los usa de
- // semilla exacta para la detección de redes propias (#1082): casos como el
- // guest de un GL.iNet, cuya MAC no comparte prefijo con routers.mac.
- func (r *AgentRegistry) LocalBssids() []string {
- r.mu.Lock()
- defer r.mu.Unlock()
- seen := map[string]bool{}
- var out []string
- add := func(mac string) {
- mac = strings.ToUpper(strings.TrimSpace(mac))
- if mac == "" || seen[mac] {
- return
- }
- seen[mac] = true
- out = append(out, mac)
- }
- for _, st := range r.states {
- if st.Payload == nil {
- continue
- }
- // BSSIDs propios reportados por el agente (#1087): exactos, cubren
- // MACs aleatorizadas y guests fuera de dawn/usteer.
- if w := st.Payload.Data.Wireless; w != nil {
- for _, ob := range w.OwnBssids {
- add(ob.BSSID)
- }
- }
- if st.Payload.Data.Dawn != nil {
- for _, ssid := range st.Payload.Data.Dawn.SSIDs {
- for _, ap := range ssid.APs {
- if ap.Local {
- add(ap.BSSID)
- }
- }
- }
- }
- if st.Payload.Data.Usteer != nil {
- for _, ssid := range st.Payload.Data.Usteer.SSIDs {
- for _, ap := range ssid.APs {
- if ap.Local {
- add(ap.BSSID)
- }
- }
- }
- }
- }
- return out
- }
- // LocalSsids devuelve los SSID que los agentes reportan como propios
- // (#1358): OwnBssids con SSID no vacío + SSIDs con al menos un AP local en
- // dawn/usteer. Es la lista "auto-aprobada" para la detección de SSID
- // impostor: cualquier BSSID ajeno anunciando uno de estos nombres es
- // sospechoso. Dedup, ordenado para salida estable.
- func (r *AgentRegistry) LocalSsids() []string {
- r.mu.Lock()
- defer r.mu.Unlock()
- seen := map[string]bool{}
- var out []string
- add := func(ssid string) {
- if ssid == "" || seen[ssid] {
- return
- }
- seen[ssid] = true
- out = append(out, ssid)
- }
- for _, st := range r.states {
- if st.Payload == nil {
- continue
- }
- if w := st.Payload.Data.Wireless; w != nil {
- for _, ob := range w.OwnBssids {
- add(ob.SSID)
- }
- }
- if st.Payload.Data.Dawn != nil {
- for name, ssid := range st.Payload.Data.Dawn.SSIDs {
- for _, ap := range ssid.APs {
- if ap.Local {
- add(name)
- break
- }
- }
- }
- }
- if st.Payload.Data.Usteer != nil {
- for name, ssid := range st.Payload.Data.Usteer.SSIDs {
- for _, ap := range ssid.APs {
- if ap.Local {
- add(name)
- break
- }
- }
- }
- }
- }
- sort.Strings(out)
- return out
- }
- // Fresh devuelve el último payload si está dentro de su ventana de
- // frescura (TTL base o 3x cadencia declarada, #288).
- func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- if !ok || r.now().Sub(st.LastSeen) > r.effectiveTTL(st) {
- return nil, false
- }
- return st.Payload, true
- }
- // Expired reporta si el slug tiene agente conocido pero su último push
- // expiró (candidato a degradar a SSH con aviso).
- func (r *AgentRegistry) Expired(slug string) bool {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- return ok && r.now().Sub(st.LastSeen) > r.effectiveTTL(st)
- }
- // StalePayload devuelve el último payload del slug sin comprobar TTL.
- // Sirve para usar datos stale en routers agent-only (sin SSH).
- func (r *AgentRegistry) StalePayload(slug string) (*probe.Payload, bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- if !ok || st.Payload == nil {
- return nil, false
- }
- return st.Payload, true
- }
- // StaleFor reporta si el slug lleva más de threshold sin empujar datos.
- // Se usa para el Dead Man's Switch (P6): confirmar que un agente está
- // realmente caído antes de disparar la alerta, evitando spam en flapeos.
- func (r *AgentRegistry) StaleFor(slug string, threshold time.Duration) bool {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- if !ok || st.LastSeen.IsZero() {
- return false
- }
- return r.now().Sub(st.LastSeen) > threshold
- }
- // ActiveCount devuelve cuántos agentes tienen su último push dentro del TTL
- // (métricas operativas de /api/health).
- func (r *AgentRegistry) ActiveCount() int {
- r.mu.Lock()
- defer r.mu.Unlock()
- n := 0
- for _, st := range r.states {
- if r.now().Sub(st.LastSeen) <= r.effectiveTTL(st) {
- n++
- }
- }
- return n
- }
- // Restore repuebla el estado de un slug desde el almacén persistente
- // (arranque del servidor). No revalida TTL: la expiración la decide el
- // reloj comparando contra el LastSeen restaurado. Sobrescribe cualquier
- // estado previo del slug. Los estados persistidos antes de #288 no traen
- // Kind/Interval y los de antes de #852 no traen Host/BridgeMAC: se
- // recuperan del payload si están ahí.
- func (r *AgentRegistry) Restore(slug string, st *AgentState) {
- r.mu.Lock()
- defer r.mu.Unlock()
- if st != nil && st.Payload != nil {
- if st.Interval == 0 {
- st.Kind, st.Interval = st.Payload.Kind, st.Payload.Interval
- }
- if sd := st.Payload.Data.System; sd != nil {
- if st.Host == "" && sd.Board != nil {
- st.Host = sd.Board.Hostname
- }
- if st.BridgeMAC == "" {
- st.BridgeMAC = sd.BridgeMAC
- }
- }
- }
- r.states[slug] = st
- }
- // Snapshot devuelve una copia del estado de un slug (o nil si no existe).
- // Usado para persistir el último push sin exponer el map interno.
- func (r *AgentRegistry) Snapshot(slug string) *AgentState {
- r.mu.Lock()
- defer r.mu.Unlock()
- st, ok := r.states[slug]
- if !ok {
- return nil
- }
- cp := *st
- return &cp
- }
- // MatchRouter busca el agente asociado a un router: primero por slug exacto,
- // luego por hostname de board y finalmente por bridge MAC (#282). El match
- // por hostname/MAC usa la identidad retenida en el estado (#852), válida
- // aunque el último push sea wireless-only. Devuelve el slug real del
- // agente, su payload y si está fresco. Permite que un agente emparejado con
- // un slug elegido por el usuario alimente un router cuyo id autogenerado no
- // coincide con ese slug.
- func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (string, *probe.Payload, bool) {
- r.mu.Lock()
- defer r.mu.Unlock()
- norm := func(s string) string {
- return strings.ToLower(strings.TrimSpace(s))
- }
- hostNames := []string{}
- if cfg.Host != "" {
- hostNames = append(hostNames, norm(cfg.Host))
- }
- if cfg.Name != "" && norm(cfg.Name) != norm(cfg.Host) {
- hostNames = append(hostNames, norm(cfg.Name))
- }
- if cfg.ID != "" && norm(cfg.ID) != norm(cfg.Host) && norm(cfg.ID) != norm(cfg.Name) {
- hostNames = append(hostNames, norm(cfg.ID))
- }
- // #1334: la MAC de bridge persistida es la identidad física autoritativa
- // (los hostnames se duplican en APs puente idénticos). Se recogen TODOS
- // los candidatos por nivel y solo un match ÚNICO asocia: la ambigüedad no
- // inventa asociaciones (antes: primer match en orden aleatorio de mapa).
- targetMac := ""
- if macs != nil {
- targetMac = strings.ToUpper(strings.TrimSpace(macs[cfg.ID]))
- }
- var macMatch *AgentState
- var macMatchSlug string
- macMatchCount := 0
- var hostMatch *AgentState
- var hostMatchSlug string
- hostMatchCount := 0
- for slug, st := range r.states {
- if slug == cfg.ID {
- fresh := r.now().Sub(st.LastSeen) <= r.effectiveTTL(st)
- return slug, st.Payload, fresh
- }
- // #852: el match usa la identidad RETENIDA (Host/BridgeMAC), no la
- // del payload actual: el último push puede ser wireless-only (evento
- // nl80211, sin sección system) y aun así debe emparejar. Sin esto,
- // cada roam borraba la identidad hasta el próximo push completo.
- if st.Payload == nil {
- continue
- }
- if targetMac != "" && strings.EqualFold(st.BridgeMAC, targetMac) {
- macMatchCount++
- macMatch = st
- macMatchSlug = slug
- }
- if h := norm(st.Host); h != "" {
- for _, candidate := range hostNames {
- if h == candidate {
- hostMatchCount++
- hostMatch = st
- hostMatchSlug = slug
- break
- }
- }
- }
- }
- if macMatchCount == 1 {
- fresh := r.now().Sub(macMatch.LastSeen) <= r.effectiveTTL(macMatch)
- return macMatchSlug, macMatch.Payload, fresh
- }
- if macMatchCount > 1 {
- return "", nil, false
- }
- if hostMatchCount == 1 {
- fresh := r.now().Sub(hostMatch.LastSeen) <= r.effectiveTTL(hostMatch)
- return hostMatchSlug, hostMatch.Payload, fresh
- }
- return "", nil, false
- }
- // Forget borra el estado del slug (revocación de token).
- func (r *AgentRegistry) Forget(slug string) {
- r.mu.Lock()
- defer r.mu.Unlock()
- delete(r.states, slug)
- }
- // ---------------------------------------------------------------------------
- // Integración con Live
- // ---------------------------------------------------------------------------
- // SetAgents enchufa el registry de agentes al adapter live (nil = sin
- // soporte de agentes; todo va por SSH como antes).
- func (l *Live) SetAgents(r *AgentRegistry) {
- l.mu.Lock()
- l.agents = r
- l.mu.Unlock()
- }
- // SetAgentDownConfirm fija el periodo de confirmación del Dead Man's Switch
- // (P6): tiempo sin push tras el cual se confirma la caída de un agente.
- func (l *Live) SetAgentDownConfirm(d time.Duration) {
- l.mu.Lock()
- if d > 0 {
- l.agentDownConfirm = d
- }
- l.mu.Unlock()
- }
- // SetAgentLatestSource fija la fuente de la versión de referencia por kind
- // de agente (issue #400): native → binario embebido del server, netgrip →
- // última release pública de NetGrip, external → "" (nunca alerta). nil o
- // referencia vacía desactivan el check de agente desactualizado.
- func (l *Live) SetAgentLatestSource(fn func(kind string) string) {
- l.mu.Lock()
- l.agentLatest = fn
- l.mu.Unlock()
- }
- // agentName: nombre para las alertas (cfg.Name o Host como el resto).
- func agentName(cfg RouterConfig) string {
- if cfg.Name != "" {
- return cfg.Name
- }
- return cfg.Host
- }
- // pollRouterAgent: si un agente asociado al router está fresco, construye el
- // sondeo desde su payload (Tier 2). Si expiró, emite UNA vez la alerta de
- // caída y devuelve (false, nil) para que el caller siga por SSH (Tier 0).
- // El emparejamiento no exige slug == router.id: también usa hostname/MAC
- // (#282). Cuando el agente está vivo pero el SSH falla por clave no
- // autorizada, emite una alerta informativa en vez de dejar la tarjeta en
- // offline (#281).
- func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
- l.mu.Lock()
- reg := l.agents
- macs := make(map[string]string, len(l.routerMacs))
- for k, v := range l.routerMacs {
- macs[k] = v
- }
- l.mu.Unlock()
- if reg == nil {
- return false, nil
- }
- slug, p, fresh := reg.MatchRouter(cfg, macs)
- if fresh {
- // issue #400: versión del agente desactualizada (alerta consolidada).
- l.checkAgentVersion(cfg, p)
- l.mu.Lock()
- if l.agentDown[cfg.ID] {
- l.agentDown[cfg.ID] = false
- name := agentName(cfg)
- // #966: la alerta de caída es VOLÁTIL con ID estable por router:
- // al recuperarse el agente desaparece del feed (no acumula
- // historial). "Agente recuperado" SÍ persiste (registro positivo).
- l.engine.Remove("alert-agent-down-" + cfg.ID)
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-agent-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "ok",
- Title: "Agent recovered on " + name,
- Description: fmt.Sprintf("The agent on %s is pushing data again - native polling resumed", name),
- Type: alerts.TypeAgentRecovered,
- Vars: map[string]string{"router": name},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- // issue #281: SSH falla por clave no autorizada pero el agente sigue
- // vivo → avisa una sola vez. Se borra el flag cuando SSH vuelve.
- if l.lastErr[cfg.ID] != nil && isAccessError(l.lastErr[cfg.ID]) {
- if !l.sshAuthFailAlerted[cfg.ID] {
- l.sshAuthFailAlerted[cfg.ID] = true
- name := agentName(cfg)
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-ssh-auth-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "warn",
- Title: "SSH access lost on " + name,
- Description: fmt.Sprintf("%s does not accept the SSH key, but its agent keeps sending data. Check authorized_keys after a firmware upgrade.", name),
- Type: alerts.TypeSSHAccessLost,
- Vars: map[string]string{"router": name},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- } else if l.sshAuthFailAlerted[cfg.ID] {
- delete(l.sshAuthFailAlerted, cfg.ID)
- name := agentName(cfg)
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-ssh-auth-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "ok",
- Title: "SSH access recovered on " + name,
- Description: fmt.Sprintf("SSH access to %s is working again", name),
- Type: alerts.TypeSSHAccessRecovered,
- Vars: map[string]string{"router": name},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- l.mu.Unlock()
- return true, l.polledFromAgent(cfg, p)
- }
- if slug != "" {
- // Dead Man's Switch (P6): el agente está stale, pero solo disparamos la
- // alerta de caída si lleva más de agentDownConfirm sin empujar. Entre
- // TTL y agentDownConfirm el router degrada a SSH silenciosamente.
- confirm := l.agentDownConfirm
- if confirm <= 0 {
- confirm = 3 * time.Minute
- }
- confirm = reg.ExternalDownConfirm(slug, confirm)
- if reg.StaleFor(slug, confirm) {
- l.mu.Lock()
- // #1917: en una unidad con inventory_mode "ssh" el agente no se
- // espera nunca, asi que su ausencia no es un evento: nada de
- // alerta, ni urgente ni warn.
- if !l.agentDown[cfg.ID] && cfg.InventoryMode != "ssh" {
- l.agentDown[cfg.ID] = true
- name := agentName(cfg)
- // #850: para routers agent-only el agente ES la única vía
- // de datos (el poll sirve el payload cacheado y el router
- // nunca marca offline): su caída es un evento de router
- // urgente, comparable al offline, para que pase los filtros
- // de notificación "solo urgentes del topic router". Con SSH
- // disponible se degrada con gracia y sigue siendo system.
- // #966: la alerta de caída es VOLÁTIL y con ID estable por
- // router (alert-agent-down-<id>): no se persiste en
- // alert_log, no sobrevive reinicios y al recuperarse el
- // agente desaparece del feed (engine.Remove arriba).
- if cfg.AgentOnly {
- l.engine.EmitVolatile(AlertEvent{
- ID: "alert-agent-down-" + cfg.ID,
- Category: alerts.CatRouter, Urgent: true,
- Severity: "critical",
- Title: fmt.Sprintf("Agent down on %s", name),
- Description: fmt.Sprintf("No data from the agent on %s for more than %s - using cached data", name, confirm),
- Hint: alerts.HintFor(alerts.HintAgentDown),
- Type: alerts.HintAgentDown,
- Vars: map[string]string{"router": name, "confirm": confirm.String()},
- Time: "just now", RouterID: cfg.ID,
- })
- } else {
- l.engine.EmitVolatile(AlertEvent{
- ID: "alert-agent-down-" + cfg.ID,
- Category: alerts.CatSystem, Urgent: false,
- Severity: "warn",
- Title: fmt.Sprintf("Agent down on %s - falling back to SSH", name),
- Description: fmt.Sprintf("No data from the agent on %s for more than %s - SSH polling resumed", name, confirm),
- Hint: alerts.HintFor(alerts.HintAgentDownSSH),
- Type: alerts.HintAgentDownSSH,
- Vars: map[string]string{"router": name, "confirm": confirm.String()},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- }
- l.mu.Unlock()
- }
- if cfg.AgentOnly {
- if p != nil {
- return true, l.polledFromAgent(cfg, p)
- }
- }
- }
- return false, nil
- }
- // agentIfSample: contadores por iface del último payload del agente (para
- // el delta de rates por boca, issue #305).
- type agentIfSample struct {
- at time.Time
- ifaces map[string]probe.IfCounters
- }
- // injectPortRates copia absolutos + rates de rates (keyed por iface física)
- // sobre las bocas: match por Iface si la boca la declara, si no por ID (en
- // DSA coinciden; en swconfig el ID es numérico y solo Iface casa).
- // appendVirtualPorts turns the interfaces NetIf carries that are not physical
- // ports into EthPorts, so the router page can list them with their traffic
- // (#1757). The agent path never built them: NetIf only fed the rates of the
- // physical ports. Up means "has carried traffic", because /proc/net/dev has no
- // link state and inventing one would be worse than saying nothing.
- func appendVirtualPorts(ports []EthPort, ifaces map[string]probe.IfCounters, rates map[string]probe.IfRate) []EthPort {
- if len(ifaces) == 0 {
- return ports
- }
- seen := make(map[string]bool, len(ports))
- for _, p := range ports {
- if p.Iface != "" {
- seen[p.Iface] = true
- }
- if p.ID != "" {
- seen[p.ID] = true
- }
- }
- names := make([]string, 0, len(ifaces))
- for name := range ifaces {
- if name == "lo" || seen[name] {
- continue
- }
- names = append(names, name)
- }
- if len(names) == 0 {
- return ports
- }
- sort.Strings(names)
- for _, name := range names {
- c := ifaces[name]
- p := EthPort{
- ID: "if-" + name,
- Label: name,
- Iface: name,
- Up: c.Rx+c.Tx > 0,
- Family: virtualIfaceFamily(name),
- RxBytes: c.Rx,
- TxBytes: c.Tx,
- RxErrs: c.RxErr,
- TxErrs: c.TxErr,
- }
- if r, ok := rates[name]; ok {
- if r.RxBps != nil {
- p.RxBps = *r.RxBps
- }
- if r.TxBps != nil {
- p.TxBps = *r.TxBps
- }
- }
- ports = append(ports, p)
- }
- return ports
- }
- // virtualIfaceFamily names the family the router page groups by, the same
- // values the SNMP path gets from ifType.
- func virtualIfaceFamily(name string) string {
- switch {
- case strings.Contains(name, "."), strings.HasPrefix(name, "vlan"):
- return "vlan"
- case strings.HasPrefix(name, "br"), name == "bridge":
- return "bridge"
- // #1757: las interfaces AP no tienen ifType en /proc/net/dev. En OpenWrt
- // son phy<N>-ap<N> (hostapd sobre mac80211) y en otras plataformas
- // wlan<N>: verlas como "virtual" a secas esconde que son el WiFi, que es
- // justo lo que se quiere leer por interfaz.
- case strings.HasPrefix(name, "phy") && strings.Contains(name, "-ap"),
- strings.HasPrefix(name, "wlan"):
- return "wifi"
- case strings.HasPrefix(name, "bond"), strings.HasPrefix(name, "lag"):
- return "lag"
- case strings.HasPrefix(name, "tun"), strings.HasPrefix(name, "tap"), strings.HasPrefix(name, "wg"),
- strings.HasPrefix(name, "pppoe"), strings.HasPrefix(name, "gre"), strings.HasPrefix(name, "sit"),
- strings.HasPrefix(name, "vti"), strings.HasPrefix(name, "ip6tnl"):
- return "tunnel"
- }
- return "virtual"
- }
- // linkPorts drops the interfaces that are not physical links: they have no
- // link state to watch, so the port monitor has nothing to say about them
- // (#1757).
- func linkPorts(ports []EthPort) []EthPort {
- n := 0
- for _, p := range ports {
- if p.Family != "" && p.Family != "ethernet" {
- n++
- }
- }
- if n == 0 {
- return ports
- }
- out := make([]EthPort, 0, len(ports)-n)
- for _, p := range ports {
- if p.Family != "" && p.Family != "ethernet" {
- continue
- }
- out = append(out, p)
- }
- return out
- }
- func injectPortRates(ports []EthPort, rates map[string]probe.IfRate) {
- for i := range ports {
- key := ports[i].Iface
- if key == "" {
- key = ports[i].ID
- }
- r, ok := rates[key]
- if !ok {
- continue
- }
- ports[i].Iface = key
- ports[i].RxBytes = r.Rx
- ports[i].TxBytes = r.Tx
- ports[i].RxErrs = r.RxErr
- ports[i].TxErrs = r.TxErr
- if r.RxBps != nil {
- ports[i].RxBps = *r.RxBps
- }
- if r.TxBps != nil {
- ports[i].TxBps = *r.TxBps
- }
- }
- }
- // agentSourceClass: la documentación de probe.Payload.Kind declara "" y
- // "native" como el mismo agente nativo, así que el cache de system los trata
- // como una sola fuente; cada kind restante (external, netgrip…) es la suya
- // propia.
- func agentSourceClass(kind string) string {
- if kind == "" || kind == "native" {
- return "native"
- }
- return kind
- }
- // isPusherType: tipos de router que no corren el agente nativo, así que su
- // push llega de un scraper o de una integración (#1871). "" se trata como
- // nativo para no inventar un kind cuando la fila no está cargada.
- func isPusherType(t string) bool {
- switch t {
- case "", "openwrt", "glinet":
- return false
- }
- return true
- }
- // portsCarryTraffic: el payload trae contadores o tasas por boca. Un beacon
- // solo publica estado de enlace y FDB, así que no entra (#1741).
- func portsCarryTraffic(ports []EthPort) bool {
- for _, p := range ports {
- if p.RxBytes > 0 || p.TxBytes > 0 || p.RxBps > 0 || p.TxBps > 0 {
- return true
- }
- }
- return false
- }
- // polledFromAgent convierte el payload del agente en el routerPolled del
- // pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
- // que pollRouter: sección ausente en el payload = sonda fallida → conserva
- // el último dato bueno cacheado.
- func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled {
- l.mu.Lock()
- cached := l.extrasCache[cfg.ID]
- l.mu.Unlock()
- out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}, polledAt: time.Now().UnixMilli()}
- // #441: conservar el kind del agente: los pushers externos (beacon/
- // scraper) no llevan sección system y el router queda sin vitals.
- out.agentKind = p.Kind
- // #1871: el kind del payload es opcional y las integraciones que empujan
- // no lo rellenan, pero el registro ya sabe que la unidad no corre el
- // agente nativo. Se sella en el polled y no en el payload a propósito:
- // checkAgentVersion y el cache anti-parpadeo leen p.Kind, y un agente
- // nativo en una fila external (migración 2.49.x) debe seguir comprobando
- // su versión y heredando sus propias vitals.
- if out.agentKind == "" && isPusherType(cfg.Type) {
- out.agentKind = "external"
- }
- // #832: el equipo se expone él mismo a Home Assistant por MQTT (NetGrip
- // con su MQTT activado); el publisher de flota cede el paso.
- out.selfExpose = p.Data.MQTT != nil && p.Data.MQTT.Enabled
- sysInfo := &SysInfo{}
- ramPct := 0
- if sd := p.Data.System; sd != nil {
- if sd.SysInfo != nil {
- sysInfo = sd.SysInfo
- out.hasUptime = true
- }
- out.board = sd.Board
- if sd.Board != nil {
- l.mu.Lock()
- l.boardCache[cfg.ID] = sd.Board
- l.mu.Unlock()
- }
- if sd.CPU != nil {
- out.cpu, out.hasCpu = *sd.CPU, true
- }
- if sd.Temp != nil {
- out.temp, out.hasTemp = *sd.Temp, true
- }
- out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
- out.latencyMs = sd.LatencyMs
- out.lossPct = sd.LossPct
- out.backhaul = sd.Backhaul
- out.brMac = sd.BridgeMAC
- // #1765: identidades propias del equipo. El agente manda las MACs de
- // todas sus interfaces; sin esto solo se absorbía la del bridge y el
- // resto (VLANs, puerto CPU de un switch DSA, radios) aparecía como
- // cliente desconocido cuando un vecino las aprendía en su FDB.
- out.selfMacs = sd.IfaceMACs
- out.flash = sd.Flash
- out.firmwareAvailable = sd.FirmwareAvailable
- } else if cached != nil && cached.system != nil && cached.systemKind == agentSourceClass(p.Kind) {
- // #441: push event-driven (wireless-only) sin system → conserva las
- // últimas vitals buenas cacheadas en vez de pintar ceros falsos.
- // Solo vitals/uptime: net/latencia/backhaul no se reciclan (evita
- // duplicar tráfico con muestras viejas).
- //
- // Solo dentro del mismo kind: extrasCache se clave únicamente por ID,
- // así que un payload external sin sección system heredaría las vitals
- // del agente nativo que alimentó al router antes. Como #1724 marca lo
- // que trae el payload de confirmado, esa herencia se publicaría como
- // lectura propia y acabaría en el histórico.
- sd := cached.system
- if sd.CPU != nil {
- out.cpu, out.hasCpu = *sd.CPU, true
- }
- if sd.Temp != nil {
- out.temp, out.hasTemp = *sd.Temp, true
- }
- if sd.SysInfo != nil {
- sysInfo = sd.SysInfo
- out.hasUptime = true
- }
- }
- mem := sysInfo.Memory
- // Con solo Mem.Total y ninguna cifra de uso no hay nada que derivar:
- // memUsagePct caería a "available = free + buffered = 0" y reportaría un
- // 100 % inventado. Eso es memoria desconocida, no memoria llena.
- if mem.Total > 0 && memUsageKnown(mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used) {
- ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
- // La memoria del payload es una lectura confirmada (los pushers de
- // RouterOS/AsusWRT la derivan de free/memory), no un hueco que haya
- // que pintar a cero.
- out.hasRam = true
- }
- out.sysInfo = sysInfo
- out.ram = ramPct
- out.uptimeSec = sysInfo.Uptime
- // Secciones con anti-parpadeo (nil en el payload = sonda fallida).
- if wd := p.Data.Wireless; wd != nil {
- if wd.Clients != nil {
- out.wireless = wd.Clients
- }
- if len(wd.Radios) > 0 {
- out.radios = radiosToAdapter(wd.Radios)
- }
- }
- if dd := p.Data.DHCP; dd != nil {
- out.leases = dd.Leases
- // gl-clients del agente (GL.iNet): enriquece IPs igual que en la
- // ruta SSH (issue #5 bug 1).
- out.glClients = dd.GlClients
- }
- if p.Data.Arp != nil {
- out.arp = p.Data.Arp
- out.arpDevs = p.Data.ArpDevs
- // An agent old enough not to send arpStale leaves this empty, and
- // the whole table counts as presence, exactly as it used to.
- out.arpStale = make(map[string]bool, len(p.Data.ArpStale))
- for _, mac := range p.Data.ArpStale {
- out.arpStale[strings.ToUpper(mac)] = true
- }
- }
- // Wan (#276): el agente lo trae en el payload desde 2.28.24+. Antes solo
- // existía la sonda SSH del server, que en un router agent_only no corre
- // nunca -- y su panel de conexión se quedaba vacío.
- if w := p.Data.Wan; w != nil {
- out.wanInfo = *w
- }
- // MultiWan: the several internet connections and which one carries
- // traffic. Only a router whose own panel manages them reports it; an
- // event-driven push carries no section, so the last good one is kept
- // or the panel would blink out between full pushes.
- out.multiWan = normalizeMultiWan(p.Data.MultiWan)
- if out.multiWan == nil && cached != nil {
- out.multiWan = cached.multiWan
- }
- // Vlans travel in the payload too, and were being dropped here: a
- // router polled through its agent never reached the SSH path that is
- // the only other place they are read, so its VLAN panel stayed empty.
- if len(p.Data.Vlans) > 0 {
- out.vlans = p.Data.Vlans
- } else if cached != nil {
- out.vlans = cached.vlans
- }
- // #1889: las redes UCI viajan en el mismo payload que las VLANs.
- if len(p.Data.Networks) > 0 {
- out.networks = p.Data.Networks
- } else if cached != nil {
- out.networks = cached.networks
- }
- // #1942: el mapa ifname -> red viaja en la seccion wireless del payload.
- if wm := wifiNetworkMap(dot11rIfacesFromPayload(p)); wm != nil {
- out.wifiNet = wm
- } else if cached != nil {
- out.wifiNet = cached.wifiNet
- }
- if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
- out.reservations = dh.Reservations
- }
- if fd := p.Data.FDB; fd != nil {
- if fd.MACs != nil {
- out.fdb = fd.MACs
- }
- // Sección FDB fresca: el hint wireless-side se pisa tal cual, incluso
- // vacío (nadie lo refresca ya: agente caído o pasado a SSH). Solo un
- // push SIN sección FDB (event-driven) recicla el cache, mismo contrato
- // anti-parpadeo que fdb.
- out.wirelessSide = fd.WirelessSide
- // #1757: VLAN real de cada cliente cableado, tal como el bridge la
- // aprendió. Se pisa tal cual (incluso vacío) por la misma razón que el
- // hint wireless-side: una sección fresca es la verdad del equipo.
- out.fdbVlans = fd.VLANs
- if len(fd.Ports) > 0 {
- out.ports = ethPortsToAdapter(fd.Ports)
- // #291: los pushers externos declaran el puerto del FDB como
- // número ("1") mientras sus bocas usan id "lan1". Normalizar
- // para que el enriquecimiento del detalle (MAC→nombre por boca)
- // y la topología casen ambas claves.
- ids := map[string]bool{}
- for _, ep := range out.ports {
- ids[ep.ID] = true
- }
- if len(ids) > 0 {
- for mac, port := range out.fdb {
- if port == "wan" || ids[port] {
- continue
- }
- if lan := "lan" + port; ids[lan] {
- out.fdb[mac] = lan
- }
- }
- }
- }
- }
- // LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de
- // topología. Best-effort: sección ausente → conserva la última buena.
- if p.Data.LuCI != nil {
- out.luci = p.Data.LuCI
- }
- // LLDP (#489): vecinos del payload del agente (antes solo llegaban por
- // la sonda SSH, muerta para routers con agente fresco). Resolución con
- // anti-parpadeo: manda la sección buena del payload; una sección
- // fallida (Available=true con Neighbors nil) o ausente (push
- // event-driven) recicla la última cacheada. Available=false explícito =
- // lldpd no instalado (hint de UI), y eso SÍ pisa lo cacheado.
- resolveLldp := func() (nbs []LldpNeighbor, unavailable bool, hint string) {
- ld := p.Data.Lldp
- if ld == nil || (ld.Available && ld.Neighbors == nil) {
- ld = nil
- if cached != nil {
- ld = cached.lldp
- }
- }
- if ld == nil {
- return nil, false, ""
- }
- if !ld.Available {
- return nil, true, ""
- }
- return lldpFromProbe(ld.Neighbors), false, ld.Hint
- }
- out.lldp, out.lldpUnavailable, out.lldpHint = resolveLldp()
- // ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
- // LLDP: la sección buena del payload manda; una sección fallida
- // (Available=true con Hosts nil) o ausente (push event-driven) recicla
- // la última cacheada; Available=false explícito = nlbwmon no instalado
- // y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
- resolveClientBw := func() *probe.ClientBwData {
- cb := p.Data.ClientBw
- if cb == nil || (cb.Available && cb.Hosts == nil) {
- cb = nil
- if cached != nil {
- cb = cached.clientBw
- }
- }
- if cb == nil || !cb.Available {
- return nil
- }
- return cb
- }
- out.clientBw = resolveClientBw()
- // Discovery (#338): mDNS services + randomized MACs. Best-effort.
- if p.Data.Discovery != nil {
- out.discovery = p.Data.Discovery
- }
- out.dawnDetected = p.Data.Dawn != nil
- if cached == nil {
- cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
- wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
- }
- if out.ports == nil {
- out.ports = cached.ports
- }
- if out.radios == nil {
- out.radios = cached.radios
- }
- if out.wireless == nil {
- out.wireless = cached.wireless
- }
- if out.fdb == nil {
- out.fdb = cached.fdb
- }
- if out.wirelessSide == nil && p.Data.FDB == nil {
- out.wirelessSide = cached.wirelessSide
- }
- if out.fdbVlans == nil && p.Data.FDB == nil {
- out.fdbVlans = cached.fdbVlans
- }
- if out.luci == nil {
- out.luci = cached.luci
- }
- // NetIf (issue #305): rates por boca con el delta entre payloads del
- // agente. El payload trae contadores ABSOLUTOS por iface; el server
- // calcula bps con la muestra anterior (ts del propio payload, no el
- // reloj del server). Sección ausente → conserva los rates cacheados.
- // Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
- // snapshot para que el cache lleve los rates frescos.
- if p.Data.NetIf != nil {
- now := time.Unix(p.Ts, 0)
- l.mu.Lock()
- prev := l.lastAgentIf[cfg.ID]
- l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
- l.mu.Unlock()
- var rates map[string]probe.IfRate
- if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
- rates = probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
- injectPortRates(out.ports, rates)
- }
- // #1757: las interfaces que no son bocas físicas (vlan, bridge,
- // bond, tun, wg) también cuentan. La página del router las lista
- // aparte por su familia, con el tráfico que ya trae NetIf.
- out.ports = appendVirtualPorts(out.ports, p.Data.NetIf, rates)
- }
- l.mu.Lock()
- freshPayload := p.Ts != l.lastObsTs[cfg.ID]
- if freshPayload {
- l.lastObsTs[cfg.ID] = p.Ts
- }
- // #441: el cache de system guarda la última sección BUENA (un push
- // wireless-only no la invalida).
- sysSnap := p.Data.System
- sysSnapKind := ""
- if kind := agentSourceClass(p.Kind); sysSnap != nil {
- sysSnapKind = kind
- } else if cached != nil && cached.systemKind == kind {
- sysSnap = cached.system
- sysSnapKind = cached.systemKind
- }
- lldpSnap := p.Data.Lldp
- if (lldpSnap == nil || (lldpSnap.Available && lldpSnap.Neighbors == nil)) && cached != nil {
- lldpSnap = cached.lldp // conserva la última sección buena (#489)
- }
- l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
- 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,
- clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
- l.mu.Unlock()
- // Solo con un payload NUEVO alimentamos las series y el monitor de
- // puertos (issue #365): entre pushes, cada rebuild del overview vuelve
- // por aquí con el MISMO payload cacheado, y re-observar contadores
- // congelados dispara alertas fantasma ("zero bytes" que solo es espera
- // del siguiente push).
- if freshPayload {
- // Los pushers external/beacon persisten sus propias series con
- // contadores de tramas en recordBeaconPortSamples (httpapi/beacon.go)
- // y sus EthPort no llevan contadores, así que pasar por
- // recordPortSamples escribiría filas a 0 intercaladas con las buenas.
- // #1741: un pusher que sí manda contadores o tasas por boca
- // (RouterOS/AsusWRT) es una fuente válida y sin estas muestras su
- // línea de 24 h no tiene de dónde salir, así que la puerta mira el
- // dato, no el kind.
- if out.agentKind != "external" || portsCarryTraffic(out.ports) {
- l.recordPortSamples(cfg.ID, out.ports)
- }
- // #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
- // now = ts del payload (no el reloj del server) para que el dt del
- // delta sea el intervalo real entre pushes del agente.
- if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
- l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
- }
- l.portMon.Observe(cfg.ID, linkPorts(out.ports), l.engine)
- }
- if out.leases == nil {
- out.leases = []DhcpLease{}
- }
- return out
- }
- // checkAgentVersion (issue #400): alerta consolidada (no urgente, sistema)
- // cuando el agente fresh del router empuja una versión anterior a la de
- // referencia de su kind: native → binario de agente embebido en el server,
- // netgrip → última release pública de NetGrip, external → sin check. Al
- // volver a estar al día emite UNA alerta ok de recuperación (patrón
- // consolidación de portmonitor, issue #366).
- func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
- l.mu.Lock()
- src := l.agentLatest
- l.mu.Unlock()
- if src == nil || p == nil || p.Version == "" || p.Kind == "external" {
- return
- }
- ref := src(p.Kind)
- if ref == "" {
- return
- }
- name := agentName(cfg)
- kindLabel := "NetPulse"
- if p.Kind == "netgrip" {
- kindLabel = "NetGrip"
- }
- l.mu.Lock()
- alerted := l.agentOutdatedAlerted[cfg.ID]
- l.mu.Unlock()
- if vercmp.Cmp(ref, p.Version) > 0 {
- if !alerted {
- l.mu.Lock()
- l.agentOutdatedAlerted[cfg.ID] = true
- l.mu.Unlock()
- }
- // #910: EmitOrUpdate notifica en cada actualización en sitio; sin
- // este guard, cada push del agente (30 s) reenviaba la notificación
- // push y refrescaba el timestamp de la alerta. Solo se emite cuando
- // la versión observada o la de referencia cambian.
- key := p.Version + "|" + ref
- l.mu.Lock()
- unchanged := l.agentOutdatedKey[cfg.ID] == key
- if !unchanged {
- l.agentOutdatedKey[cfg.ID] = key
- }
- l.mu.Unlock()
- if unchanged {
- return
- }
- l.engine.EmitOrUpdate(AlertEvent{
- ID: fmt.Sprintf("alert-agent-outdated-%s", cfg.ID),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "warn",
- Title: "Agent outdated on " + name,
- Description: fmt.Sprintf("%s pushes version %s; the latest available for the %s agent is %s", name, p.Version, kindLabel, ref),
- Hint: alerts.HintFor(alerts.HintAgentOutdated),
- Type: alerts.HintAgentOutdated,
- Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
- Time: "just now", RouterID: cfg.ID,
- })
- } else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
- l.mu.Lock()
- delete(l.agentOutdatedAlerted, cfg.ID)
- l.mu.Unlock()
- // #833: la alerta de desactualizado DESAPARECE del feed al
- // actualizarse el agente (además del aviso ok de recuperación, que
- // solo se emite cuando el flag en memoria estaba activo).
- l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
- l.mu.Lock()
- delete(l.agentOutdatedKey, cfg.ID)
- l.mu.Unlock()
- if alerted {
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "ok",
- Title: "Agent updated on " + name,
- Description: fmt.Sprintf("%s now pushes version %s of %s", name, p.Version, kindLabel),
- Type: alerts.TypeAgentUpdated,
- Vars: map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
- // #1349: el evento de cierre referencia al que resuelve
- // (conservado en el log marcado, no borrado).
- Resolves: []string{fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- }
- }
|