| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248 |
- // 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 {
- rp := l.polledFromAgent(cfg, p)
- // #850 keeps serving cached data so the card never goes blank,
- // but a pusher dead past the down-confirm window is not
- // "online": flag it so buildRouter reads offline while keeping
- // the last readings. Same window as the agent-down alert, so
- // the status does not flap on a momentary blip.
- rp.agentStale = reg.StaleFor(slug, confirm)
- return true, rp
- }
- }
- }
- 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,
- })
- }
- }
- }
|