store.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package clientbw
  2. import (
  3. "database/sql"
  4. "log"
  5. "time"
  6. )
  7. const (
  8. RawRetentionMS = 7 * 24 * 60 * 60 * 1000
  9. // BucketRetentionMS (#1862): un trimestre de buckets de 5m. Con un año la
  10. // BD llegaba a ~1,3 GB en este despliegue (los 5m ya ocupaban 182 MB con
  11. // 64 días), demasiado para el disco del contenedor junto con las copias
  12. // del updater. Noventa días cubren las vistas de trimestre y dejan el
  13. // histórico largo a los buckets de más granularidad.
  14. BucketRetentionMS = 90 * 24 * 60 * 60 * 1000
  15. BucketMS = 5 * 60 * 1000
  16. )
  17. // rollupRawWindow (#812): el rollup raw→5m cubre TODA la retención raw (7d),
  18. // no una ventana fija de 48h. Si no, una caída mayor de dos días dejaba sin
  19. // agregar el tramo 48h..7d, que al purgarse producía un hueco permanente.
  20. const rollupRawWindow = time.Duration(RawRetentionMS) * time.Millisecond
  21. // client_bw_raw guarda una muestra por (mac, router_id, ts): los bytes del
  22. // INTERVALO (delta entre contadores absolutos de dos sondeos) y el rate medio
  23. // de ese intervalo (rx_bps = delta*8/dt). El server calcula ambos en la
  24. // ingesta desde los contadores acumulados que reporta la fuente (nlbwmon o
  25. // hostapd bytes por estación, issue #551).
  26. const schemaSQL = `
  27. CREATE TABLE IF NOT EXISTS client_bw_raw (
  28. mac TEXT NOT NULL,
  29. router_id TEXT NOT NULL,
  30. ts INTEGER NOT NULL,
  31. rx_bytes INTEGER NOT NULL DEFAULT 0,
  32. tx_bytes INTEGER NOT NULL DEFAULT 0,
  33. rx_bps REAL NOT NULL DEFAULT 0,
  34. tx_bps REAL NOT NULL DEFAULT 0,
  35. PRIMARY KEY (mac, router_id, ts)
  36. );
  37. CREATE INDEX IF NOT EXISTS idx_client_bw_raw_ts ON client_bw_raw(ts);
  38. CREATE TABLE IF NOT EXISTS client_bw_5m (
  39. mac TEXT NOT NULL,
  40. router_id TEXT NOT NULL,
  41. bucket_ts INTEGER NOT NULL,
  42. n INTEGER NOT NULL,
  43. rx_bytes INTEGER NOT NULL DEFAULT 0,
  44. tx_bytes INTEGER NOT NULL DEFAULT 0,
  45. rx_bps_min REAL NOT NULL DEFAULT 0,
  46. rx_bps_max REAL NOT NULL DEFAULT 0,
  47. rx_bps_avg REAL NOT NULL DEFAULT 0,
  48. tx_bps_min REAL NOT NULL DEFAULT 0,
  49. tx_bps_max REAL NOT NULL DEFAULT 0,
  50. tx_bps_avg REAL NOT NULL DEFAULT 0,
  51. PRIMARY KEY (mac, router_id, bucket_ts)
  52. );
  53. CREATE INDEX IF NOT EXISTS idx_client_bw_5m_ts ON client_bw_5m(bucket_ts);
  54. CREATE TABLE IF NOT EXISTS client_bw_daily (
  55. mac TEXT NOT NULL,
  56. router_id TEXT NOT NULL,
  57. date TEXT NOT NULL,
  58. n INTEGER NOT NULL,
  59. rx_bytes INTEGER NOT NULL DEFAULT 0,
  60. tx_bytes INTEGER NOT NULL DEFAULT 0,
  61. rx_bps_avg REAL NOT NULL DEFAULT 0,
  62. tx_bps_avg REAL NOT NULL DEFAULT 0,
  63. PRIMARY KEY (mac, router_id, date)
  64. );
  65. `
  66. // Sample es una muestra de tráfico de UN cliente en UN router: bytes del
  67. // intervalo (delta) y rate medio del intervalo en bps.
  68. type Sample struct {
  69. MAC string
  70. RouterID string
  71. TS time.Time
  72. RxBytes uint64
  73. TxBytes uint64
  74. RxBps float64
  75. TxBps float64
  76. }
  77. type Point struct {
  78. TS time.Time `json:"ts"`
  79. RxBytes uint64 `json:"rxBytes"`
  80. TxBytes uint64 `json:"txBytes"`
  81. RxBps float64 `json:"rxBps"`
  82. TxBps float64 `json:"txBps"`
  83. }
  84. type Store struct {
  85. db *sql.DB
  86. }
  87. func NewStore(db *sql.DB) (*Store, error) {
  88. if db != nil {
  89. if _, err := db.Exec(schemaSQL); err != nil {
  90. return nil, err
  91. }
  92. // Migración tolerante: DBs creadas antes del #551 no tienen las
  93. // columnas bps en raw (el esquema viejo las ignoraba).
  94. ensureColumn(db, "client_bw_raw", "rx_bps", "ALTER TABLE client_bw_raw ADD COLUMN rx_bps REAL NOT NULL DEFAULT 0")
  95. ensureColumn(db, "client_bw_raw", "tx_bps", "ALTER TABLE client_bw_raw ADD COLUMN tx_bps REAL NOT NULL DEFAULT 0")
  96. }
  97. return &Store{db: db}, nil
  98. }
  99. func ensureColumn(db *sql.DB, table, column, alterSQL string) {
  100. rows, err := db.Query("PRAGMA table_info(" + table + ")")
  101. if err != nil {
  102. return
  103. }
  104. defer rows.Close()
  105. for rows.Next() {
  106. var cid int
  107. var name, ctype string
  108. var notnull, pk int
  109. var dflt any
  110. if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err == nil && name == column {
  111. return
  112. }
  113. }
  114. _, _ = db.Exec(alterSQL)
  115. }
  116. func (s *Store) Insert(sample Sample) error {
  117. if s.db == nil {
  118. return nil
  119. }
  120. _, err := s.db.Exec(
  121. `INSERT OR REPLACE INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes, rx_bps, tx_bps)
  122. VALUES (?,?,?,?,?,?,?)`,
  123. sample.MAC, sample.RouterID, sample.TS.UnixMilli(), sample.RxBytes, sample.TxBytes,
  124. sample.RxBps, sample.TxBps)
  125. return err
  126. }
  127. func (s *Store) GetSeries(mac, routerID string, from, to time.Time, resolution string) ([]Point, error) {
  128. if s.db == nil {
  129. return nil, nil
  130. }
  131. fromMs, toMs := from.UnixMilli(), to.UnixMilli()
  132. switch resolution {
  133. case "raw":
  134. return s.queryRaw(mac, routerID, fromMs, toMs)
  135. case "5m":
  136. return s.query5m(mac, routerID, fromMs, toMs)
  137. case "daily":
  138. return s.queryDaily(mac, routerID, from, to)
  139. default:
  140. return s.queryRaw(mac, routerID, fromMs, toMs)
  141. }
  142. }
  143. // GetMACSeries devuelve la serie de un cliente (MAC) agregando a través de
  144. // TODOS los routers: un dispositivo puede verse en varios APs a lo largo del
  145. // día (roaming), y la UI del detalle quiere el total, no el de un router.
  146. func (s *Store) GetMACSeries(mac string, from, to time.Time, resolution string) ([]Point, error) {
  147. if s.db == nil {
  148. return nil, nil
  149. }
  150. fromMs, toMs := from.UnixMilli(), to.UnixMilli()
  151. switch resolution {
  152. case "raw":
  153. return s.queryRawMAC(mac, fromMs, toMs)
  154. case "5m":
  155. return s.query5mMAC(mac, fromMs, toMs)
  156. case "daily":
  157. return s.queryDailyMAC(mac, from, to)
  158. default:
  159. return s.queryRawMAC(mac, fromMs, toMs)
  160. }
  161. }
  162. func (s *Store) queryRawMAC(mac string, fromMs, toMs int64) ([]Point, error) {
  163. rows, err := s.db.Query(
  164. `SELECT ts, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps), AVG(tx_bps)
  165. FROM client_bw_raw
  166. WHERE mac = ? AND ts >= ? AND ts <= ?
  167. GROUP BY ts ORDER BY ts`, mac, fromMs, toMs)
  168. if err != nil {
  169. return nil, err
  170. }
  171. defer rows.Close()
  172. var out []Point
  173. for rows.Next() {
  174. var p Point
  175. var ts int64
  176. if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  177. p.TS = time.UnixMilli(ts)
  178. out = append(out, p)
  179. }
  180. }
  181. return out, rows.Err()
  182. }
  183. func (s *Store) query5mMAC(mac string, fromMs, toMs int64) ([]Point, error) {
  184. rows, err := s.db.Query(
  185. `SELECT bucket_ts, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
  186. FROM client_bw_5m
  187. WHERE mac = ? AND bucket_ts >= ? AND bucket_ts <= ?
  188. GROUP BY bucket_ts ORDER BY bucket_ts`, mac, fromMs, toMs)
  189. if err != nil {
  190. return nil, err
  191. }
  192. defer rows.Close()
  193. var out []Point
  194. for rows.Next() {
  195. var p Point
  196. var ts int64
  197. if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  198. p.TS = time.UnixMilli(ts)
  199. out = append(out, p)
  200. }
  201. }
  202. return out, rows.Err()
  203. }
  204. func (s *Store) queryDailyMAC(mac string, from, to time.Time) ([]Point, error) {
  205. fromDate := from.Format("2006-01-02")
  206. toDate := to.Format("2006-01-02")
  207. rows, err := s.db.Query(
  208. `SELECT date, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
  209. FROM client_bw_daily
  210. WHERE mac = ? AND date >= ? AND date <= ?
  211. GROUP BY date ORDER BY date`, mac, fromDate, toDate)
  212. if err != nil {
  213. return nil, err
  214. }
  215. defer rows.Close()
  216. var out []Point
  217. for rows.Next() {
  218. var p Point
  219. var date string
  220. if err := rows.Scan(&date, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  221. p.TS, _ = time.Parse("2006-01-02", date)
  222. out = append(out, p)
  223. }
  224. }
  225. return out, rows.Err()
  226. }
  227. func (s *Store) queryRaw(mac, routerID string, fromMs, toMs int64) ([]Point, error) {
  228. rows, err := s.db.Query(
  229. `SELECT ts, rx_bytes, tx_bytes, rx_bps, tx_bps FROM client_bw_raw
  230. WHERE mac = ? AND router_id = ? AND ts >= ? AND ts <= ?
  231. ORDER BY ts`, mac, routerID, fromMs, toMs)
  232. if err != nil {
  233. return nil, err
  234. }
  235. defer rows.Close()
  236. var out []Point
  237. for rows.Next() {
  238. var p Point
  239. var ts int64
  240. if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  241. p.TS = time.UnixMilli(ts)
  242. out = append(out, p)
  243. }
  244. }
  245. return out, rows.Err()
  246. }
  247. func (s *Store) query5m(mac, routerID string, fromMs, toMs int64) ([]Point, error) {
  248. rows, err := s.db.Query(
  249. `SELECT bucket_ts, rx_bytes, tx_bytes, rx_bps_avg, tx_bps_avg FROM client_bw_5m
  250. WHERE mac = ? AND router_id = ? AND bucket_ts >= ? AND bucket_ts <= ?
  251. ORDER BY bucket_ts`, mac, routerID, fromMs, toMs)
  252. if err != nil {
  253. return nil, err
  254. }
  255. defer rows.Close()
  256. var out []Point
  257. for rows.Next() {
  258. var p Point
  259. var ts int64
  260. if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  261. p.TS = time.UnixMilli(ts)
  262. out = append(out, p)
  263. }
  264. }
  265. return out, rows.Err()
  266. }
  267. func (s *Store) queryDaily(mac, routerID string, from, to time.Time) ([]Point, error) {
  268. fromDate := from.Format("2006-01-02")
  269. toDate := to.Format("2006-01-02")
  270. rows, err := s.db.Query(
  271. `SELECT date, rx_bytes, tx_bytes, rx_bps_avg, tx_bps_avg FROM client_bw_daily
  272. WHERE mac = ? AND router_id = ? AND date >= ? AND date <= ?
  273. ORDER BY date`, mac, routerID, fromDate, toDate)
  274. if err != nil {
  275. return nil, err
  276. }
  277. defer rows.Close()
  278. var out []Point
  279. for rows.Next() {
  280. var p Point
  281. var date string
  282. if err := rows.Scan(&date, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
  283. p.TS, _ = time.Parse("2006-01-02", date)
  284. out = append(out, p)
  285. }
  286. }
  287. return out, rows.Err()
  288. }
  289. func (s *Store) RollupRawTo5m(window time.Duration) error {
  290. if s.db == nil {
  291. return nil
  292. }
  293. since := time.Now().Add(-window).UnixMilli()
  294. _, err := s.db.Exec(`
  295. INSERT OR REPLACE INTO client_bw_5m
  296. (mac, router_id, bucket_ts, n, rx_bytes, tx_bytes,
  297. rx_bps_min, rx_bps_max, rx_bps_avg, tx_bps_min, tx_bps_max, tx_bps_avg)
  298. SELECT
  299. mac, router_id, (ts / ?) * ?, COUNT(*),
  300. SUM(rx_bytes), SUM(tx_bytes),
  301. MIN(rx_bps), MAX(rx_bps), AVG(rx_bps),
  302. MIN(tx_bps), MAX(tx_bps), AVG(tx_bps)
  303. FROM client_bw_raw
  304. WHERE ts >= ?
  305. GROUP BY mac, router_id, (ts / ?)`,
  306. BucketMS, BucketMS, since, BucketMS)
  307. return err
  308. }
  309. func (s *Store) Rollup5mToDaily(window time.Duration) error {
  310. if s.db == nil {
  311. return nil
  312. }
  313. since := time.Now().Add(-window).UnixMilli()
  314. _, err := s.db.Exec(`
  315. INSERT OR REPLACE INTO client_bw_daily
  316. (mac, router_id, date, n, rx_bytes, tx_bytes, rx_bps_avg, tx_bps_avg)
  317. SELECT
  318. mac, router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch'),
  319. SUM(n), SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
  320. FROM client_bw_5m
  321. WHERE bucket_ts >= ?
  322. GROUP BY mac, router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch')`,
  323. since)
  324. return err
  325. }
  326. func (s *Store) Purge() error {
  327. if s.db == nil {
  328. return nil
  329. }
  330. now := time.Now()
  331. rawCutoff := now.Add(-time.Duration(RawRetentionMS) * time.Millisecond).UnixMilli()
  332. bucketCutoff := now.Add(-time.Duration(BucketRetentionMS) * time.Millisecond).UnixMilli()
  333. _, _ = s.db.Exec("DELETE FROM client_bw_raw WHERE ts < ?", rawCutoff)
  334. _, _ = s.db.Exec("DELETE FROM client_bw_5m WHERE bucket_ts < ?", bucketCutoff)
  335. return nil
  336. }
  337. // NightlyJob: escalera de rollup + purga (patrón portseries). La agrega
  338. // DB.NightlyJob tras los rollups de métricas. Ventana raw→5m = retención raw
  339. // (#812) para rellenar huecos de caídas largas antes de purgar.
  340. func (s *Store) NightlyJob() {
  341. start := time.Now()
  342. log.Printf("[netpulse:clientbw] nightly rollup: start")
  343. if err := s.RollupRawTo5m(rollupRawWindow); err != nil {
  344. log.Printf("[netpulse:clientbw] rollup raw->5m error: %v", err)
  345. }
  346. if err := s.Rollup5mToDaily(35 * 24 * time.Hour); err != nil {
  347. log.Printf("[netpulse:clientbw] rollup 5m->daily error: %v", err)
  348. }
  349. if err := s.Purge(); err != nil {
  350. log.Printf("[netpulse:clientbw] purge error: %v", err)
  351. }
  352. log.Printf("[netpulse:clientbw] nightly rollup: done (%s)", time.Since(start).Round(time.Millisecond))
  353. }
  354. func (s *Store) TopClients(routerID string, since time.Time, limit int) ([]TopClient, error) {
  355. if s.db == nil {
  356. return nil, nil
  357. }
  358. rows, err := s.db.Query(
  359. `SELECT mac, SUM(rx_bytes) as rx, SUM(tx_bytes) as tx
  360. FROM client_bw_raw WHERE router_id = ? AND ts >= ?
  361. GROUP BY mac ORDER BY (rx + tx) DESC LIMIT ?`,
  362. routerID, since.UnixMilli(), limit)
  363. if err != nil {
  364. return nil, err
  365. }
  366. defer rows.Close()
  367. var out []TopClient
  368. for rows.Next() {
  369. var tc TopClient
  370. if err := rows.Scan(&tc.MAC, &tc.RxBytes, &tc.TxBytes); err == nil {
  371. out = append(out, tc)
  372. }
  373. }
  374. return out, rows.Err()
  375. }
  376. type TopClient struct {
  377. MAC string `json:"mac"`
  378. RxBytes uint64 `json:"rxBytes"`
  379. TxBytes uint64 `json:"txBytes"`
  380. }