store.go 12 KB

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