payload.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // payload.go — wire format de POST /api/ingest/agent (SPEC-AGENTE-PILOTO §1).
  2. // `data` lleva los shapes PARSEADOS de las sondas de este package (los mismos
  3. // que produce el sondeo SSH de internal/adapters/openwrt.go), para que el
  4. // pipeline del servidor (snapshot → SSE → persistencia) no cambie.
  5. package probe
  6. // Payload es el cuerpo JSON único que el agente empuja cada intervalo.
  7. type Payload struct {
  8. Router string `json:"router"` // slug del equipo (token agent.token.<slug>)
  9. Ts int64 `json:"ts"` // unix SEGUNDOS de la muestra
  10. Version string `json:"version"` // versión del agente (la muestra GET /api/agents)
  11. // Kind declara el tipo de pusher (#288): "" y "native" = agente nativo
  12. // netpulse-agent; "external" = pusher externo (scraper de un switch
  13. // gestionado, integración de terceros). El server lo usa para la UI y
  14. // para escalar ventanas de frescura.
  15. Kind string `json:"kind,omitempty"`
  16. // Interval declara la cadencia de push en SEGUNDOS (#288). 0 = default
  17. // del agente nativo (~30 s). Un pusher externo que empuja cada 5 min
  18. // declara 300 y el server amplía su TTL a 3x ese intervalo.
  19. Interval int `json:"interval,omitempty"`
  20. // PanelPort: the port the embedder's own web panel listens on, so
  21. // anything linking to it does not have to guess. 0 = no panel, or an
  22. // agent that does not report one.
  23. PanelPort int `json:"panelPort,omitempty"`
  24. Data PayloadData `json:"data"`
  25. }
  26. // PayloadData agrupa las secciones del tier rápido. Punteros/mapas nil =
  27. // sonda fallida en este push (el servidor conserva el último dato bueno,
  28. // mismo anti-parpadeo que el pipeline SSH).
  29. type PayloadData struct {
  30. System *SystemData `json:"system,omitempty"`
  31. Wireless *WirelessData `json:"wireless,omitempty"`
  32. DHCP *DHCPData `json:"dhcp,omitempty"`
  33. FDB *FDBData `json:"fdb,omitempty"`
  34. // Arp: MAC → IPv4 de la tabla ARP del equipo (/proc/net/arp, #377).
  35. // Resuelve IPs donde el DHCP no está en el equipo sondeado (APs tontos
  36. // con el dnsmasq en otro router): cualquier router de la flota que
  37. // enrute la LAN conoce el mapa completo.
  38. Arp map[string]string `json:"arp,omitempty"`
  39. // ArpDevs: MAC -> interfaz donde el kernel tiene la entrada ARP (#1485).
  40. // Permite al servidor distinguir el ARP aprendido en el puerto WAN (el
  41. // primer salto del enlace, ONT/modem en bridge) del de la LAN. Un agente
  42. // antiguo lo omite y el servidor no atribuye nada al lado WAN.
  43. ArpDevs map[string]string `json:"arpDevs,omitempty"`
  44. // ArpStale: the MACs of Arp whose neighbour entries are all unconfirmed
  45. // (STALE/FAILED/INCOMPLETE). Their address is still the best one known
  46. // for the host, but their presence in the table proves nothing: the
  47. // kernel keeps a stale neighbour long after the device has gone. An
  48. // older agent omits this, and the server then trusts the whole table as
  49. // it always did.
  50. ArpStale []string `json:"arpStale,omitempty"`
  51. Dawn *DawnData `json:"dawn,omitempty"` // Fase 14: DAWN roaming (solo si instalado; compat rollback)
  52. Usteer *UsteerData `json:"usteer,omitempty"` // usteer roaming (solo si instalado)
  53. // LuCI: etiquetas de puertos/VLANs del router (issue #258), si están
  54. // definidas en /etc/config/luci.
  55. LuCI *LuCILabels `json:"luci,omitempty"`
  56. // NetIf: contadores acumulados POR INTERFAZ de /proc/net/dev (issue
  57. // #305). El servidor calcula los rates por boca con el delta entre
  58. // payloads. nil = sonda fallida (conserva la última buena).
  59. NetIf map[string]IfCounters `json:"netIf,omitempty"`
  60. // Vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sonda
  61. // fallida o router sin bridge vlan filtering.
  62. Vlans []VlanPort `json:"vlans,omitempty"`
  63. // Lldp (#489): vecinos LLDP de lldpd. nil = sonda fallida en este push
  64. // (el server conserva el último dato bueno); Available=false = lldpd
  65. // no instalado (hint de UI).
  66. Lldp *LldpData `json:"lldp,omitempty"`
  67. // ClientBw (#551): tráfico por cliente desde nlbwmon del router. nil =
  68. // sonda fallida en este push; Available=false = nlbwmon no instalado
  69. // (el server usa entonces hostapd bytes por estación).
  70. ClientBw *ClientBwData `json:"clientBw,omitempty"`
  71. // Discovery: mDNS services and randomized MAC detection (#338).
  72. Discovery *DiscoveryData `json:"discovery,omitempty"`
  73. // MQTT (#832): el equipo se expone ÉL MISMO a Home Assistant por MQTT.
  74. // Lo rellena el embedder (p. ej. NetGrip, que ya habla MQTT con sus
  75. // propias entidades y comandos); nil = no aplica (agente standalone) u
  76. // omitido por el embedder; Enabled=false = informado pero apagado.
  77. MQTT *MQTTData `json:"mqtt,omitempty"`
  78. // Wan: estado del uplink (proto, IP pública, gateway, DNS y la boca por
  79. // la que sale). El servidor lo sondeaba por SSH solo en el gateway, vía
  80. // que no existe en un router agent_only: sin esto su panel de conexión
  81. // se queda vacío. nil = sonda fallida o router sin uplink (AP).
  82. Wan *WanInfo `json:"wan,omitempty"`
  83. // MultiWan: the uplink policy the router's own panel manages — which
  84. // connections exist, which one carries traffic, how the load is split.
  85. // Read-only here. nil = this router reports no multi-WAN, which is also
  86. // what an older agent sends.
  87. MultiWan *MultiWanInfo `json:"multiWan,omitempty"`
  88. }
  89. // MQTTData: exposición propia del equipo a Home Assistant por MQTT (#832).
  90. // El servidor la usa para no duplicar el dispositivo por router: quien se
  91. // expone solo es el propio equipo.
  92. type MQTTData struct {
  93. Enabled bool `json:"enabled"`
  94. Node string `json:"node,omitempty"` // id de nodo de sus topics (p. ej. el hostname)
  95. }
  96. // SystemData: salud del equipo + tráfico + latencias.
  97. type SystemData struct {
  98. SysInfo *SysInfo `json:"sysinfo,omitempty"`
  99. Board *BoardInfo `json:"board,omitempty"`
  100. CPU *int `json:"cpu"` // null en la primera muestra (delta /proc/stat)
  101. Temp *int `json:"temp"` // null si no hay thermal zone
  102. RxBps *float64 `json:"rxBps"`
  103. TxBps *float64 `json:"txBps"`
  104. LatencyMs *float64 `json:"latencyMs"` // gateway: ping WAN; AP: ping al gateway
  105. LossPct *float64 `json:"lossPct"` // solo gateway (ping WAN)
  106. Backhaul string `json:"backhaul,omitempty"` // "cable"|"wifi" (ausente = desconocido)
  107. BridgeMAC string `json:"bridgeMac,omitempty"` // MAC de br-lan (uplinks/topología)
  108. // Flash and FirmwareAvailable let an external pusher report storage and
  109. // pending firmware without a vendor-specific server adapter. Both are
  110. // optional and remain empty when the source does not expose them.
  111. Flash string `json:"flash,omitempty"`
  112. FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
  113. }
  114. // WirelessData: clientes asociados + radios agregadas por banda.
  115. type WirelessData struct {
  116. Clients map[string]WirelessClient `json:"clients"` // {} = sin clientes; sección ausente = sonda fallida
  117. Radios []Radio `json:"radios"`
  118. // Scans: redes vecinas vistas por cada interfaz WiFi (Fase 18/#452).
  119. // nil/ausente = el scan no se pudo realizar en este push.
  120. Scans []ScanResult `json:"scans,omitempty"`
  121. // OwnBssids: BSSIDs de las interfaces AP de ESTE equipo (#1087), de
  122. // `iw dev`. El server los usa de semilla exacta para no contar las
  123. // propias redes como vecinas (casos con MAC aleatorizada o guest cuya
  124. // MAC no casa con routers.mac). nil con agentes antiguos.
  125. OwnBssids []OwnBSSID `json:"ownBssids,omitempty"`
  126. // SurveyRaw (#1214): salida cruda de `iw dev <iface> survey dump` con
  127. // marcadores "==IFACE==" por interfaz. El server la parsea con su
  128. // parser (adapters.ParseIwSurvey) para la lente "Ahora" en unidades
  129. // agent-only sin SSH. Vacío = sin survey fresco (throttle 5 min).
  130. SurveyRaw string `json:"surveyRaw,omitempty"`
  131. // UciWirelessRaw (#1450): salida cruda de `uci show wireless`. El server
  132. // la parsea con su parseUciWireless (misma función que el camino SSH)
  133. // para la vista 802.11r en flotas agent-only, donde no hay llave SSH.
  134. // Se refresca cada uciWirelessTTL pero va en TODOS los pushes (también
  135. // los de evento), para que el último payload del router nunca la pierda.
  136. // Vacío = no se pudo leer, o agente antiguo que no manda el campo: en
  137. // ambos casos el server degrada a "802.11r no disponible" sin error.
  138. UciWirelessRaw string `json:"uciWirelessRaw,omitempty"`
  139. }
  140. // GetRadios devuelve las radios agregadas tolerando un receptor nil (sección
  141. // wireless ausente): el hint WirelessSide del FDB las usa para etiquetar la
  142. // banda y no debe obligar a que la sonda de estaciones haya ido bien.
  143. func (w *WirelessData) GetRadios() []Radio {
  144. if w == nil {
  145. return nil
  146. }
  147. return w.Radios
  148. }
  149. // OwnBSSID: una interfaz AP local con su BSSID y SSID (#1087).
  150. type OwnBSSID struct {
  151. Iface string `json:"iface"`
  152. BSSID string `json:"bssid"` // MAC en mayúsculas
  153. SSID string `json:"ssid"` // puede estar vacío
  154. }
  155. // ScanResult es un AP vecino detectado por un scan pasivo.
  156. type ScanResult struct {
  157. Iface string `json:"iface"` // interfaz que hizo el scan, p. ej. wlan0
  158. BSSID string `json:"bssid"` // MAC del AP vecino
  159. SSID string `json:"ssid"` // ESSID (puede estar vacío)
  160. Channel int `json:"channel"` // canal numérico
  161. Freq int `json:"freq"` // frecuencia en MHz
  162. Signal int `json:"signal"` // dBm (negativo)
  163. // WidthMhz: ancho de canal anunciado (HT/VHT operation del scan, #1087).
  164. // 0 con agentes antiguos o BSS sin esos bloques: la UI usa 20 MHz de
  165. // fallback en ese caso.
  166. WidthMhz int `json:"widthMhz,omitempty"`
  167. }
  168. // DHCPData: leases ipv4 (mac en mayúsculas) + clientes GL.iNet.
  169. type DHCPData struct {
  170. Leases []DhcpLease `json:"leases"`
  171. // GlClients (GL.iNet): base de clientes del firmware, superset de las
  172. // leases — resuelve IPs de equipos con IP estática o sin lease en el
  173. // dnsmasq del Flint2 (issue #5 bug 1). Vacío/ausente en otros routers.
  174. GlClients []DhcpLease `json:"glClients,omitempty"`
  175. // Reservations: the `config host` entries of /etc/config/dhcp. Without
  176. // them a client with a fixed address of its own shows as a bare MAC,
  177. // because it never takes a lease to carry a hostname.
  178. Reservations []DhcpReservation `json:"reservations,omitempty"`
  179. }
  180. // FDBData: MAC aprendida → puerto del bridge + puertos ethernet.
  181. type FDBData struct {
  182. MACs map[string]string `json:"macs"` // {} = sin entradas; ausente = sonda fallida
  183. Ports []EthPort `json:"ports"`
  184. // WirelessSide (#rotMAC): MACs que el bridge aprende en puertos del lado
  185. // inalámbrico (wl0.1, wlan0, phy0-ap0…) pero que la tabla de estaciones NO
  186. // lista: MACs rotadas/aleatorias que siguen emitiendo tramas, clientes en
  187. // backhaul 4-address… Sin este hint el server solo las ve en el FDB del
  188. // gateway (tránsito bridged) y su fallback los dibuja como clientes
  189. // cableados. Valor = banda de la radio cuyo BSSID es la MAC del puerto
  190. // ("2.4 GHz"|"5 GHz"|"6 GHz"); sin radio que casar, la MAC se omite.
  191. WirelessSide map[string]string `json:"wirelessSide,omitempty"`
  192. }
  193. // DawnData: estado de DAWN (roaming/band-steering, Fase 14). Solo si DAWN
  194. // está instalado en el router. Trimmed del output de `ubus call dawn
  195. // get_network` — solo lo que la UI necesita (APs + señal por cliente).
  196. type DawnData struct {
  197. SSIDs map[string]DawnSSID `json:"ssids"`
  198. }
  199. // DawnSSID: por red WiFi (p. ej. "temiscira").
  200. type DawnSSID struct {
  201. APs []DawnAP `json:"aps"`
  202. Clients map[string]DawnClient `json:"clients"` // MAC upper → cliente
  203. }
  204. // DawnAP: un punto de acceso (BSSID) visto por DAWN en este SSID.
  205. type DawnAP struct {
  206. BSSID string `json:"bssid"`
  207. Hostname string `json:"hostname,omitempty"`
  208. Channel int `json:"channel"`
  209. Freq int `json:"freq"`
  210. Utilization int `json:"utilization"` // %
  211. Clients int `json:"clients"`
  212. Local bool `json:"local"` // true si es este router
  213. HT bool `json:"ht"`
  214. VHT bool `json:"vht"`
  215. }
  216. // DawnClient: un cliente WiFi visto por DAWN con señal al AP asociado.
  217. type DawnClient struct {
  218. BSSID string `json:"bssid"`
  219. Signal int `json:"signal"` // dBm (negativo)
  220. HT bool `json:"ht"`
  221. VHT bool `json:"vht"`
  222. }
  223. // UsteerData: estado de usteer (roaming/steering). Solo si usteer está
  224. // instalado en el router. Trimmed del output de `ubus call usteer local_info`,
  225. // `remote_info` y `connected_clients` — solo lo que la UI necesita (APs por
  226. // SSID + clientes con señal).
  227. type UsteerData struct {
  228. SSIDs map[string]UsteerSSID `json:"ssids"`
  229. }
  230. // UsteerSSID: por red WiFi (p. ej. "temiscira").
  231. type UsteerSSID struct {
  232. APs []UsteerAP `json:"aps"`
  233. Clients map[string]UsteerClient `json:"clients"` // MAC upper → cliente
  234. }
  235. // UsteerAP: un punto de acceso (local o remoto) visto por usteer en este SSID.
  236. type UsteerAP struct {
  237. BSSID string `json:"bssid"`
  238. Hostname string `json:"hostname,omitempty"` // IP del AP remoto; vacío si local
  239. Freq int `json:"freq"` // MHz (>= 5000 → 5 GHz)
  240. Load int `json:"load"` // utilización % reportada por usteer
  241. Clients int `json:"clients"` // n_assoc
  242. Local bool `json:"local"` // true si es este router
  243. }
  244. // UsteerClient: un cliente WiFi visto por usteer con señal al AP asociado.
  245. type UsteerClient struct {
  246. Signal int `json:"signal"` // dBm (negativo)
  247. }
  248. // DiscoveryData: mDNS service discovery + randomized MAC detection (#338).
  249. // Source: umdns browse on OpenWrt; falls back to parsing /tmp/umdns/ if
  250. // available. Best-effort: nil section if umdns is not installed.
  251. type DiscoveryData struct {
  252. // Services: hostname -> list of mDNS service types advertised.
  253. // e.g. {"Apple-TV._airplay._tcp.local": ["_airplay._tcp", "_raop._tcp"]}
  254. Services map[string][]string `json:"services,omitempty"`
  255. // HostByIP: IP -> hostname from mDNS PTR records. Helps resolve devices
  256. // that have no DHCP hostname.
  257. HostByIP map[string]string `json:"hostByIp,omitempty"`
  258. // RandomMACs: MACs detected as locally-administered (bit 1 of byte 0 set).
  259. // These are typically iOS/Android private WiFi addresses that rotate.
  260. RandomMACs []string `json:"randomMacs,omitempty"`
  261. }