presence.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // presence.go — timeline de presencia por cliente y salud de roaming (#771).
  2. //
  3. // Los eventos YA se generaban: device_events (#184, online/offline del
  4. // poller) y roam_events (Fase 14.5, AP-STA-CONNECTED/DISCONNECTED vía
  5. // logread). Estos handlers los funden en tramos de presencia por MAC y
  6. // exponen la salud de roaming de la flota; la retención configurable vive en
  7. // kv (presence.retention_days) y la aplica un loop de poda en main.
  8. package httpapi
  9. import (
  10. "database/sql"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/agent/macaddr"
  16. "github.com/gnacho/netpulse/server-go/internal/deviceevents"
  17. )
  18. const presenceRetentionKey = "presence.retention_days"
  19. // historyLimitKey (#975): interruptor maestro de la poda del historial.
  20. // ON por defecto (ausente = limitar); OFF = retención ilimitada: el loop de
  21. // poda de main no borra nada aunque presence.retention_days tenga valor.
  22. const historyLimitKey = "history.limit_enabled"
  23. // handleDevicePresence devuelve los tramos de presencia de una MAC (dias
  24. // visibles, default 7, máx 30) más los eventos recientes y el nº de
  25. // conexiones en las últimas 24 h. En demo devuelve una muestra sintética
  26. // determinista para que la UI sea explorable sin red real.
  27. func (s *server) handleDevicePresence(w http.ResponseWriter, r *http.Request) {
  28. mac := macaddr.Normalize(r.PathValue("mac"))
  29. if mac == "" {
  30. writeError(w, http.StatusBadRequest, "invalid_mac")
  31. return
  32. }
  33. days := 7
  34. if v := r.URL.Query().Get("days"); v != "" {
  35. if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= 30 {
  36. days = n
  37. }
  38. }
  39. now := time.Now()
  40. since := now.Add(-time.Duration(days) * 24 * time.Hour).UnixMilli()
  41. if s.cfg.DemoMode {
  42. writeJSON(w, http.StatusOK, demoPresence(mac, days, now))
  43. return
  44. }
  45. intervals, err := deviceevents.Intervals(s.db.DB, mac, since)
  46. if err != nil {
  47. writeError(w, http.StatusInternalServerError, "db_error")
  48. return
  49. }
  50. events, err := deviceevents.ListEvents(s.db.DB, 50, since, "", mac, "")
  51. if err != nil {
  52. writeError(w, http.StatusInternalServerError, "db_error")
  53. return
  54. }
  55. connects24h, _ := deviceevents.CountConnects(s.db.DB, mac, now.Add(-24*time.Hour).UnixMilli())
  56. writeJSON(w, http.StatusOK, map[string]any{
  57. "mac": mac,
  58. "days": days,
  59. "nowMs": now.UnixMilli(),
  60. "intervals": intervals,
  61. "events": events,
  62. "connects24h": connects24h,
  63. })
  64. }
  65. // handlePresenceRoaming devuelve las MACs con más eventos 'connected' en las
  66. // últimas 24 h (los primeros puestos son los clientes que más rebotan entre
  67. // APs), con nombre resuelto desde la flota actual o los alias conocidos.
  68. // source=false indica que ninguna unidad aporta atribución wireless, así que
  69. // un 0 no significa "roaming sano" sino "no hay fuente" (#1740).
  70. func (s *server) handlePresenceRoaming(w http.ResponseWriter, r *http.Request) {
  71. type item struct {
  72. MAC string `json:"mac"`
  73. Name string `json:"name"`
  74. Connects int `json:"connects"`
  75. }
  76. if s.cfg.DemoMode {
  77. writeJSON(w, http.StatusOK, map[string]any{"items": []item{}, "source": true})
  78. return
  79. }
  80. since := time.Now().Add(-24 * time.Hour).UnixMilli()
  81. counts, err := deviceevents.RoamCounts(s.db.DB, since, 20)
  82. if err != nil {
  83. writeError(w, http.StatusInternalServerError, "db_error")
  84. return
  85. }
  86. names := map[string]string{}
  87. if s.adapter != nil {
  88. for _, d := range s.adapter.GetDevices(r.Context()) {
  89. names[strings.ToUpper(d.MAC)] = d.Name
  90. }
  91. }
  92. items := make([]item, 0, len(counts))
  93. for _, c := range counts {
  94. mac := strings.ToUpper(c.MAC)
  95. nm := names[mac]
  96. if nm == "" {
  97. nm = s.knownMacName(mac)
  98. }
  99. items = append(items, item{MAC: mac, Name: nm, Connects: c.Connects})
  100. }
  101. writeJSON(w, http.StatusOK, map[string]any{
  102. "items": items,
  103. "source": deviceevents.HasAttribution(s.db.DB, since),
  104. })
  105. }
  106. // knownMacName resuelve el alias de una MAC desde known_macs ("" si no hay).
  107. func (s *server) knownMacName(mac string) string {
  108. var name string
  109. _ = s.db.QueryRow("SELECT name FROM known_macs WHERE mac = ?", mac).Scan(&name)
  110. return name
  111. }
  112. // handlePresenceSettingsGet/Put exponen la retención de eventos de presencia
  113. // (días; 0 = conservar siempre). La poda la aplica el loop de main.
  114. func (s *server) handlePresenceSettingsGet(w http.ResponseWriter, r *http.Request) {
  115. writeJSON(w, http.StatusOK, map[string]any{"retention_days": s.presenceRetentionDays()})
  116. }
  117. func (s *server) handlePresenceSettingsPut(w http.ResponseWriter, r *http.Request) {
  118. var body struct {
  119. RetentionDays int `json:"retention_days"`
  120. }
  121. if st := readJSONBody(w, r, &body); st != 0 {
  122. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  123. return
  124. }
  125. if body.RetentionDays < 0 || body.RetentionDays > 365 {
  126. writeError(w, http.StatusBadRequest, "invalid_retention", "retención 0..365 días")
  127. return
  128. }
  129. if _, err := s.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  130. presenceRetentionKey, strconv.Itoa(body.RetentionDays)); err != nil {
  131. writeError(w, http.StatusInternalServerError, "db_error")
  132. return
  133. }
  134. writeJSON(w, http.StatusOK, map[string]any{"retention_days": body.RetentionDays})
  135. }
  136. // PresenceRetentionDays lee la retención configurada del kv (default 30
  137. // días; 0 = conservar siempre). La usa el handler de settings y el loop de
  138. // poda de main.
  139. func PresenceRetentionDays(db *sql.DB) int {
  140. if v := kvGet(db, presenceRetentionKey); v != "" {
  141. if n, err := strconv.Atoi(v); err == nil {
  142. return n
  143. }
  144. }
  145. return 30
  146. }
  147. // HistoryLimitEnabled lee el interruptor maestro de la poda (#975): default
  148. // ON (solo un "0" explícito lo desactiva). Lo usa el loop de poda de main.
  149. func HistoryLimitEnabled(db *sql.DB) bool {
  150. return kvGet(db, historyLimitKey) != "0"
  151. }
  152. // handleHistoryLimitGet/Put exponen el interruptor maestro «Limitar
  153. // historial» (#975). OFF = sin poda de presencia/itinerancia (retención
  154. // ilimitada); el intervalo de ingesta (roam.collect.interval_sec) es
  155. // independiente y sigue aplicando con el límite desactivado.
  156. func (s *server) handleHistoryLimitGet(w http.ResponseWriter, _ *http.Request) {
  157. writeJSON(w, http.StatusOK, map[string]any{"enabled": HistoryLimitEnabled(s.db.DB)})
  158. }
  159. func (s *server) handleHistoryLimitPut(w http.ResponseWriter, r *http.Request) {
  160. var body struct {
  161. Enabled bool `json:"enabled"`
  162. }
  163. if st := readJSONBody(w, r, &body); st != 0 {
  164. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  165. return
  166. }
  167. v := "1"
  168. if !body.Enabled {
  169. v = "0"
  170. }
  171. if _, err := s.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  172. historyLimitKey, v); err != nil {
  173. writeError(w, http.StatusInternalServerError, "db_error")
  174. return
  175. }
  176. writeJSON(w, http.StatusOK, map[string]any{"enabled": body.Enabled})
  177. }
  178. // presenceRetentionDays es la variante del server para el handler de settings.
  179. func (s *server) presenceRetentionDays() int {
  180. return PresenceRetentionDays(s.db.DB)
  181. }
  182. // demoPresence genera una muestra determinista para el modo demo: dos tramos
  183. // hoy (mañana en el router par, tarde en impar) y un tramo de ayer, más la
  184. // ventana pedida vacía en días anteriores.
  185. func demoPresence(mac string, days int, now time.Time) map[string]any {
  186. // Hash simple de la MAC para desplazar las horas de forma estable.
  187. h := 0
  188. for _, c := range mac {
  189. h = (h*31 + int(c)) % 240
  190. }
  191. dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
  192. mk := func(d time.Time, h1, h2 int) deviceevents.Interval {
  193. s := d.Add(time.Duration(h1)*time.Hour + time.Duration(h%60)*time.Minute).UnixMilli()
  194. e := d.Add(time.Duration(h2) * time.Hour).UnixMilli()
  195. return deviceevents.Interval{RouterID: "rt-a", StartMs: s, EndMs: &e}
  196. }
  197. yesterday := dayStart.Add(-24 * time.Hour)
  198. intervals := []deviceevents.Interval{
  199. mk(yesterday, 18, 23),
  200. mk(dayStart, 8, 12),
  201. }
  202. nowMs := now.UnixMilli()
  203. if h%2 == 0 {
  204. intervals = append(intervals, deviceevents.Interval{RouterID: "rt-b", StartMs: dayStart.Add(13 * time.Hour).UnixMilli()})
  205. } else {
  206. e := dayStart.Add(20 * time.Hour).UnixMilli()
  207. intervals = append(intervals, deviceevents.Interval{RouterID: "rt-a", StartMs: dayStart.Add(13 * time.Hour).UnixMilli(), EndMs: &e})
  208. }
  209. return map[string]any{
  210. "mac": mac,
  211. "days": days,
  212. "nowMs": nowMs,
  213. "intervals": intervals,
  214. "events": []deviceevents.Event{},
  215. "connects24h": 2 + h%3,
  216. }
  217. }