wifi_channelplan.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. if s.agents != nil {
  53. if st := s.agents.Snapshot(slug); st != nil {
  54. payload = st.Payload
  55. }
  56. }
  57. if payload != nil && payload.Data.System != nil && payload.Data.System.Board != nil {
  58. if norm(payload.Data.System.Board.Hostname) == want {
  59. return slug
  60. }
  61. }
  62. if id := resolveAgentRouter(slug, payload, routerByID); id != "" {
  63. if id == routerID || norm(routerByID[id].Name) == want || norm(routerByID[id].Host) == want {
  64. return slug
  65. }
  66. }
  67. }
  68. return routerID
  69. }
  70. mux.Handle("GET /api/wifi/channel-plan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  71. routerID := r.URL.Query().Get("routerId")
  72. if routerID == "" {
  73. writeError(w, http.StatusBadRequest, "invalid_body", "routerId requerido")
  74. return
  75. }
  76. slug := agentSlugForRouter(routerID)
  77. // #1080: solo Fresh() convertía cualquier hueco de frescura del
  78. // agente (reconexión, backhaul, reinicio) en "no reporta radios".
  79. // Es una vista de análisis: mejor el último payload conocido aunque
  80. // pase el TTL que fingir que el equipo no tiene WiFi. El aviso solo
  81. // tiene sentido si no existe payload alguno (o no trae wireless).
  82. var radios []probe.Radio
  83. if s.agents != nil {
  84. payload, ok := s.agents.Fresh(slug)
  85. if !ok {
  86. payload, _ = s.agents.StalePayload(slug)
  87. }
  88. if payload != nil && payload.Data.Wireless != nil {
  89. radios = payload.Data.Wireless.Radios
  90. }
  91. }
  92. recommendations, err := s.channelPlan.Recommend(slug, radios, 24*time.Hour)
  93. if err != nil {
  94. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  95. return
  96. }
  97. scans, err := s.channelPlan.RecentScans(slug, 24*time.Hour)
  98. if err != nil {
  99. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  100. return
  101. }
  102. // #1214: flotas con NETPULSE_SCAN_INTERVAL=0 no escanean nunca por
  103. // intervalo - con la ventana fija de 24h la vista moría en cuanto el
  104. // último scan cumplía un día (solo quedaba el bloque propio
  105. // sintético y un espectro vacío). Misma filosofía que #1080 con los
  106. // radios: mejor el último dato conocido, aunque sea antiguo, que
  107. // fingir que no hay nada; el "Escanear ahora" lo renueva al momento.
  108. if len(scans) == 0 {
  109. scans, err = s.channelPlan.RecentScans(slug, 30*24*time.Hour)
  110. if err != nil {
  111. writeError(w, http.StatusInternalServerError, "channel_plan_error")
  112. return
  113. }
  114. }
  115. writeJSON(w, http.StatusOK, map[string]any{
  116. "routerId": routerID,
  117. "radios": recommendations,
  118. "scans": scans,
  119. })
  120. })))
  121. // #1214: scan ad hoc para flotas con NETPULSE_SCAN_INTERVAL=0. El evento
  122. // "refresh" fuerza en el agente un ciclo con ForceScan (el throttle del
  123. // intervalo no aplica) y el push siguiente trae los vecinos nuevos a
  124. // wifi_scans. Requiere el agente conectado por SSE.
  125. //
  126. // #1561: este endpoint es el único camino de scan con el default nuevo,
  127. // así que lleva su propio anti-martilleo por unidad. Abrir la vista pide
  128. // el scan, y sin límite dos pestañas (o dos admins) encadenarían ciclos
  129. // sacando la radio del canal, que es justo lo que #1557 reporta.
  130. mux.Handle("POST /api/wifi/channel-plan/scan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  131. routerID := r.URL.Query().Get("routerId")
  132. if routerID == "" {
  133. writeError(w, http.StatusBadRequest, "invalid_body", "routerId requerido")
  134. return
  135. }
  136. slug := agentSlugForRouter(routerID)
  137. if s.agentHub == nil {
  138. writeError(w, http.StatusServiceUnavailable, "unavailable", "SSE agentHub no configurado")
  139. return
  140. }
  141. if retry, ok := s.claimPlanScan(slug); !ok {
  142. w.Header().Set("Retry-After", strconv.Itoa(retry))
  143. writeJSON(w, http.StatusTooManyRequests, map[string]any{
  144. "error": "rate_limited",
  145. "retryAfterSec": retry,
  146. })
  147. return
  148. }
  149. if !s.agentHub.Send(slug, "refresh", map[string]any{}) {
  150. // Sin agente conectado el scan no va a ocurrir: se libera el
  151. // turno para que el siguiente intento no espere 5 minutos.
  152. s.releasePlanScan(slug)
  153. writeError(w, http.StatusNotFound, "not_found", "el agente no está conectado por SSE")
  154. return
  155. }
  156. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
  157. })))
  158. }
  159. // planScanMinInterval: mínimo entre scans bajo demanda de una misma unidad
  160. // (#1561). Un scan de vecinos tarda 2-4s por radio y saca la radio del canal.
  161. const planScanMinInterval = 5 * time.Minute
  162. // claimPlanScan reserva el turno de scan de la unidad o devuelve los segundos
  163. // que faltan para el siguiente. El estado vive en memoria: un reinicio del
  164. // server solo permite un scan de más.
  165. func (s *server) claimPlanScan(slug string) (int, bool) {
  166. s.planScanMu.Lock()
  167. defer s.planScanMu.Unlock()
  168. now := time.Now()
  169. if s.lastPlanScan == nil {
  170. s.lastPlanScan = make(map[string]time.Time, 8)
  171. }
  172. if last, ok := s.lastPlanScan[slug]; ok {
  173. if since := now.Sub(last); since < planScanMinInterval {
  174. retry := int(math.Ceil((planScanMinInterval - since).Seconds()))
  175. return retry, false
  176. }
  177. }
  178. s.lastPlanScan[slug] = now
  179. return 0, true
  180. }
  181. // releasePlanScan devuelve el turno cuando el scan no llegó a pedirse.
  182. func (s *server) releasePlanScan(slug string) {
  183. s.planScanMu.Lock()
  184. delete(s.lastPlanScan, slug)
  185. s.planScanMu.Unlock()
  186. }