| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280 |
- // payload.go — wire format de POST /api/ingest/agent (SPEC-AGENTE-PILOTO §1).
- // `data` lleva los shapes PARSEADOS de las sondas de este package (los mismos
- // que produce el sondeo SSH de internal/adapters/openwrt.go), para que el
- // pipeline del servidor (snapshot → SSE → persistencia) no cambie.
- package probe
- // Payload es el cuerpo JSON único que el agente empuja cada intervalo.
- type Payload struct {
- Router string `json:"router"` // slug del equipo (token agent.token.<slug>)
- Ts int64 `json:"ts"` // unix SEGUNDOS de la muestra
- Version string `json:"version"` // versión del agente (la muestra GET /api/agents)
- // Kind declara el tipo de pusher (#288): "" y "native" = agente nativo
- // netpulse-agent; "external" = pusher externo (scraper de un switch
- // gestionado, integración de terceros). El server lo usa para la UI y
- // para escalar ventanas de frescura.
- Kind string `json:"kind,omitempty"`
- // Interval declara la cadencia de push en SEGUNDOS (#288). 0 = default
- // del agente nativo (~30 s). Un pusher externo que empuja cada 5 min
- // declara 300 y el server amplía su TTL a 3x ese intervalo.
- Interval int `json:"interval,omitempty"`
- // PanelPort: the port the embedder's own web panel listens on, so
- // anything linking to it does not have to guess. 0 = no panel, or an
- // agent that does not report one.
- PanelPort int `json:"panelPort,omitempty"`
- Data PayloadData `json:"data"`
- }
- // PayloadData agrupa las secciones del tier rápido. Punteros/mapas nil =
- // sonda fallida en este push (el servidor conserva el último dato bueno,
- // mismo anti-parpadeo que el pipeline SSH).
- type PayloadData struct {
- System *SystemData `json:"system,omitempty"`
- Wireless *WirelessData `json:"wireless,omitempty"`
- DHCP *DHCPData `json:"dhcp,omitempty"`
- FDB *FDBData `json:"fdb,omitempty"`
- // Arp: MAC → IPv4 de la tabla ARP del equipo (/proc/net/arp, #377).
- // Resuelve IPs donde el DHCP no está en el equipo sondeado (APs tontos
- // con el dnsmasq en otro router): cualquier router de la flota que
- // enrute la LAN conoce el mapa completo.
- Arp map[string]string `json:"arp,omitempty"`
- // ArpDevs: MAC -> interfaz donde el kernel tiene la entrada ARP (#1485).
- // Permite al servidor distinguir el ARP aprendido en el puerto WAN (el
- // primer salto del enlace, ONT/modem en bridge) del de la LAN. Un agente
- // antiguo lo omite y el servidor no atribuye nada al lado WAN.
- ArpDevs map[string]string `json:"arpDevs,omitempty"`
- // ArpStale: the MACs of Arp whose neighbour entries are all unconfirmed
- // (STALE/FAILED/INCOMPLETE). Their address is still the best one known
- // for the host, but their presence in the table proves nothing: the
- // kernel keeps a stale neighbour long after the device has gone. An
- // older agent omits this, and the server then trusts the whole table as
- // it always did.
- ArpStale []string `json:"arpStale,omitempty"`
- Dawn *DawnData `json:"dawn,omitempty"` // Fase 14: DAWN roaming (solo si instalado; compat rollback)
- Usteer *UsteerData `json:"usteer,omitempty"` // usteer roaming (solo si instalado)
- // LuCI: etiquetas de puertos/VLANs del router (issue #258), si están
- // definidas en /etc/config/luci.
- LuCI *LuCILabels `json:"luci,omitempty"`
- // NetIf: contadores acumulados POR INTERFAZ de /proc/net/dev (issue
- // #305). El servidor calcula los rates por boca con el delta entre
- // payloads. nil = sonda fallida (conserva la última buena).
- NetIf map[string]IfCounters `json:"netIf,omitempty"`
- // Vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sonda
- // fallida o router sin bridge vlan filtering.
- Vlans []VlanPort `json:"vlans,omitempty"`
- // Lldp (#489): vecinos LLDP de lldpd. nil = sonda fallida en este push
- // (el server conserva el último dato bueno); Available=false = lldpd
- // no instalado (hint de UI).
- Lldp *LldpData `json:"lldp,omitempty"`
- // ClientBw (#551): tráfico por cliente desde nlbwmon del router. nil =
- // sonda fallida en este push; Available=false = nlbwmon no instalado
- // (el server usa entonces hostapd bytes por estación).
- ClientBw *ClientBwData `json:"clientBw,omitempty"`
- // Discovery: mDNS services and randomized MAC detection (#338).
- Discovery *DiscoveryData `json:"discovery,omitempty"`
- // MQTT (#832): el equipo se expone ÉL MISMO a Home Assistant por MQTT.
- // Lo rellena el embedder (p. ej. NetGrip, que ya habla MQTT con sus
- // propias entidades y comandos); nil = no aplica (agente standalone) u
- // omitido por el embedder; Enabled=false = informado pero apagado.
- MQTT *MQTTData `json:"mqtt,omitempty"`
- // Wan: estado del uplink (proto, IP pública, gateway, DNS y la boca por
- // la que sale). El servidor lo sondeaba por SSH solo en el gateway, vía
- // que no existe en un router agent_only: sin esto su panel de conexión
- // se queda vacío. nil = sonda fallida o router sin uplink (AP).
- Wan *WanInfo `json:"wan,omitempty"`
- // MultiWan: the uplink policy the router's own panel manages — which
- // connections exist, which one carries traffic, how the load is split.
- // Read-only here. nil = this router reports no multi-WAN, which is also
- // what an older agent sends.
- MultiWan *MultiWanInfo `json:"multiWan,omitempty"`
- }
- // MQTTData: exposición propia del equipo a Home Assistant por MQTT (#832).
- // El servidor la usa para no duplicar el dispositivo por router: quien se
- // expone solo es el propio equipo.
- type MQTTData struct {
- Enabled bool `json:"enabled"`
- Node string `json:"node,omitempty"` // id de nodo de sus topics (p. ej. el hostname)
- }
- // SystemData: salud del equipo + tráfico + latencias.
- type SystemData struct {
- SysInfo *SysInfo `json:"sysinfo,omitempty"`
- Board *BoardInfo `json:"board,omitempty"`
- CPU *int `json:"cpu"` // null en la primera muestra (delta /proc/stat)
- Temp *int `json:"temp"` // null si no hay thermal zone
- RxBps *float64 `json:"rxBps"`
- TxBps *float64 `json:"txBps"`
- LatencyMs *float64 `json:"latencyMs"` // gateway: ping WAN; AP: ping al gateway
- LossPct *float64 `json:"lossPct"` // solo gateway (ping WAN)
- Backhaul string `json:"backhaul,omitempty"` // "cable"|"wifi" (ausente = desconocido)
- BridgeMAC string `json:"bridgeMac,omitempty"` // MAC de br-lan (uplinks/topología)
- // Flash and FirmwareAvailable let an external pusher report storage and
- // pending firmware without a vendor-specific server adapter. Both are
- // optional and remain empty when the source does not expose them.
- Flash string `json:"flash,omitempty"`
- FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
- }
- // WirelessData: clientes asociados + radios agregadas por banda.
- type WirelessData struct {
- Clients map[string]WirelessClient `json:"clients"` // {} = sin clientes; sección ausente = sonda fallida
- Radios []Radio `json:"radios"`
- // Scans: redes vecinas vistas por cada interfaz WiFi (Fase 18/#452).
- // nil/ausente = el scan no se pudo realizar en este push.
- Scans []ScanResult `json:"scans,omitempty"`
- // OwnBssids: BSSIDs de las interfaces AP de ESTE equipo (#1087), de
- // `iw dev`. El server los usa de semilla exacta para no contar las
- // propias redes como vecinas (casos con MAC aleatorizada o guest cuya
- // MAC no casa con routers.mac). nil con agentes antiguos.
- OwnBssids []OwnBSSID `json:"ownBssids,omitempty"`
- // SurveyRaw (#1214): salida cruda de `iw dev <iface> survey dump` con
- // marcadores "==IFACE==" por interfaz. El server la parsea con su
- // parser (adapters.ParseIwSurvey) para la lente "Ahora" en unidades
- // agent-only sin SSH. Vacío = sin survey fresco (throttle 5 min).
- SurveyRaw string `json:"surveyRaw,omitempty"`
- // UciWirelessRaw (#1450): salida cruda de `uci show wireless`. El server
- // la parsea con su parseUciWireless (misma función que el camino SSH)
- // para la vista 802.11r en flotas agent-only, donde no hay llave SSH.
- // Se refresca cada uciWirelessTTL pero va en TODOS los pushes (también
- // los de evento), para que el último payload del router nunca la pierda.
- // Vacío = no se pudo leer, o agente antiguo que no manda el campo: en
- // ambos casos el server degrada a "802.11r no disponible" sin error.
- UciWirelessRaw string `json:"uciWirelessRaw,omitempty"`
- }
- // GetRadios devuelve las radios agregadas tolerando un receptor nil (sección
- // wireless ausente): el hint WirelessSide del FDB las usa para etiquetar la
- // banda y no debe obligar a que la sonda de estaciones haya ido bien.
- func (w *WirelessData) GetRadios() []Radio {
- if w == nil {
- return nil
- }
- return w.Radios
- }
- // OwnBSSID: una interfaz AP local con su BSSID y SSID (#1087).
- type OwnBSSID struct {
- Iface string `json:"iface"`
- BSSID string `json:"bssid"` // MAC en mayúsculas
- SSID string `json:"ssid"` // puede estar vacío
- }
- // ScanResult es un AP vecino detectado por un scan pasivo.
- type ScanResult struct {
- Iface string `json:"iface"` // interfaz que hizo el scan, p. ej. wlan0
- BSSID string `json:"bssid"` // MAC del AP vecino
- SSID string `json:"ssid"` // ESSID (puede estar vacío)
- Channel int `json:"channel"` // canal numérico
- Freq int `json:"freq"` // frecuencia en MHz
- Signal int `json:"signal"` // dBm (negativo)
- // WidthMhz: ancho de canal anunciado (HT/VHT operation del scan, #1087).
- // 0 con agentes antiguos o BSS sin esos bloques: la UI usa 20 MHz de
- // fallback en ese caso.
- WidthMhz int `json:"widthMhz,omitempty"`
- }
- // DHCPData: leases ipv4 (mac en mayúsculas) + clientes GL.iNet.
- type DHCPData struct {
- Leases []DhcpLease `json:"leases"`
- // GlClients (GL.iNet): base de clientes del firmware, superset de las
- // leases — resuelve IPs de equipos con IP estática o sin lease en el
- // dnsmasq del Flint2 (issue #5 bug 1). Vacío/ausente en otros routers.
- GlClients []DhcpLease `json:"glClients,omitempty"`
- // Reservations: the `config host` entries of /etc/config/dhcp. Without
- // them a client with a fixed address of its own shows as a bare MAC,
- // because it never takes a lease to carry a hostname.
- Reservations []DhcpReservation `json:"reservations,omitempty"`
- }
- // FDBData: MAC aprendida → puerto del bridge + puertos ethernet.
- type FDBData struct {
- MACs map[string]string `json:"macs"` // {} = sin entradas; ausente = sonda fallida
- Ports []EthPort `json:"ports"`
- // WirelessSide (#rotMAC): MACs que el bridge aprende en puertos del lado
- // inalámbrico (wl0.1, wlan0, phy0-ap0…) pero que la tabla de estaciones NO
- // lista: MACs rotadas/aleatorias que siguen emitiendo tramas, clientes en
- // backhaul 4-address… Sin este hint el server solo las ve en el FDB del
- // gateway (tránsito bridged) y su fallback los dibuja como clientes
- // cableados. Valor = banda de la radio cuyo BSSID es la MAC del puerto
- // ("2.4 GHz"|"5 GHz"|"6 GHz"); sin radio que casar, la MAC se omite.
- WirelessSide map[string]string `json:"wirelessSide,omitempty"`
- }
- // DawnData: estado de DAWN (roaming/band-steering, Fase 14). Solo si DAWN
- // está instalado en el router. Trimmed del output de `ubus call dawn
- // get_network` — solo lo que la UI necesita (APs + señal por cliente).
- type DawnData struct {
- SSIDs map[string]DawnSSID `json:"ssids"`
- }
- // DawnSSID: por red WiFi (p. ej. "temiscira").
- type DawnSSID struct {
- APs []DawnAP `json:"aps"`
- Clients map[string]DawnClient `json:"clients"` // MAC upper → cliente
- }
- // DawnAP: un punto de acceso (BSSID) visto por DAWN en este SSID.
- type DawnAP struct {
- BSSID string `json:"bssid"`
- Hostname string `json:"hostname,omitempty"`
- Channel int `json:"channel"`
- Freq int `json:"freq"`
- Utilization int `json:"utilization"` // %
- Clients int `json:"clients"`
- Local bool `json:"local"` // true si es este router
- HT bool `json:"ht"`
- VHT bool `json:"vht"`
- }
- // DawnClient: un cliente WiFi visto por DAWN con señal al AP asociado.
- type DawnClient struct {
- BSSID string `json:"bssid"`
- Signal int `json:"signal"` // dBm (negativo)
- HT bool `json:"ht"`
- VHT bool `json:"vht"`
- }
- // UsteerData: estado de usteer (roaming/steering). Solo si usteer está
- // instalado en el router. Trimmed del output de `ubus call usteer local_info`,
- // `remote_info` y `connected_clients` — solo lo que la UI necesita (APs por
- // SSID + clientes con señal).
- type UsteerData struct {
- SSIDs map[string]UsteerSSID `json:"ssids"`
- }
- // UsteerSSID: por red WiFi (p. ej. "temiscira").
- type UsteerSSID struct {
- APs []UsteerAP `json:"aps"`
- Clients map[string]UsteerClient `json:"clients"` // MAC upper → cliente
- }
- // UsteerAP: un punto de acceso (local o remoto) visto por usteer en este SSID.
- type UsteerAP struct {
- BSSID string `json:"bssid"`
- Hostname string `json:"hostname,omitempty"` // IP del AP remoto; vacío si local
- Freq int `json:"freq"` // MHz (>= 5000 → 5 GHz)
- Load int `json:"load"` // utilización % reportada por usteer
- Clients int `json:"clients"` // n_assoc
- Local bool `json:"local"` // true si es este router
- }
- // UsteerClient: un cliente WiFi visto por usteer con señal al AP asociado.
- type UsteerClient struct {
- Signal int `json:"signal"` // dBm (negativo)
- }
- // DiscoveryData: mDNS service discovery + randomized MAC detection (#338).
- // Source: umdns browse on OpenWrt; falls back to parsing /tmp/umdns/ if
- // available. Best-effort: nil section if umdns is not installed.
- type DiscoveryData struct {
- // Services: hostname -> list of mDNS service types advertised.
- // e.g. {"Apple-TV._airplay._tcp.local": ["_airplay._tcp", "_raop._tcp"]}
- Services map[string][]string `json:"services,omitempty"`
- // HostByIP: IP -> hostname from mDNS PTR records. Helps resolve devices
- // that have no DHCP hostname.
- HostByIP map[string]string `json:"hostByIp,omitempty"`
- // RandomMACs: MACs detected as locally-administered (bit 1 of byte 0 set).
- // These are typically iOS/Android private WiFi addresses that rotate.
- RandomMACs []string `json:"randomMacs,omitempty"`
- }
|