| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732 |
- // openwrt.go — Cliente live para routers OpenWrt / GL.iNet (port de
- // src/adapters/openwrt.js, SPEC §7.2):
- //
- // 1. ubus JSON-RPC sobre HTTP (POST http://<host>/ubus, session login con
- // token cacheado y un solo re-login ante sesión caducada).
- // 2. Fallback SSH con pool persistente (sshpool.go; equivalente al
- // ControlMaster del JS).
- //
- // Comandos y parseo literales del JS; timeouts cortos y errores controlados:
- // el caller (live) marca el router offline y sigue con el resto.
- package adapters
- import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/agent/probe"
- )
- const (
- ubusHTTPTimeout = 4 * time.Second
- iwinfoTimeout = 8 * time.Second
- // radiosTTL (#368/#373, paridad con el agente): el resumen de radios
- // (canal/htmode/txpower) apenas cambia; cachearlo evita correr iwinfo en
- // cada poll de 5 s del server contra APs de bajas prestaciones (p.ej.
- // Archer A7 v5). El agente usa el mismo TTL desde el PR #373.
- radiosTTL = 5 * time.Minute
- )
- // poolRunner es el subconjunto de *SSHPool que usa OpenWrtClient (Run para
- // los comandos y RunCtx para LLDP). Permite inyectar un runner falso en
- // tests, igual que sshRunner para las funciones live sueltas.
- type poolRunner interface {
- Run(host, cmd string, timeout time.Duration) (string, error)
- RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error)
- }
- // OpenWrtClient es el cliente de un router (uno por router del config).
- type OpenWrtClient struct {
- Host string
- User string // para ubus HTTP (default root)
- Password string
- pool poolRunner
- // mu protege el estado mutable del cliente (sid, lastStat, lastNetDev,
- // lldpDownUntil): los handlers HTTP pueden sondear (p.ej. GetSurvey) en
- // paralelo con el poller.
- mu sync.Mutex
- sid string // sesión ubus HTTP cacheada
- lastStat *cpuSample // /proc/stat previo
- lastNetDev *netSample // /proc/net/dev previo
- // lastNetIf: /proc/net/dev previo POR INTERFAZ (contadores por boca,
- // issue #305). Acceso serializado por mu.
- lastNetIf *netIfSample
- // lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
- // martillear con un comando que no existe. Acceso serializado por mu.
- lldpDownUntil time.Time
- // radiosMu serializa la caché de radios (radiosCache/radiosAt): el
- // poller y los handlers HTTP pueden sondear el mismo cliente en paralelo.
- radiosMu sync.Mutex
- radiosCache []Radio // resumen por banda, refrescado cada radiosTTL
- radiosAt time.Time
- }
- type cpuSample struct{ total, idleAll float64 }
- type netSample struct {
- rx, tx float64
- at time.Time
- }
- type netIfSample struct {
- at time.Time
- ifaces map[string]probe.IfCounters
- }
- // Aliases a los shapes compartidos de agent/probe: el agente nativo parsea
- // LOCALMENTE con el mismo package (misma fuente de verdad) y empuja esos
- // shapes al endpoint de ingesta (SPEC-AGENTE-PILOTO §1-2).
- type (
- SysInfo = probe.SysInfo
- BoardInfo = probe.BoardInfo
- DhcpLease = probe.DhcpLease
- WirelessClient = probe.WirelessClient
- PortState = probe.PortState
- PortLayout = probe.PortLayout
- VlanPort = probe.VlanPort
- MultiWanInfo = probe.MultiWanInfo
- WanUplink = probe.WanUplink
- VlanEntry = probe.VlanEntry
- DhcpReservation = probe.DhcpReservation
- )
- // NewOpenWrtClient crea el cliente de un router.
- func NewOpenWrtClient(cfg RouterConfig, pool poolRunner, user, password string) *OpenWrtClient {
- if user == "" {
- user = "root"
- }
- // Host aquí es el destino `host:port` (#605) para el pool SSH.
- return &OpenWrtClient{Host: cfg.SSHAddr(), User: user, Password: password, pool: pool}
- }
- // ---------------------------------------------------------------------------
- // Transporte ubus HTTP (JSON-RPC)
- // ---------------------------------------------------------------------------
- type ubusRPCError struct{ msg string }
- func (e *ubusRPCError) Error() string { return e.msg }
- // ubusHTTPRpc: POST /ubus; devuelve result[1] si result[0] == 0.
- func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (json.RawMessage, error) {
- if params == nil {
- params = map[string]any{}
- }
- body, _ := json.Marshal(map[string]any{
- "jsonrpc": "2.0", "id": 1, "method": "call",
- "params": []any{sid, object, method, params},
- })
- ctx, cancel := context.WithTimeout(context.Background(), ubusHTTPTimeout)
- defer cancel()
- req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.Host+"/ubus", bytes.NewReader(body))
- if err != nil {
- return nil, err
- }
- req.Header.Set("Content-Type", "application/json")
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
- if err != nil {
- return nil, err
- }
- if res.StatusCode != 200 {
- return nil, &ubusRPCError{fmt.Sprintf("ubus HTTP %d", res.StatusCode)}
- }
- var rpc struct {
- Error json.RawMessage `json:"error"`
- Result json.RawMessage `json:"result"`
- }
- if err := json.Unmarshal(data, &rpc); err != nil {
- return nil, &ubusRPCError{"ubus: respuesta no JSON"}
- }
- if len(rpc.Error) > 0 && string(rpc.Error) != "null" {
- return nil, &ubusRPCError{"ubus RPC error: " + string(rpc.Error)}
- }
- // ubus devuelve [exitCode, payload]
- var result []json.RawMessage
- if err := json.Unmarshal(rpc.Result, &result); err != nil || len(result) != 2 {
- return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
- }
- var code int
- if err := json.Unmarshal(result[0], &code); err != nil || code != 0 {
- return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
- }
- return result[1], nil
- }
- // ubusLogin: session login con sid '0'×32 → ubus_rpc_session.
- func (c *OpenWrtClient) ubusLogin() error {
- payload, err := c.ubusHTTPRpc("00000000000000000000000000000000", "session", "login",
- map[string]any{"username": c.User, "password": c.Password})
- if err != nil {
- return err
- }
- var res struct {
- Session string `json:"ubus_rpc_session"`
- }
- if err := json.Unmarshal(payload, &res); err != nil || res.Session == "" {
- return &ubusRPCError{"ubus login: sin ubus_rpc_session"}
- }
- c.sid = res.Session
- return nil
- }
- // UbusCall: ubus call con HTTP + login cacheado; un solo re-login si la
- // sesión caducó; fallback a SSH si HTTP no está disponible.
- func (c *OpenWrtClient) UbusCall(object, method string, params any) (json.RawMessage, error) {
- if params == nil {
- params = map[string]any{}
- }
- payload, err := func() (json.RawMessage, error) {
- if c.sid == "" {
- if err := c.ubusLogin(); err != nil {
- return nil, err
- }
- }
- payload, err := c.ubusHTTPRpc(c.sid, object, method, params)
- if err != nil {
- // Sesión caducada → un solo re-login
- c.sid = ""
- if lerr := c.ubusLogin(); lerr != nil {
- return nil, lerr
- }
- return c.ubusHTTPRpc(c.sid, object, method, params)
- }
- return payload, nil
- }()
- if err == nil {
- return payload, nil
- }
- // Fallback SSH: ubus call <object> <method> '<json>'
- paramsJSON, _ := json.Marshal(params)
- esc := strings.ReplaceAll(string(paramsJSON), `'`, `'\''`)
- out, serr := c.pool.Run(c.Host, fmt.Sprintf("ubus call %s %s '%s'", object, method, esc), 0)
- if serr != nil {
- return nil, serr
- }
- if !json.Valid([]byte(out)) {
- return nil, &ubusRPCError{"ubus ssh: respuesta no JSON"}
- }
- return json.RawMessage(out), nil
- }
- // ---------------------------------------------------------------------------
- // Sonda de sistema
- // ---------------------------------------------------------------------------
- // GetBoard: modelo, release, kernel → metadatos estáticos del router.
- func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
- raw, err := c.UbusCall("system", "board", nil)
- if err != nil {
- return nil, err
- }
- var b BoardInfo
- if err := json.Unmarshal(raw, &b); err != nil {
- return nil, err
- }
- return &b, nil
- }
- // GetSysInfo: uptime, memoria, load.
- func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
- raw, err := c.UbusCall("system", "info", nil)
- if err != nil {
- return nil, err
- }
- var s SysInfo
- if err := json.Unmarshal(raw, &s); err != nil {
- return nil, err
- }
- return &s, nil
- }
- // ---------------------------------------------------------------------------
- // CPU / temperatura / netdev / ping (SSH; parseo literal del JS)
- // ---------------------------------------------------------------------------
- // GetCPUPercent: CPU % por delta de /proc/stat. Primera muestra: nil.
- func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
- out, err := c.pool.Run(c.Host, probe.CmdProcStat, 0)
- if err != nil {
- return nil, err
- }
- cur, err := parseProcStat(out)
- if err != nil {
- return nil, err
- }
- prev := c.lastStat
- c.lastStat = &cur
- if prev == nil {
- return nil, nil
- }
- return probe.CPUPercent(probe.CPUSample{Total: prev.total, IdleAll: prev.idleAll},
- probe.CPUSample{Total: cur.total, IdleAll: cur.idleAll}), nil
- }
- // parseProcStat parsea "cpu user nice system idle iowait irq softirq ..."
- // (delega en el parseo compartido con el agente nativo).
- func parseProcStat(out string) (cpuSample, error) {
- s, err := probe.ParseProcStat(out)
- return cpuSample{total: s.Total, idleAll: s.IdleAll}, err
- }
- // GetTempC: °C del primer thermal zone disponible (nil si no hay).
- func (c *OpenWrtClient) GetTempC() (*int, error) {
- out, err := c.pool.Run(c.Host, probe.CmdTemp, 0)
- if err != nil {
- return nil, err
- }
- return probe.ParseTempC(out), nil
- }
- // NetDevBps es el resultado del delta de /proc/net/dev.
- type NetDevBps struct {
- RxBps *float64
- TxBps *float64
- }
- // GetNetDev: tráfico agregado por delta de /proc/net/dev (excluye lo,
- // bridges, ifb, wg, tun/tap para no duplicar contadores) + rates POR INTERFAZ
- // (issue #305, para las bocas del chasis). Una sola lectura de /proc/net/dev;
- // primera muestra: rates null.
- func (c *OpenWrtClient) GetNetDev() (*NetDevBps, map[string]probe.IfRate) {
- out, err := c.pool.Run(c.Host, probe.CmdNetDev, 0)
- if err != nil {
- return nil, nil
- }
- rx, tx := parseNetDev(out)
- curIf := probe.ParseNetDevIfaces(out)
- now := time.Now()
- c.mu.Lock()
- defer c.mu.Unlock()
- prev := c.lastNetDev
- c.lastNetDev = &netSample{rx: rx, tx: tx, at: now}
- prevIf := c.lastNetIf
- c.lastNetIf = &netIfSample{at: now, ifaces: curIf}
- res := &NetDevBps{}
- if prev != nil {
- res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
- }
- var rates map[string]probe.IfRate
- if prevIf != nil {
- rates = probe.IfRates(prevIf.ifaces, curIf, now.Sub(prevIf.at).Seconds())
- }
- return res, rates
- }
- // parseNetDev suma rx/tx de las interfaces físicas (compartido con el agente).
- func parseNetDev(out string) (rx, tx float64) {
- return probe.ParseNetDev(out)
- }
- // GetWanLatency: ping a internet (solo gateway) → latencia avg + pérdida.
- func (c *OpenWrtClient) GetWanLatency(target string) (latency *float64, loss *float64, err error) {
- if target == "" {
- target = "1.1.1.1"
- }
- out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingWan, target), 0)
- if err != nil {
- return nil, nil, err
- }
- latency, loss = probe.ParsePingSummary(out)
- return latency, loss, nil
- }
- // GetGatewayLatency: ping corto al gateway desde un AP (avg, redondeado).
- func (c *OpenWrtClient) GetGatewayLatency(gatewayHost string) (*float64, error) {
- out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingGateway, gatewayHost), 0)
- if err != nil {
- return nil, err
- }
- latency, _ := probe.ParsePingSummary(out)
- return latency, nil
- }
- // ---------------------------------------------------------------------------
- // Clientes (DHCP + wireless)
- // ---------------------------------------------------------------------------
- // GetDhcpLeases: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases.
- func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
- raw, err := c.UbusCall("dhcp", "ipv4leases", nil)
- if err == nil {
- if leases, perr := probe.ParseDhcpUbus(raw); perr == nil {
- return leases
- }
- }
- out, serr := c.pool.Run(c.Host, probe.CmdDhcpFile, 0)
- if serr != nil {
- return []DhcpLease{}
- }
- return parseDhcpLeasesFile(out)
- }
- // GetWanInfo: estado del uplink (issue #276). Via ubus network.interface
- // dump, que trae todas las interfaces y deja elegir la que lleva internet
- // por su ruta por defecto en vez de por llamarse "wan" (un PPPoE puede
- // llamarse de cualquier forma, y el nombre "wan" puede ser un módem ocioso).
- // Cae al status de la interfaz "wan" con los ubus antiguos; si el router no
- // tiene ninguna (AP), devuelve WanInfo vacío.
- func (c *OpenWrtClient) GetWanInfo() probe.WanInfo {
- if raw, err := c.UbusCall("network.interface", "dump", nil); err == nil {
- if info := probe.ParseWanStatus(raw); info.Proto != "" || info.IP != "" || info.Gateway != "" {
- return info
- }
- }
- raw, err := c.UbusCall("network.interface.wan", "status", nil)
- if err == nil {
- return probe.ParseWanStatus(raw)
- }
- return probe.WanInfo{}
- }
- // GetDhcpReservations: the `config host` entries of /etc/config/dhcp, for
- // the routers polled over SSH (the agent sends them in its payload). Error
- // or no entries → empty, and clients keep falling back to their MAC.
- func (c *OpenWrtClient) GetDhcpReservations() []DhcpReservation {
- out, err := c.pool.Run(c.Host, probe.CmdDhcpReservations, 0)
- if err != nil {
- return nil
- }
- return probe.ParseDhcpReservations(out)
- }
- // GetGlClients: base de clientes del firmware GL.iNet (`ubus call gl-clients
- // list`). SUPERSET de dhcp.leases: incluye equipos con IP estática o sin
- // lease que el dnsmasq del Flint2 no lista. En routers sin el objeto ubus
- // gl-clients devuelve vacío (la salida del comando es vacía) — el caller lo
- // usa solo para enriquecer IPs de dispositivos ya conocidos, nunca para
- // crearlos (issue #5 bug 1).
- func (c *OpenWrtClient) GetGlClients() []DhcpLease {
- out, err := c.pool.Run(c.Host, probe.CmdGlClients, 0)
- if err != nil || strings.TrimSpace(out) == "" {
- return []DhcpLease{}
- }
- leases, perr := probe.ParseGlClients([]byte(out))
- if perr != nil {
- return []DhcpLease{}
- }
- return leases
- }
- // parseDhcpLeasesFile parsea /tmp/dhcp.leases:
- // <expiry> <mac> <ip> <hostname> <clientid>
- func parseDhcpLeasesFile(out string) []DhcpLease {
- return probe.ParseDhcpLeasesFile(out)
- }
- // GetWirelessClients: clientes wifi asociados (MAC → señal/banda). Port del
- // fix #373 (#368) al sondeo SSH: ubus hostapd get_clients primero (una
- // llamada ubus barata por AP, sin ucode/iwinfo), fallback de iwinfo combinado
- // en UNA pasada por interfaz, y como último recurso el par legacy. Vacío si
- // el router no expone ninguna fuente wireless.
- func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
- // 1. ubus hostapd get_clients (barato; APs con hostapd ubus moderno).
- // Autoritativo cuando hay objetos hostapd.* (incluso con 0 clientes: un
- // AP vacío no debe caer al fallback iwinfo en cada poll de 5 s del
- // server). Solo si ubus no expone objetos se baja al fallback.
- if out, err := c.pool.Run(c.Host, probe.CmdHostapdClients, iwinfoTimeout); err == nil && strings.Contains(out, "==AP==") {
- return probe.ParseHostapdClients(out)
- }
- // 2. iwinfo combinado en UNA pasada (info + assoclist juntos por interfaz;
- // emite clientes y radios). Mitad de spawns que el par legacy de abajo.
- // Las radios se cachean aunque no haya clientes (GetRadios no re-sondea).
- if out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout); err == nil {
- clients, radios := probe.ParseWirelessCombined(out)
- if len(radios) > 0 {
- c.setRadiosCache(radiosToAdapter(radios))
- }
- if len(clients) > 0 {
- return clients
- }
- }
- // 3. Último recurso: par legacy (equipos donde el combinado no aplica).
- out, err := c.pool.Run(c.Host, probe.CmdIwinfoAssoc, iwinfoTimeout)
- if err != nil {
- return map[string]WirelessClient{}
- }
- return parseWirelessClients(out)
- }
- // parseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
- func parseWirelessClients(out string) map[string]WirelessClient {
- return probe.ParseWirelessClients(out)
- }
- // GetRadios: radios activas por banda (canal/htmode/txpower + nº clientes).
- // Cacheadas radiosTTL (5 min): el resumen de radios apenas cambia y correr
- // CmdRadios (iwinfo) en CADA poll de 5 s del server quemaba CPU en APs de
- // bajas prestaciones (port #373 al sondeo SSH). Si la caché está fresca se
- // devuelve sin tocar el router; si caducó (o está vacía) se refresca.
- func (c *OpenWrtClient) GetRadios() []Radio {
- c.radiosMu.Lock()
- cached := c.radiosCache
- if len(cached) > 0 && time.Since(c.radiosAt) < radiosTTL {
- c.radiosMu.Unlock()
- return cached
- }
- c.radiosMu.Unlock()
- // Refresco. Prioridad al combinado (una pasada por interfaz) cuando ubus
- // no estuvo disponible para clientes: el propio comando emite las radios.
- out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout)
- if err == nil {
- if _, radios := probe.ParseWirelessCombined(out); len(radios) > 0 {
- rs := radiosToAdapter(radios)
- c.setRadiosCache(rs)
- return rs
- }
- }
- out, err = c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
- if err != nil {
- return []Radio{}
- }
- rs := parseRadios(out)
- if len(rs) > 0 {
- c.setRadiosCache(rs)
- }
- return rs
- }
- // setRadiosCache guarda el resumen de radios con su timestamp (best-effort:
- // no falla si la caché está vacía; el poller reintenta en el próximo ciclo).
- func (c *OpenWrtClient) setRadiosCache(rs []Radio) {
- if len(rs) == 0 {
- return
- }
- c.radiosMu.Lock()
- c.radiosCache = rs
- c.radiosAt = time.Now()
- c.radiosMu.Unlock()
- }
- // GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
- // interfaz STA activa/asociada en `ubus call network.wireless status`).
- // Error si el router no soporta la llamada (sin wifi → el caller omite el
- // campo backhaul, nunca rompe el sondeo).
- func (c *OpenWrtClient) GetWirelessUplink() (bool, error) {
- raw, err := c.UbusCall("network.wireless", "status", nil)
- if err != nil {
- return false, err
- }
- return parseWirelessUplink(raw)
- }
- // parseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
- // up e ifname asignado = asociada). Tolerante con radios/entradas raras.
- func parseWirelessUplink(raw json.RawMessage) (bool, error) {
- return probe.ParseWirelessUplink(raw)
- }
- // ---------------------------------------------------------------------------
- // Puertos
- // ---------------------------------------------------------------------------
- // GetPortStates: estado de interfaces desde /sys (SSH).
- func (c *OpenWrtClient) GetPortStates() []PortState {
- out, err := c.pool.Run(c.Host, probe.CmdPortStates, 0)
- if err != nil {
- return []PortState{}
- }
- return parsePortStates(out)
- }
- // parsePortStates parsea líneas "<name> <operstate> <speed>".
- func parsePortStates(out string) []PortState {
- return probe.ParsePortStates(out)
- }
- // GetPortLayout: layout canónico desde /etc/board.json (estático; lo cachea
- // el live). WAN normalizado a id 'wan'.
- func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
- out, err := c.pool.Run(c.Host, probe.CmdBoardJSON, 0)
- if err != nil {
- return nil, err
- }
- return parsePortLayout(out)
- }
- // parsePortLayout parsea board.json → [{id, name, label, role}].
- func parsePortLayout(out string) ([]PortLayout, error) {
- return probe.ParsePortLayout(out)
- }
- // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
- // fallback heurístico sin config. rates = contadores por iface (#305, de
- // GetNetDev; nil = sin stats). Devuelve []EthPort listo para el detalle.
- func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate, uplink string) []EthPort {
- states := c.GetPortStates()
- members := map[string]bool{}
- if len(layout) > 0 {
- // Miembros del bridge: si "wan" está en br-lan, este router es un AP
- brif, _ := c.pool.Run(c.Host, probe.CmdBrifMembers, 0)
- for _, l := range strings.Split(strings.TrimSpace(brif), "\n") {
- if l != "" {
- members[l] = true
- }
- }
- }
- return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates, uplink))
- }
- // ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
- func ethPortsToAdapter(in []probe.EthPort) []EthPort {
- f := func(v *float64) float64 {
- if v == nil {
- return 0
- }
- return *v
- }
- out := make([]EthPort, 0, len(in))
- for _, p := range in {
- ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up, Iface: p.Iface,
- RxBytes: p.RxBytes, TxBytes: p.TxBytes, RxErrs: p.RxErrs, TxErrs: p.TxErrs,
- RxBps: f(p.RxBps), TxBps: f(p.TxBps)}
- if p.Up {
- ep.Speed = p.Speed
- }
- if p.Sfp != nil {
- ep.Sfp = &SfpInfo{
- Temperature: p.Sfp.Temperature, Voltage: p.Sfp.Voltage,
- TxPower: p.Sfp.TxPower, RxPower: p.Sfp.RxPower,
- Vendor: p.Sfp.Vendor, PartNumber: p.Sfp.PartNumber,
- Present: p.Sfp.Present,
- }
- }
- out = append(out, ep)
- }
- return out
- }
- // naturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
- func naturalLess(a, b string) bool {
- return probe.NaturalLess(a, b)
- }
- // GetBridgeFdb: MAC aprendida → puerto (brctl showmacs + port_no).
- // Devuelve nil en error para que el anti-parpadeo de pollRouter conserve la
- // última lista buena en vez de sustituirla por un FDB vacío (#694).
- func (c *OpenWrtClient) GetBridgeFdb() map[string]string {
- out, err := c.pool.Run(c.Host, probe.CmdBridgeFDB, 0)
- if err != nil {
- return nil
- }
- return parseBridgeFdb(out)
- }
- // parseBridgeFdb parsea la salida ==PORTS==/==MACS== del JS.
- func parseBridgeFdb(out string) map[string]string {
- return probe.ParseBridgeFdb(out)
- }
- // GetBridgeMac: MAC del bridge br-lan (para reconocer uplinks).
- func (c *OpenWrtClient) GetBridgeMac() string {
- out, err := c.pool.Run(c.Host, probe.CmdBridgeMAC, 0)
- if err != nil {
- return ""
- }
- return strings.ToUpper(strings.TrimSpace(out))
- }
- // GetLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258), si el
- // router las define en /etc/config/luci. Best-effort: fichero sin secciones
- // → nil.
- func (c *OpenWrtClient) GetLuCILabels() *probe.LuCILabels {
- out, err := c.pool.Run(c.Host, probe.CmdLuCILabels, 0)
- if err != nil {
- return nil
- }
- return probe.ParseLuCILabels(out)
- }
- // GetBridgeVlans: VLANs del bridge (issue #315). La salida del kernel se
- // fusiona con la configuración (#1757): un router que segmenta con
- // subinterfaces 802.1Q contesta con todos los puertos en la VLAN 1 y las
- // VLANs reales solo están en `uci show network`. nil si ninguna de las dos
- // fuentes dice nada.
- func (c *OpenWrtClient) GetBridgeVlans() []probe.VlanPort {
- var kernel []probe.VlanPort
- if out, err := c.pool.Run(c.Host, probe.CmdBridgeVlan, 0); err == nil {
- kernel = probe.ParseBridgeVlan(out)
- }
- var declared []probe.VlanPort
- if out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0); err == nil {
- declared = probe.MergeVlanPorts(probe.ParseUciBridgeVlans(out), probe.ParseUciNetworkVlans(out))
- }
- ports := probe.MergeVlanPorts(kernel, declared)
- if len(ports) == 0 {
- return nil
- }
- return ports
- }
- // ---------------------------------------------------------------------------
- // Radios WiFi
- // ---------------------------------------------------------------------------
- // parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
- func parseRadios(out string) []Radio {
- return radiosToAdapter(probe.ParseRadios(out))
- }
- // radiosToAdapter convierte el shape compartido al Radio del contrato.
- func radiosToAdapter(in []probe.Radio) []Radio {
- out := make([]Radio, 0, len(in))
- for _, r := range in {
- out = append(out, Radio{Name: r.Name, Channel: r.Channel,
- WidthMhz: r.WidthMhz, PowerDbm: r.PowerDbm, Clients: r.Clients,
- NoiseDbm: r.NoiseDbm, BSSID: r.BSSID})
- }
- return out
- }
- // GetArp devuelve la tabla ARP del equipo (MAC→IP, #377). Fuente barata
- // para resolver IPs cuando el DHCP no es local.
- //
- // Reads `ip neigh` so the state of each entry comes with it, and returns the
- // MACs the kernel remembers without confirming (stale): their address is
- // still usable, but they are not evidence that the host is connected. Falls
- // back to /proc/net/arp, where no state is available and nothing is stale.
- // GetArp devuelve además MAC -> interfaz (#1485): con esa columna el poller
- // distingue el ARP del puerto WAN (primer salto del enlace) del de la LAN.
- func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool, devs map[string]string) {
- if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
- if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
- return m, st, probe.ParseIPNeighDevs(out)
- }
- }
- out, err := c.pool.Run(c.Host, probe.CmdProcArp, 0)
- if err != nil {
- return nil, nil, nil
- }
- return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
- }
- // GetNetworks: redes logicas que la unidad declara en UCI (#1889). Es la
- // misma lectura que alimenta las VLANs, asi que una unidad por SSH tambien
- // tiene la vista de redes; lo que no tiene son los contadores por interfaz.
- // nil si no hay datos, para que el anti-parpadeo conserve la ultima lista.
- func (c *OpenWrtClient) GetNetworks() []probe.UciNetwork {
- out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0)
- if err != nil {
- return nil
- }
- nets := probe.ParseUciNetworks(out)
- if len(nets) == 0 {
- return nil
- }
- return nets
- }
|