wifi_channelplan.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package httpapi
  2. import (
  3. "math"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/gnacho/netpulse/agent/probe"
  9. "github.com/gnacho/netpulse/server-go/internal/auth"
  10. )
  11. // registerChannelPlanRoutes añade los endpoints de channel planning (#452).
  12. func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
  13. if s.channelPlan == nil {
  14. return
  15. }
  16. // agentSlugForRouter resuelve la clave que usa la UI (el id del router
  17. // en el overview: hostname o nombre amigable) al slug del agente bajo el
  18. // que viven Fresh() y wifi_scans (#475): la flota manda flint2/rt2 y los
  19. // agentes se llaman gateway/redmi-ax6. Tres capas: slug directo,
  20. // hostname del board del último payload, e id/nombre de la tabla routers
  21. // resuelto con resolveAgentRouter.
  22. agentSlugForRouter := func(routerID string) string {
  23. norm := func(v string) string { return strings.ToLower(strings.TrimSpace(v)) }
  24. routerByID := map[string]routerIdentity{}
  25. slugs := []string{}
  26. if s.db != nil {
  27. if rows, err := s.db.Query("SELECT id, type, name, host, COALESCE(mac,'') FROM routers"); err == nil {
  28. for rows.Next() {
  29. var id, typ, name, host, mac string
  30. if rows.Scan(&id, &typ, &name, &host, &mac) == nil {
  31. routerByID[id] = routerIdentity{ID: id, Type: typ, Name: name, Host: host, Mac: mac}
  32. }
  33. }
  34. rows.Close()
  35. }
  36. if rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ?", agentTokenKeyPrefix+"%"); err == nil {
  37. for rows.Next() {
  38. var key string
  39. if rows.Scan(&key) == nil {
  40. slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
  41. }
  42. }
  43. rows.Close()
  44. }
  45. }
  46. want := norm(routerID)
  47. for _, slug := range slugs {
  48. if slug == routerID {
  49. return slug
  50. }
  51. var payload *probe.Payload
  52. host, bridgeMAC := "", ""
  53. if s.agents != nil {
  54. if st := s.agents.Snapshot(slug); st != nil {
  55. payload = st.Payload
  56. }
  57. // #1874: un push event-driven (wireless-only) no trae board ni
  58. // bridge MAC; la identidad retenida mantiene la asociación.
  59. host, bridgeMAC, _ = s.agents.Identity(slug)
  60. }
  61. if payload != nil && payload.Data.System != nil {
  62. if b := payload.Data.System.Board; b != nil {
  63. if h := strings.TrimSpace(b.Hostname); h != "" {
  64. host = h
  65. }
  66. }
  67. if bridgeMAC == "" {
  68. bridgeMAC = payload.Data.System.BridgeMAC
  69. }
  70. }
  71. if norm(host) == want {
  72. return slug
  73. }
  74. if id := resolveAgentRouterIdentity(slug, host, bridgeMAC, routerByID); id != "" {
  75. if id == routerID || norm(routerByID[id].Name) == want || norm(routerByID[id].Host) == want {
  76. return slug
  77. }
  78. }
  79. }
  80. return routerID
  81. }
  82. mux.Handle("GET /api/wifi/channel-plan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  83. routerID := r.URL.Query().Get("routerId")
  84. if routerID == "" {
  85. writeError(w, http.StatusBadRequest, "invalid_body", "routerId requerido")
  86. return
  87. }
  88. slug := agentSlugForRouter(routerID)
  89. // #1080: solo Fresh() convertía cualquier hueco de frescura del
  90. // agente (reconexión, backhaul, reinicio) en "no reporta radios".
  91. // Es una vista de análisis: mejor el último payload conocido aunque
  92. // pase el TTL que fingir que el equipo no tiene WiFi. El aviso solo
  93. // tiene sentido si no existe payload alguno (o no trae wireless).
  94. var radios []probe.Radio
  95. if s.agents != nil {
  96. payload, ok := s.agents.Fresh(slug)
  97. if !ok {
  98. payload, _ = s.agents.StalePayload(slug)
  99. }
  100. if payload != nil && payload.Data.Wireless != nil {
  101. radios = payload.Data.Wireless.Radios
  102. }
  103. }
  104. // #1742: lo que se puntúa y lo que se enseña tienen que salir de la
  105. // misma ventana. Antes se recomendaba con 24 h fijas y, si no había
  106. // scans, solo la lista se ampliaba a 30 días: la vista mostraba filas
  107. // con todos los vecinos a 0 porque el análisis nunca las había visto.
  108. // #1214: flotas con NETPULSE_SCAN_INTERVAL=0 no escanean nunca por
  109. // intervalo - con la ventana fija de 24h la vista moría en cuanto el
  110. // último scan cumplía un día (solo quedaba el bloque propio
  111. // sintético y un espectro vacío). Misma filosofía que #1080 con los
  112. // radios: mejor el último dato conocido, aunque sea antiguo, que
  113. // fingir que no hay nada; el "Escanear ahora" lo renueva al momento.
  114. window := 24 * time.Hour
  115. scans, err := s.channelPlan.RecentScans(slug, window)
  116. if err != nil {
  117. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  118. return
  119. }
  120. if len(scans) == 0 {
  121. window = 30 * 24 * time.Hour
  122. scans, err = s.channelPlan.RecentScans(slug, window)
  123. if err != nil {
  124. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  125. return
  126. }
  127. }
  128. recommendations, err := s.channelPlan.Recommend(slug, radios, window)
  129. if err != nil {
  130. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  131. return
  132. }
  133. // #1848: motivo del ultimo scan por interfaz. Va en la respuesta y,
  134. // cuando la interfaz coincide, pegado al radio: es lo que explica una
  135. // banda a cero sin inventar datos.
  136. outcomes, err := s.channelPlan.ScanOutcomes(slug)
  137. if err != nil {
  138. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  139. return
  140. }
  141. reasonByIface := map[string]string{}
  142. for _, oc := range outcomes {
  143. if oc.Error != "" {
  144. reasonByIface[oc.Iface] = oc.Error
  145. }
  146. }
  147. for i := range recommendations {
  148. if reason := reasonByIface[recommendations[i].Iface]; reason != "" {
  149. recommendations[i].ScanError = reason
  150. }
  151. }
  152. writeJSON(w, http.StatusOK, map[string]any{
  153. "routerId": routerID,
  154. "radios": recommendations,
  155. "scans": scans,
  156. "scanOutcomes": outcomes,
  157. })
  158. })))
  159. // #1214: scan ad hoc para flotas con NETPULSE_SCAN_INTERVAL=0. El evento
  160. // "refresh" fuerza en el agente un ciclo con ForceScan (el throttle del
  161. // intervalo no aplica) y el push siguiente trae los vecinos nuevos a
  162. // wifi_scans. Requiere el agente conectado por SSE.
  163. //
  164. // #1561: este endpoint es el único camino de scan con el default nuevo,
  165. // así que lleva su propio anti-martilleo por unidad. Abrir la vista pide
  166. // el scan, y sin límite dos pestañas (o dos admins) encadenarían ciclos
  167. // sacando la radio del canal, que es justo lo que #1557 reporta.
  168. mux.Handle("POST /api/wifi/channel-plan/scan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  169. routerID := r.URL.Query().Get("routerId")
  170. if routerID == "" {
  171. writeError(w, http.StatusBadRequest, "invalid_body", "routerId requerido")
  172. return
  173. }
  174. slug := agentSlugForRouter(routerID)
  175. if s.agentHub == nil {
  176. writeError(w, http.StatusServiceUnavailable, "unavailable", "SSE agentHub no configurado")
  177. return
  178. }
  179. if retry, ok := s.claimPlanScan(slug); !ok {
  180. w.Header().Set("Retry-After", strconv.Itoa(retry))
  181. writeJSON(w, http.StatusTooManyRequests, map[string]any{
  182. "error": "rate_limited",
  183. "retryAfterSec": retry,
  184. })
  185. return
  186. }
  187. if !s.agentHub.Send(slug, "refresh", map[string]any{}) {
  188. // Sin agente conectado el scan no va a ocurrir: se libera el
  189. // turno para que el siguiente intento no espere 5 minutos.
  190. s.releasePlanScan(slug)
  191. writeError(w, http.StatusNotFound, "not_found", "el agente no está conectado por SSE")
  192. return
  193. }
  194. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
  195. })))
  196. }
  197. // planScanMinInterval: mínimo entre scans bajo demanda de una misma unidad
  198. // (#1561). Un scan de vecinos tarda 2-4s por radio y saca la radio del canal.
  199. const planScanMinInterval = 5 * time.Minute
  200. // claimPlanScan reserva el turno de scan de la unidad o devuelve los segundos
  201. // que faltan para el siguiente. El estado vive en memoria: un reinicio del
  202. // server solo permite un scan de más.
  203. func (s *server) claimPlanScan(slug string) (int, bool) {
  204. s.planScanMu.Lock()
  205. defer s.planScanMu.Unlock()
  206. now := time.Now()
  207. if s.lastPlanScan == nil {
  208. s.lastPlanScan = make(map[string]time.Time, 8)
  209. }
  210. if last, ok := s.lastPlanScan[slug]; ok {
  211. if since := now.Sub(last); since < planScanMinInterval {
  212. retry := int(math.Ceil((planScanMinInterval - since).Seconds()))
  213. return retry, false
  214. }
  215. }
  216. s.lastPlanScan[slug] = now
  217. return 0, true
  218. }
  219. // releasePlanScan devuelve el turno cuando el scan no llegó a pedirse.
  220. func (s *server) releasePlanScan(slug string) {
  221. s.planScanMu.Lock()
  222. delete(s.lastPlanScan, slug)
  223. s.planScanMu.Unlock()
  224. }