Просмотр исходного кода

feat(adapters): LLDP live — LldpNeighbors (lldpcli -f json), ErrLldpUnavailable cacheado 5 min, tier lento 45 s y detección de backhaul integrada en el sondeo (C2)

agent 4 месяцев назад
Родитель
Сommit
db2ce8be0e
2 измененных файлов с 367 добавлено и 26 удалено
  1. 136 26
      server-go/internal/adapters/live.go
  2. 231 0
      server-go/internal/adapters/lldp.go

+ 136 - 26
server-go/internal/adapters/live.go

@@ -9,6 +9,7 @@ import (
 	"context"
 	"database/sql"
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log"
 	"math"
@@ -73,6 +74,10 @@ type routerPolled struct {
 	brMac     string
 	latencyMs *float64
 	lossPct   *float64
+	// backhaul: "cable"|"wifi"|"" (desconocido → se omite en el contrato).
+	backhaul string
+	// lldp: vecinos LLDP del tier lento (nil = sin lldpd o sonda fallida).
+	lldp []LldpNeighbor
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -83,6 +88,25 @@ type extrasSnapshot struct {
 	fdb      map[string]string
 }
 
+// backhaulCacheTTL: el medio del uplink cambia muy raro; no se sondea cada 5 s.
+const backhaulCacheTTL = 5 * time.Minute
+
+// backhaulCacheEntry: resultado cacheado de la detección de uplink wifi
+// (value "" = desconocido/sonda fallida → el campo se omite).
+type backhaulCacheEntry struct {
+	value string
+	at    time.Time
+}
+
+// lldpCacheTTL: tier lento LLDP (45 s, como los extras cacheados).
+const lldpCacheTTL = 45 * time.Second
+
+// lldpCacheEntry: vecinos LLDP cacheados por router (nil = sin datos).
+type lldpCacheEntry struct {
+	neighbors []LldpNeighbor
+	at        time.Time
+}
+
 // Live es el Snapshotter del modo live.
 type Live struct {
 	cfg  *config.Config
@@ -94,16 +118,18 @@ type Live struct {
 	gatewayCfg *RouterConfig
 	clients    map[string]*OpenWrtClient
 
-	lastGood    map[string]*Router
-	lastStatus  map[string]string
-	boardCache  map[string]*BoardInfo
-	layoutCache map[string][]PortLayout
-	extrasCache map[string]*extrasSnapshot
-	lastPolled  map[string]*routerPolled
-	failCount   map[string]int
-	alerts      []AlertEvent
-	wgActive    map[string]bool
-	weakAlerted map[string]int64
+	lastGood      map[string]*Router
+	lastStatus    map[string]string
+	boardCache    map[string]*BoardInfo
+	layoutCache   map[string][]PortLayout
+	extrasCache   map[string]*extrasSnapshot
+	lastPolled    map[string]*routerPolled
+	failCount     map[string]int
+	alerts        []AlertEvent
+	wgActive      map[string]bool
+	weakAlerted   map[string]int64
+	backhaulCache map[string]backhaulCacheEntry
+	lldpCache     map[string]lldpCacheEntry
 
 	agStd *AdGuardClient
 	agGL  *AdGuardGlinetClient
@@ -121,18 +147,20 @@ type sfResult struct {
 // NewLive crea el adapter live (db puede ser nil en tests).
 func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool) *Live {
 	l := &Live{
-		cfg:         cfg,
-		db:          d,
-		pool:        pool,
-		lastGood:    map[string]*Router{},
-		lastStatus:  map[string]string{},
-		boardCache:  map[string]*BoardInfo{},
-		layoutCache: map[string][]PortLayout{},
-		extrasCache: map[string]*extrasSnapshot{},
-		lastPolled:  map[string]*routerPolled{},
-		failCount:   map[string]int{},
-		wgActive:    map[string]bool{},
-		weakAlerted: map[string]int64{},
+		cfg:           cfg,
+		db:            d,
+		pool:          pool,
+		lastGood:      map[string]*Router{},
+		lastStatus:    map[string]string{},
+		boardCache:    map[string]*BoardInfo{},
+		layoutCache:   map[string][]PortLayout{},
+		extrasCache:   map[string]*extrasSnapshot{},
+		lastPolled:    map[string]*routerPolled{},
+		failCount:     map[string]int{},
+		wgActive:      map[string]bool{},
+		weakAlerted:   map[string]int64{},
+		backhaulCache: map[string]backhaulCacheEntry{},
+		lldpCache:     map[string]lldpCacheEntry{},
 	}
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
@@ -208,6 +236,63 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.failCount, id)
 		}
 	}
+	for id := range l.backhaulCache {
+		if !ids[id] {
+			delete(l.backhaulCache, id)
+		}
+	}
+	for id := range l.lldpCache {
+		if !ids[id] {
+			delete(l.lldpCache, id)
+		}
+	}
+}
+
+// probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";
+// si no → "cable") con caché de 5 min: no se sondea cada tick. Error (router
+// sin wifi, ubus caído) → "" cacheado igualmente (el campo se omite y el
+// sondeo no se rompe).
+func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
+	l.mu.Lock()
+	e, ok := l.backhaulCache[routerID]
+	l.mu.Unlock()
+	if ok && time.Since(e.at) < backhaulCacheTTL {
+		return e.value
+	}
+	value := ""
+	if wifi, err := client.GetWirelessUplink(); err == nil {
+		value = "cable"
+		if wifi {
+			value = "wifi"
+		}
+	}
+	l.mu.Lock()
+	l.backhaulCache[routerID] = backhaulCacheEntry{value: value, at: time.Now()}
+	l.mu.Unlock()
+	return value
+}
+
+// probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
+// extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
+// sigue mandando, comportamiento actual intacto).
+func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) []LldpNeighbor {
+	l.mu.Lock()
+	e, ok := l.lldpCache[routerID]
+	l.mu.Unlock()
+	if ok && time.Since(e.at) < lldpCacheTTL {
+		return e.neighbors
+	}
+	neighbors, err := client.LldpNeighbors(ctx)
+	if err != nil {
+		if !errors.Is(err, ErrLldpUnavailable) {
+			log.Printf("[netpulse] LLDP %s: %v", routerID, err)
+		}
+		neighbors = nil
+	}
+	l.mu.Lock()
+	l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, at: time.Now()}
+	l.mu.Unlock()
+	return neighbors
 }
 
 // getAdguardClient: kv (GL.iNet) con fallback a .env (AGH estándar).
@@ -320,7 +405,7 @@ func (l *Live) metricsHistory(routerID, rang string) []histPoint {
 }
 
 // pollRouter sondea un router; error si está inalcanzable.
-func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
+func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
 	l.mu.Lock()
 	client := l.clients[cfg.ID]
 	gw := l.gatewayCfg
@@ -363,6 +448,10 @@ func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
 	radios := client.GetRadios()
 	fdb := client.GetBridgeFdb()
 	brMac := client.GetBridgeMac()
+	// Tier lento: backhaul (5 min) y vecinos LLDP (45 s), ambos cacheados y
+	// tolerantes a error (router sin wifi/lldpd → campo ausente, sin romper).
+	backhaul := l.probeBackhaul(cfg.ID, client)
+	lldp := l.probeLldp(ctx, cfg.ID, client)
 	if !hasBoard {
 		if b, err := client.GetBoard(); err == nil {
 			board = b
@@ -431,6 +520,7 @@ func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
 		uptimeSec: sysInfo.Uptime, net: net, leases: leases,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
+		backhaul: backhaul, lldp: lldp,
 	}, nil
 }
 
@@ -494,6 +584,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.brMac != "" {
 		r.MAC = p.brMac
 	}
+	if p.backhaul != "" {
+		r.Backhaul = p.backhaul
+	}
 	if p.board != nil {
 		r.Firmware = p.board.Release.Description
 	}
@@ -538,7 +631,7 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 }
 
 // pollAll sondea todos los routers en paralelo (Promise.allSettled).
-func (l *Live) pollAll() map[string]*routerPolled {
+func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	l.mu.Unlock()
@@ -554,7 +647,7 @@ func (l *Live) pollAll() map[string]*routerPolled {
 		wg.Add(1)
 		go func(i int, cfg RouterConfig) {
 			defer wg.Done()
-			p, err := l.pollRouter(cfg)
+			p, err := l.pollRouter(ctx, cfg)
 			results[i] = result{cfg, p, err}
 		}(i, cfg)
 	}
@@ -913,7 +1006,7 @@ func (l *Live) GetOverview(ctx context.Context) (*Overview, error) {
 }
 
 func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
-	polled := l.pollAll()
+	polled := l.pollAll(ctx)
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	gw := l.gatewayCfg
@@ -1161,6 +1254,11 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		if neighbor != "" {
 			port.ConnectedTo = routerByMac[neighbor]
 			port.Detail = "enlace entre routers"
+			// El vecino además se anuncia por LLDP → el frontend puede
+			// mostrar el sufijo "· LLDP" en la etiqueta del uplink (C2).
+			if nb := lldpNeighborOnPort(p.lldp, port.ID); nb != nil {
+				port.Detail = "enlace entre routers · LLDP"
+			}
 			enriched = append(enriched, port)
 			continue
 		}
@@ -1185,6 +1283,18 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		}
 		// 3) Varios: el vecino es un switch/hub
 		if len(all) > 1 {
+			// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
+			// es mejor pista que el hostname DHCP.
+			if nb := lldpNeighborOnPort(p.lldp, port.ID); nb != nil && nb.displayName() != "" {
+				port.ConnectedTo = nb.displayName()
+				if nb.Mgmt != "" {
+					port.Detail = nb.Mgmt + " · LLDP"
+				} else {
+					port.Detail = "LLDP"
+				}
+				enriched = append(enriched, port)
+				continue
+			}
 			infraMac := ""
 			for _, mac := range all {
 				if le, ok := leaseMap[mac]; ok && le.Hostname != "" {

+ 231 - 0
server-go/internal/adapters/lldp.go

@@ -0,0 +1,231 @@
+// lldp.go — Vecinos LLDP live (contrato C2, SPEC Fase 5): sonda SSH
+// `lldpcli -f json show neighbors` con timeout corto, error tipado
+// ErrLldpUnavailable cuando lldpd no está instalado (cacheado ≥5 min para no
+// martillear) y parseo defensivo del JSON (todos los campos opcionales; una
+// forma inesperada NUNCA debe romper el sondeo).
+package adapters
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"sort"
+	"strings"
+	"time"
+)
+
+// lldpTimeout: timeout corto de la sonda (≤5 s, contrato C2).
+const lldpTimeout = 5 * time.Second
+
+// lldpDownTTL: cuánto se cachea que lldpd NO está instalado (≥5 min, C2).
+const lldpDownTTL = 5 * time.Minute
+
+// ErrLldpUnavailable: lldpd no instalado en el router (lldpcli no existe:
+// exit 127 / "not found"). El caller lo trata como "sin datos LLDP", no como
+// fallo del router.
+var ErrLldpUnavailable = errors.New("lldpd no disponible")
+
+// LldpNeighbor es un vecino LLDP anunciado en un puerto local. Todos los
+// campos son opcionales en el anuncio; vacío = no anunciado.
+type LldpNeighbor struct {
+	Port       string   // puerto local que recibe el anuncio ("lan3"…)
+	ChassisMac string   // id del chasis tipo mac (mayúsculas)
+	Chassis    string   // nombre del chasis (o id si no hay nombre)
+	Mgmt       string   // primera mgmt-ip anunciada
+	Caps       []string // capacidades enabled ("Bridge", "Router", "Wlan"…)
+	PortDesc   string   // descripción del puerto remoto
+}
+
+// info construye el LldpInfo del contrato (Caps unidas, como la demo).
+func (n LldpNeighbor) info() *LldpInfo {
+	return &LldpInfo{
+		Chassis:  n.Chassis,
+		Mgmt:     n.Mgmt,
+		Caps:     strings.Join(n.Caps, ", "),
+		PortDesc: n.PortDesc,
+	}
+}
+
+// displayName: nombre del chasis o, en su defecto, su id (MAC).
+func (n LldpNeighbor) displayName() string {
+	if n.Chassis != "" {
+		return n.Chassis
+	}
+	return n.ChassisMac
+}
+
+// LldpNeighbors: vecinos LLDP del router (contrato C2). Si lldpcli no existe
+// devuelve ErrLldpUnavailable y cachea la indisponibilidad lldpDownTTL.
+func (c *OpenWrtClient) LldpNeighbors(ctx context.Context) ([]LldpNeighbor, error) {
+	if time.Now().Before(c.lldpDownUntil) {
+		return nil, ErrLldpUnavailable
+	}
+	out, err := c.pool.RunCtx(ctx, c.Host, "lldpcli -f json show neighbors", lldpTimeout)
+	if err != nil {
+		if isLldpUnavailable(err) {
+			c.lldpDownUntil = time.Now().Add(lldpDownTTL)
+			return nil, ErrLldpUnavailable
+		}
+		return nil, err
+	}
+	neighbors, perr := parseLldpNeighbors([]byte(out))
+	if perr != nil {
+		// Salida no JSON (p.ej. mensaje de error de lldpcli con exit 0):
+		// no es "no instalado", se reintenta en el próximo tick lento.
+		return nil, perr
+	}
+	return neighbors, nil
+}
+
+// isLldpUnavailable: el comando no existe en el router (exit 127 del shell,
+// "not found" en el mensaje…). Cualquier otro fallo (red, lldpd parado con
+// lldpcli instalado) NO es indisponibilidad cacheable.
+func isLldpUnavailable(err error) bool {
+	if err == nil {
+		return false
+	}
+	msg := err.Error()
+	return strings.Contains(msg, "status 127") || strings.Contains(msg, "not found")
+}
+
+// parseLldpNeighbors parsea `lldpcli -f json show neighbors`:
+//
+//	{"lldp":{"interface":[{"name","chassis":{<nombre>:{id{type,value},descr,
+//	  mgmt-ip,capability[]}},"port":{id{type,value},descr}}]}}
+//
+// Defensivo: campos ausentes o de tipo inesperado se ignoran (best-effort de
+// encoding/json rellena lo compatible); interface también se acepta como
+// mapa nombre→objeto (versiones viejas de lldpd). Error solo si la raíz no
+// es JSON válido.
+func parseLldpNeighbors(data []byte) ([]LldpNeighbor, error) {
+	var root struct {
+		Lldp struct {
+			Ifaces json.RawMessage `json:"interface"`
+		} `json:"lldp"`
+	}
+	if err := json.Unmarshal(data, &root); err != nil {
+		return nil, err
+	}
+	if len(root.Lldp.Ifaces) == 0 || string(root.Lldp.Ifaces) == "null" {
+		return []LldpNeighbor{}, nil
+	}
+	var entries []json.RawMessage
+	if err := json.Unmarshal(root.Lldp.Ifaces, &entries); err != nil {
+		// Forma mapa: {"lan3": {...}, "lan1": {...}} (lldpd viejo)
+		var byName map[string]json.RawMessage
+		if err2 := json.Unmarshal(root.Lldp.Ifaces, &byName); err2 != nil {
+			// Ni array ni mapa: forma desconocida → sin datos, no error
+			return []LldpNeighbor{}, nil
+		}
+		names := make([]string, 0, len(byName))
+		for name := range byName {
+			names = append(names, name)
+		}
+		sort.Strings(names)
+		for _, name := range names {
+			entries = append(entries, byName[name])
+		}
+	}
+	neighbors := make([]LldpNeighbor, 0, len(entries))
+	for _, raw := range entries {
+		neighbors = append(neighbors, parseLldpEntry(raw))
+	}
+	return neighbors, nil
+}
+
+// parseLldpEntry parsea una entrada de interface (nunca entra en pánico:
+// los Unmarshal secundarios ignoran el error a propósito — best-effort).
+func parseLldpEntry(raw json.RawMessage) LldpNeighbor {
+	var e struct {
+		Name    string                     `json:"name"`
+		Chassis map[string]json.RawMessage `json:"chassis"`
+		Port    json.RawMessage            `json:"port"`
+	}
+	if json.Unmarshal(raw, &e) != nil {
+		return LldpNeighbor{}
+	}
+	n := LldpNeighbor{Port: e.Name}
+
+	// Chassis: mapa nombre→datos (normalmente uno; el primero ordenado)
+	keys := make([]string, 0, len(e.Chassis))
+	for k := range e.Chassis {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	if len(keys) > 0 {
+		n.Chassis = keys[0]
+		var ch struct {
+			ID struct {
+				Type  string `json:"type"`
+				Value string `json:"value"`
+			} `json:"id"`
+			MgmtIP json.RawMessage `json:"mgmt-ip"`
+			Caps   []struct {
+				Type    string `json:"type"`
+				Enabled bool   `json:"enabled"`
+			} `json:"capability"`
+		}
+		_ = json.Unmarshal(e.Chassis[keys[0]], &ch) // best-effort (ver cabecera)
+		if ch.ID.Type == "mac" {
+			n.ChassisMac = strings.ToUpper(ch.ID.Value)
+		}
+		if n.Chassis == "" {
+			n.Chassis = ch.ID.Value
+		}
+		n.Mgmt = firstMgmtIP(ch.MgmtIP)
+		for _, cap := range ch.Caps {
+			if cap.Enabled && cap.Type != "" {
+				n.Caps = append(n.Caps, cap.Type)
+			}
+		}
+	}
+
+	// Puerto remoto: descr; si no, el id
+	if len(e.Port) > 0 {
+		var p struct {
+			ID struct {
+				Value string `json:"value"`
+			} `json:"id"`
+			Descr string `json:"descr"`
+		}
+		if json.Unmarshal(e.Port, &p) == nil {
+			n.PortDesc = p.Descr
+			if n.PortDesc == "" {
+				n.PortDesc = p.ID.Value
+			}
+		}
+	}
+	return n
+}
+
+// firstMgmtIP: mgmt-ip viene como array (lldpd actual) o string suelto.
+func firstMgmtIP(raw json.RawMessage) string {
+	if len(raw) == 0 || string(raw) == "null" {
+		return ""
+	}
+	var list []string
+	if err := json.Unmarshal(raw, &list); err == nil {
+		for _, ip := range list {
+			if ip != "" {
+				return ip
+			}
+		}
+		return ""
+	}
+	var single string
+	if err := json.Unmarshal(raw, &single); err == nil {
+		return single
+	}
+	return ""
+}
+
+// lldpNeighborOnPort: vecino anunciado en un puerto local concreto (nil si
+// ninguno). Para el enriquecimiento de bocas del detalle ("· LLDP").
+func lldpNeighborOnPort(neighbors []LldpNeighbor, port string) *LldpNeighbor {
+	for i := range neighbors {
+		if neighbors[i].Port == port {
+			return &neighbors[i]
+		}
+	}
+	return nil
+}