| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300 |
- // 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"
- "maps"
- "slices"
- "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). Las MAC
- // del payload deben venir ya en forma canónica: el push de agente las normaliza
- // (httpapi) y el beacon las construye así. Ingest no las reescribe
- // porque el beacon reutiliza partes del payload anterior, ya publicado.
- 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.clients se lee bajo l.mu: SetRouters lo reemplaza con el lock tomado.
- l.mu.Lock()
- cached := l.extrasCache[cfg.ID]
- client := l.clients[cfg.ID]
- l.mu.Unlock()
- out := &routerPolled{cfg: cfg, client: client, 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
- out.uplinkDevs = []string{w.Device, w.Port}
- } else if cached != nil {
- // Push event-driven (solo wireless + ARP): sin las interfaces del
- // uplink, sus vecinos volverían a salir como clientes cableados.
- out.uplinkDevs = cached.uplinkDevs
- }
- // 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
- }
- // Workloads (#2227): the nested guests a hypervisor-class pusher
- // reports. Structural census data like multiWan, so the same
- // anti-blink rule: a push without the section recycles the last good
- // one instead of emptying the panel.
- out.workloads = p.Data.Workloads
- if out.workloads == nil && cached != nil {
- out.workloads = cached.workloads
- }
- if out.workloads != nil {
- capped, dropped, truncated := capWorkloads(out.workloads)
- if dropped > 0 || truncated > 0 {
- workloadsWarn.Printf(cfg.ID, "capped the workloads census of %s: %d items dropped, %d fields shortened", cfg.ID, dropped, truncated)
- }
- out.workloads = capped
- }
- // 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
- }
- // Interfaces lógicas en ejecución (`ubus call network.interface dump`):
- // mismo anti-parpadeo que networks para que un push event-driven no
- // pierda las filas por red del panel de descubrimiento.
- if len(p.Data.NetIfaces) > 0 {
- out.netIfaces = p.Data.NetIfaces
- } else if cached != nil {
- out.netIfaces = cached.netIfaces
- }
- // #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.
- // fd.MACs es el mapa del payload publicado en AgentRegistry, que
- // otras goroutines leen (persistAgentState, el beacon periódico):
- // se reescribe sobre una copia, hecha solo si hay algo que cambiar.
- ids := map[string]bool{}
- for _, ep := range out.ports {
- ids[ep.ID] = true
- }
- if len(ids) > 0 {
- copied := false
- for mac, port := range fd.MACs {
- if port == "wan" || ids[port] {
- continue
- }
- if lan := "lan" + port; ids[lan] {
- if !copied {
- out.fdb = maps.Clone(fd.MACs)
- copied = true
- }
- 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 {
- // Copia: cached.ports es el slice de un routerPolled ya publicado en
- // lastPolled, e injectPortRates/appendVirtualPorts escriben en él. La
- // copia es segura porque solo buildOverview llega aquí y el singleflight
- // de GetOverview no deja que dos builds se solapen: applySNMPSurface, que
- // escribe en el slice cacheado, ya terminó en el build anterior.
- out.ports = slices.Clone(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, netIfaces: out.netIfaces, wifiNet: out.wifiNet, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
- clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan, uplinkDevs: out.uplinkDevs, workloads: out.workloads}
- 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{}
- }
- // #1818: el FDB de un bridge con batman-adv aprende las tramas LOOP
- // DETECT (BA:BE:xx:xx:xx:xx). Fuera antes de que el FDB alimente clientes,
- // topología o hints de rack.
- out.fdb = withoutBatadvBla(out.fdb)
- 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,
- })
- }
- }
- }
|