db.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. // Package db — SQLite (modernc.org/sqlite, sin CGO): schema literal de Node,
  2. // pragmas (WAL, synchronous NORMAL, foreign_keys ON), migraciones tolerantes
  3. // y jobs de mantenimiento (retención 7 días + wal_checkpoint(TRUNCATE) 1 h).
  4. // Paridad con server/src/db.js (SPEC §4).
  5. //
  6. // Epochs: TODOS los timestamps de la DB son milisegundos (created_at,
  7. // expires_at, metrics.ts, locked_until). Segundos solo en overview.ts.
  8. package db
  9. import (
  10. "context"
  11. "database/sql"
  12. "fmt"
  13. "log"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "time"
  19. _ "modernc.org/sqlite"
  20. "github.com/gnacho/netpulse/server-go/internal/clientbw"
  21. "github.com/gnacho/netpulse/server-go/internal/portseries"
  22. "github.com/gnacho/netpulse/server-go/internal/wgseries"
  23. )
  24. const (
  25. RetentionMS = 7 * 24 * 60 * 60 * 1000 // 7 días
  26. Maintenance = time.Hour
  27. databaseFile = "netpulse.db"
  28. // AttribRetentionMS: 90 días sin verse para purgar device_attrib
  29. // (issue #206; dispositivos que se fueron para siempre).
  30. AttribRetentionMS = 90 * 24 * 60 * 60 * 1000
  31. // DNSActivityRetentionMS: detalle horario del query log (#2078).
  32. DNSActivityRetentionMS = 7 * 24 * 60 * 60 * 1000
  33. // DNSFirstsRetentionMS: histórico de "primera vez visto" por dominio (#2078).
  34. DNSFirstsRetentionMS = 90 * 24 * 60 * 60 * 1000
  35. )
  36. // rollupRawWindow (#812): el rollup raw→5m cubre TODA la retención raw (7d) en
  37. // lugar de una ventana fija de 48h. Con 48h, una caída de más de dos días
  38. // dejaba sin agregar los samples de 48h..7d, que al purgarse a los 7d
  39. // producían un hueco permanente en 5m/daily. El orden rollup→purga del job
  40. // nocturno garantiza que la ventana siempre encuentre el raw disponible.
  41. const rollupRawWindow = time.Duration(RetentionMS) * time.Millisecond
  42. // schemaSQL es el SQL literal de src/db.js:20-85.
  43. const schemaSQL = `
  44. -- Sesiones (cookie id.hmac)
  45. CREATE TABLE IF NOT EXISTS sessions (
  46. id TEXT PRIMARY KEY,
  47. created_at INTEGER NOT NULL,
  48. expires_at INTEGER NOT NULL,
  49. ua TEXT
  50. );
  51. -- Rate-limit de login por IP
  52. CREATE TABLE IF NOT EXISTS login_attempts (
  53. ip TEXT PRIMARY KEY,
  54. attempts INTEGER DEFAULT 0,
  55. locked_until INTEGER DEFAULT 0
  56. );
  57. -- Clave-valor (session_secret, auth_pass_hash, ...)
  58. CREATE TABLE IF NOT EXISTS kv (
  59. key TEXT PRIMARY KEY,
  60. value TEXT
  61. );
  62. -- Métricas por router y tick del poller
  63. CREATE TABLE IF NOT EXISTS metrics (
  64. router_id TEXT NOT NULL,
  65. ts INTEGER NOT NULL,
  66. cpu REAL, ram REAL, temp REAL,
  67. latency_ms REAL, rx_bps REAL, tx_bps REAL,
  68. PRIMARY KEY (router_id, ts)
  69. );
  70. CREATE INDEX IF NOT EXISTS idx_metrics_router_ts ON metrics(router_id, ts);
  71. -- Escalera de retención: raw 7 días → buckets
  72. -- 5 min 1 año → daily ∞. El job nocturno hace el rollup en este orden; el
  73. -- endpoint de histórico sirve largo plazo desde estos niveles.
  74. CREATE TABLE IF NOT EXISTS metrics_buckets (
  75. router_id TEXT NOT NULL,
  76. bucket_ts INTEGER NOT NULL,
  77. n INTEGER NOT NULL,
  78. min_ts INTEGER NOT NULL,
  79. cpu_min REAL, cpu_max REAL, cpu_avg REAL,
  80. ram_min REAL, ram_max REAL, ram_avg REAL,
  81. temp_min REAL, temp_max REAL, temp_avg REAL,
  82. lat_min REAL, lat_max REAL, lat_avg REAL,
  83. rx_min REAL, rx_max REAL, rx_avg REAL,
  84. tx_min REAL, tx_max REAL, tx_avg REAL,
  85. PRIMARY KEY (router_id, bucket_ts)
  86. );
  87. CREATE INDEX IF NOT EXISTS idx_metrics_buckets_ts ON metrics_buckets(bucket_ts);
  88. CREATE TABLE IF NOT EXISTS metrics_daily (
  89. router_id TEXT NOT NULL,
  90. date TEXT NOT NULL,
  91. n INTEGER NOT NULL,
  92. cpu_avg REAL, ram_avg REAL, temp_avg REAL,
  93. lat_avg REAL, rx_avg REAL, tx_avg REAL,
  94. rx_total REAL, tx_total REAL,
  95. -- up_min: LEGACY (#987). Minutos de recolección asumiendo poll de 5 s
  96. -- (SUM(n) * 5 / 60): con cualquier otro intervalo miente (con poll de 30 s
  97. -- da 240 min/día). Los informes ya no lo leen; usan up_count.
  98. up_min INTEGER NOT NULL DEFAULT 0,
  99. -- up_count: nº de buckets de 5 min con datos (288 = día completo). Es la
  100. -- base de la disponibilidad de los informes: agnóstica del intervalo de
  101. -- poll mientras este sea < 5 min.
  102. up_count INTEGER NOT NULL DEFAULT 0,
  103. PRIMARY KEY (router_id, date)
  104. );
  105. -- Estadísticas AdGuard por tick
  106. CREATE TABLE IF NOT EXISTS adguard_stats (
  107. ts INTEGER NOT NULL,
  108. queries INTEGER, blocked INTEGER
  109. );
  110. CREATE INDEX IF NOT EXISTS idx_adguard_ts ON adguard_stats(ts);
  111. -- Usuarios (multiusuario: el admin gestiona altas/bajas/passwords)
  112. CREATE TABLE IF NOT EXISTS users (
  113. id INTEGER PRIMARY KEY AUTOINCREMENT,
  114. username TEXT UNIQUE NOT NULL,
  115. pass_hash TEXT NOT NULL,
  116. role TEXT NOT NULL DEFAULT 'user',
  117. created_at INTEGER NOT NULL
  118. );
  119. -- Última atribución conocida por MAC
  120. CREATE TABLE IF NOT EXISTS device_attrib (
  121. mac TEXT PRIMARY KEY,
  122. router_id TEXT,
  123. band TEXT,
  124. signal_dbm INTEGER,
  125. last_seen INTEGER NOT NULL
  126. );
  127. -- Primera/última vez que el server vio online a cada cliente (#954).
  128. -- A diferencia de device_events (transiciones, con retención) y de
  129. -- device_attrib (solo wireless), aquí entra TODA MAC vista online en el
  130. -- ciclo del poller; first_seen no se toca nunca tras el alta.
  131. CREATE TABLE IF NOT EXISTS device_seen (
  132. mac TEXT PRIMARY KEY,
  133. first_seen INTEGER NOT NULL,
  134. last_seen INTEGER NOT NULL
  135. );
  136. -- #1278: lápidas de clientes borrados a mano. Sin esto, cualquier fuente
  137. -- que vuelva a reportar la MAC online (una entrada cacheada del AP, un
  138. -- colector) la re-alta y el borrado "no funciona".
  139. CREATE TABLE IF NOT EXISTS deleted_clients (
  140. mac TEXT PRIMARY KEY,
  141. deleted_at INTEGER NOT NULL
  142. );
  143. -- #1151: cliente con varias MACs (un hostname, nunca simultáneas): cada fila
  144. -- dice "esta MAC es el mismo cliente que canonical". Clave = alias; el
  145. -- canónico no tiene fila propia (ausencia de fila = MAC canónica).
  146. CREATE TABLE IF NOT EXISTS device_links (
  147. mac TEXT PRIMARY KEY,
  148. canonical TEXT NOT NULL
  149. );
  150. -- Routers configurados
  151. CREATE TABLE IF NOT EXISTS routers (
  152. id TEXT PRIMARY KEY,
  153. name TEXT,
  154. host TEXT NOT NULL,
  155. type TEXT NOT NULL DEFAULT 'openwrt',
  156. is_gateway INTEGER NOT NULL DEFAULT 0,
  157. created_at INTEGER NOT NULL
  158. );
  159. -- Allowlist de dispositivos confiables (issue #196): una MAC conocida no
  160. -- dispara "dispositivo desconocido" y su name se usa como alias.
  161. CREATE TABLE IF NOT EXISTS known_macs (
  162. mac TEXT PRIMARY KEY,
  163. name TEXT NOT NULL,
  164. note TEXT,
  165. created_at INTEGER NOT NULL
  166. );
  167. -- Suscripciones Web Push (Fase 3 Bloque C; sin paridad Node: el push es
  168. -- nuevo en Go). created_at en milisegundos como el resto de epochs.
  169. CREATE TABLE IF NOT EXISTS push_subscriptions (
  170. endpoint TEXT PRIMARY KEY,
  171. keys_auth TEXT NOT NULL,
  172. keys_p256dh TEXT NOT NULL,
  173. user_agent TEXT,
  174. created_at INTEGER NOT NULL
  175. );
  176. -- DLQ de webhooks salientes (Fase 8.7b): eventos no entregados tras agotar
  177. -- reintentos. event_id único (idempotencia del emisor).
  178. CREATE TABLE IF NOT EXISTS webhook_events (
  179. event_id TEXT PRIMARY KEY,
  180. payload TEXT NOT NULL,
  181. sent_at INTEGER NOT NULL,
  182. error TEXT
  183. );
  184. CREATE TABLE IF NOT EXISTS orchestr_plans (
  185. id TEXT PRIMARY KEY,
  186. router_id TEXT NOT NULL,
  187. resource TEXT NOT NULL,
  188. desired TEXT NOT NULL,
  189. diff TEXT NOT NULL,
  190. status TEXT NOT NULL DEFAULT 'pending',
  191. created_by TEXT NOT NULL,
  192. created_at INTEGER NOT NULL,
  193. applied_at INTEGER,
  194. result TEXT
  195. );
  196. CREATE TABLE IF NOT EXISTS orchestr_audit (
  197. id INTEGER PRIMARY KEY AUTOINCREMENT,
  198. plan_id TEXT NOT NULL,
  199. action TEXT NOT NULL,
  200. actor TEXT NOT NULL,
  201. detail TEXT,
  202. ts INTEGER NOT NULL
  203. );
  204. -- roam_events: feed continuo de eventos hostapd/DAWN (Fase 14.5).
  205. -- Ingesta cada 60s via logread grep; dedup por content_hash.
  206. CREATE TABLE IF NOT EXISTS roam_events (
  207. id INTEGER PRIMARY KEY AUTOINCREMENT,
  208. ts_ms INTEGER NOT NULL,
  209. router_id TEXT NOT NULL,
  210. type TEXT NOT NULL,
  211. mac TEXT,
  212. iface TEXT,
  213. detail TEXT,
  214. content_hash TEXT NOT NULL
  215. );
  216. CREATE UNIQUE INDEX IF NOT EXISTS idx_roam_events_dedup ON roam_events(content_hash);
  217. CREATE INDEX IF NOT EXISTS idx_roam_events_ts ON roam_events(ts_ms DESC);
  218. CREATE INDEX IF NOT EXISTS idx_roam_events_router_ts ON roam_events(router_id, ts_ms DESC);
  219. -- device_events: transiciones offline/online detectadas por el poller (issue #184).
  220. -- Generados por el adapter Live en el ciclo de buildDevices; consultables por API.
  221. CREATE TABLE IF NOT EXISTS device_events (
  222. id INTEGER PRIMARY KEY AUTOINCREMENT,
  223. ts_ms INTEGER NOT NULL,
  224. mac TEXT NOT NULL,
  225. router_id TEXT,
  226. state TEXT NOT NULL, -- 'offline' | 'online'
  227. signal_dbm INTEGER,
  228. detail TEXT
  229. );
  230. CREATE INDEX IF NOT EXISTS idx_device_events_ts ON device_events(ts_ms DESC);
  231. CREATE INDEX IF NOT EXISTS idx_device_events_mac_ts ON device_events(mac, ts_ms DESC);
  232. -- Overrides manuales de topología (issue #142, Fase A): capa 2 sobre el
  233. -- autodiscover. El builder los aplica DESPUÉS de inferTopology.
  234. -- kind 'hypervisor' (target MAC): el dispositivo es un hipervisor; los CTs
  235. -- con OUI de hipervisor del mismo puerto se anidan bajo él.
  236. -- kind 'switch' (target MAC): el dispositivo es un switch manual (sin LLDP);
  237. -- el puerto del target pasa a ser nodo managed con esa MAC.
  238. -- kind 'attach' (target MAC, parent MAC): el target cuelga del parent.
  239. CREATE TABLE IF NOT EXISTS topology_overrides (
  240. id TEXT PRIMARY KEY,
  241. mac TEXT NOT NULL, -- target normalizado (minúsculas, '-')
  242. kind TEXT NOT NULL, -- 'hypervisor' | 'switch' | 'attach'
  243. name TEXT, -- nombre personalizado (opcional)
  244. parent TEXT, -- kind='attach': MAC del padre
  245. enabled INTEGER NOT NULL DEFAULT 1,
  246. created_at INTEGER NOT NULL,
  247. updated_at INTEGER NOT NULL
  248. );
  249. CREATE INDEX IF NOT EXISTS idx_topo_overrides_mac ON topology_overrides(mac);
  250. -- Historial de actualizaciones (issue #159): registro de cada apply del
  251. -- updater. En canal rolling main version_from/to son SHAs de commit.
  252. CREATE TABLE IF NOT EXISTS update_history (
  253. id INTEGER PRIMARY KEY AUTOINCREMENT,
  254. event_id TEXT NOT NULL,
  255. ts INTEGER NOT NULL,
  256. action TEXT NOT NULL,
  257. channel TEXT NOT NULL,
  258. version_from TEXT,
  259. version_to TEXT,
  260. initiated_by TEXT NOT NULL DEFAULT '',
  261. status TEXT NOT NULL DEFAULT 'running',
  262. duration_ms INTEGER,
  263. backup_path TEXT,
  264. error TEXT
  265. );
  266. CREATE INDEX IF NOT EXISTS idx_update_history_ts ON update_history(ts DESC);
  267. -- Overrides manuales de dispositivo (issue #437): alias, icono y estado de
  268. -- bloqueo por banda. La clave es la MAC normalizada (minúsculas, ':').
  269. -- #797: name (nombre visible) y device_type (override del tipo clasificado).
  270. CREATE TABLE IF NOT EXISTS device_overrides (
  271. mac TEXT PRIMARY KEY,
  272. icon TEXT,
  273. name TEXT NOT NULL DEFAULT '',
  274. device_type TEXT NOT NULL DEFAULT '',
  275. banned_bands TEXT NOT NULL DEFAULT '', -- lista separada por comas: '2.4,5,6'
  276. notify_offline INTEGER NOT NULL DEFAULT 0, -- issue #1354: alert opt-in cuando se desconecta
  277. name_source TEXT NOT NULL DEFAULT '', -- #2163: fuente de nombre elegida por cliente ('' = automática)
  278. created_at INTEGER NOT NULL,
  279. updated_at INTEGER NOT NULL
  280. );
  281. -- Per-port time series (issue #302): raw (7d) -> 5m (1y) -> daily (forever).
  282. CREATE TABLE IF NOT EXISTS port_series_raw (
  283. router_id TEXT NOT NULL,
  284. port_id TEXT NOT NULL,
  285. ts INTEGER NOT NULL,
  286. rx_bytes INTEGER NOT NULL DEFAULT 0,
  287. tx_bytes INTEGER NOT NULL DEFAULT 0,
  288. rx_errors INTEGER NOT NULL DEFAULT 0,
  289. tx_errors INTEGER NOT NULL DEFAULT 0,
  290. rx_frames INTEGER NOT NULL DEFAULT 0,
  291. tx_frames INTEGER NOT NULL DEFAULT 0,
  292. rx_bps REAL NOT NULL DEFAULT 0,
  293. tx_bps REAL NOT NULL DEFAULT 0,
  294. speed_mbps INTEGER NOT NULL DEFAULT 0,
  295. PRIMARY KEY (router_id, port_id, ts)
  296. );
  297. -- #817: solo el índice por ts (retención). El PK (router_id, port_id, ts) ya
  298. -- cubre las consultas por router/puerto; idx_port_series_raw_rpt era idéntico
  299. -- al PK y se elimina (DROP INDEX en Open para las DBs existentes).
  300. CREATE INDEX IF NOT EXISTS idx_port_series_raw_ts ON port_series_raw(ts);
  301. CREATE TABLE IF NOT EXISTS port_series_5m (
  302. router_id TEXT NOT NULL,
  303. port_id TEXT NOT NULL,
  304. bucket_ts INTEGER NOT NULL,
  305. n INTEGER NOT NULL,
  306. rx_bytes INTEGER NOT NULL DEFAULT 0,
  307. tx_bytes INTEGER NOT NULL DEFAULT 0,
  308. rx_errors INTEGER NOT NULL DEFAULT 0,
  309. tx_errors INTEGER NOT NULL DEFAULT 0,
  310. rx_frames INTEGER NOT NULL DEFAULT 0,
  311. tx_frames INTEGER NOT NULL DEFAULT 0,
  312. rx_bps_min REAL NOT NULL DEFAULT 0,
  313. rx_bps_max REAL NOT NULL DEFAULT 0,
  314. rx_bps_avg REAL NOT NULL DEFAULT 0,
  315. tx_bps_min REAL NOT NULL DEFAULT 0,
  316. tx_bps_max REAL NOT NULL DEFAULT 0,
  317. tx_bps_avg REAL NOT NULL DEFAULT 0,
  318. speed_mbps INTEGER NOT NULL DEFAULT 0,
  319. PRIMARY KEY (router_id, port_id, bucket_ts)
  320. );
  321. CREATE INDEX IF NOT EXISTS idx_port_series_5m_ts ON port_series_5m(bucket_ts);
  322. CREATE TABLE IF NOT EXISTS port_series_daily (
  323. router_id TEXT NOT NULL,
  324. port_id TEXT NOT NULL,
  325. date TEXT NOT NULL,
  326. n INTEGER NOT NULL,
  327. rx_bytes INTEGER NOT NULL DEFAULT 0,
  328. tx_bytes INTEGER NOT NULL DEFAULT 0,
  329. rx_errors INTEGER NOT NULL DEFAULT 0,
  330. tx_errors INTEGER NOT NULL DEFAULT 0,
  331. rx_frames INTEGER NOT NULL DEFAULT 0,
  332. tx_frames INTEGER NOT NULL DEFAULT 0,
  333. rx_bps_avg REAL NOT NULL DEFAULT 0,
  334. tx_bps_avg REAL NOT NULL DEFAULT 0,
  335. speed_mbps INTEGER NOT NULL DEFAULT 0,
  336. PRIMARY KEY (router_id, port_id, date)
  337. );
  338. -- wifi_scans: scans pasivos de vecinos recogidos por el agente (#452).
  339. -- Se guardan por push para poder hacer recomendaciones de canal.
  340. CREATE TABLE IF NOT EXISTS wifi_scans (
  341. id INTEGER PRIMARY KEY AUTOINCREMENT,
  342. router_id TEXT NOT NULL,
  343. iface TEXT NOT NULL,
  344. bssid TEXT NOT NULL,
  345. ssid TEXT NOT NULL DEFAULT '',
  346. channel INTEGER NOT NULL,
  347. freq INTEGER NOT NULL,
  348. signal_dbm INTEGER NOT NULL,
  349. width_mhz INTEGER NOT NULL DEFAULT 0,
  350. ts INTEGER NOT NULL
  351. );
  352. CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
  353. CREATE INDEX IF NOT EXISTS idx_wifi_scans_channel ON wifi_scans(channel, freq);
  354. -- wifi_scan_outcomes (#1848): ultimo resultado del scan de vecinos por
  355. -- interfaz. Guarda el motivo cuando el driver lo rechaza, para que la vista
  356. -- de canales no muestre una banda vacia sin explicacion. Es el ultimo estado
  357. -- conocido, no un historico: una fila por router e interfaz.
  358. CREATE TABLE IF NOT EXISTS wifi_scan_outcomes (
  359. router_id TEXT NOT NULL,
  360. iface TEXT NOT NULL,
  361. phy INTEGER NOT NULL DEFAULT -1,
  362. bss INTEGER NOT NULL DEFAULT 0,
  363. err TEXT NOT NULL DEFAULT '',
  364. ts INTEGER NOT NULL,
  365. PRIMARY KEY (router_id, iface)
  366. );
  367. -- Firmware upgrades de routers OpenWrt (#453).
  368. -- firmware_targets: información de firmware soportado por router.
  369. CREATE TABLE IF NOT EXISTS firmware_targets (
  370. router_id TEXT PRIMARY KEY,
  371. model TEXT NOT NULL,
  372. current_version TEXT NOT NULL DEFAULT '',
  373. target_version TEXT NOT NULL DEFAULT '',
  374. target_url TEXT NOT NULL DEFAULT '',
  375. checksum TEXT NOT NULL DEFAULT '',
  376. updated_at INTEGER NOT NULL
  377. );
  378. -- firmware_upgrades: historial y estado de upgrades en curso.
  379. CREATE TABLE IF NOT EXISTS firmware_upgrades (
  380. id INTEGER PRIMARY KEY AUTOINCREMENT,
  381. router_id TEXT NOT NULL,
  382. target_version TEXT NOT NULL,
  383. target_url TEXT NOT NULL,
  384. checksum TEXT NOT NULL DEFAULT '',
  385. status TEXT NOT NULL DEFAULT 'idle',
  386. error TEXT NOT NULL DEFAULT '',
  387. backup_path TEXT,
  388. started_at INTEGER NOT NULL,
  389. finished_at INTEGER,
  390. -- #494: programación de upgrades desatendidos (epoch ms UTC; NULL = flujo
  391. -- manual/inmediato sin programar). started_at/finished_at siguen en segundos.
  392. scheduled_for INTEGER
  393. );
  394. CREATE INDEX IF NOT EXISTS idx_firmware_upgrades_router_started ON firmware_upgrades(router_id, started_at DESC);
  395. -- Log de alertas persistido (issue #798): el historial sobrevive a reinicios
  396. -- (el self-update del updater reinicia el proceso y antes se perdía entero).
  397. -- La lista en memoria sigue acotada a los 100 más recientes; aquí se guardan
  398. -- hasta 500 para poder restaurarlos. read_flag va aparte en kv (readSet), pero
  399. -- se espeja en la columna para restaurarlo al cargar. (OJO: "read" crudo es
  400. -- problemático como nombre de columna; por eso read_flag.)
  401. CREATE TABLE IF NOT EXISTS alert_log (
  402. id TEXT PRIMARY KEY,
  403. ts INTEGER NOT NULL,
  404. category TEXT NOT NULL,
  405. type TEXT NOT NULL DEFAULT '',
  406. severity TEXT NOT NULL DEFAULT '',
  407. urgent INTEGER NOT NULL DEFAULT 0,
  408. title TEXT NOT NULL,
  409. description TEXT NOT NULL DEFAULT '',
  410. hint TEXT NOT NULL DEFAULT '',
  411. router_id TEXT NOT NULL DEFAULT '',
  412. suppressed_by TEXT NOT NULL DEFAULT '',
  413. vars TEXT NOT NULL DEFAULT '',
  414. read_flag INTEGER NOT NULL DEFAULT 0,
  415. resolves TEXT NOT NULL DEFAULT ''
  416. );
  417. CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
  418. -- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
  419. -- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):
  420. -- rack_mounts.device_mac apunta a esa identidad y device_rack_profile guarda
  421. -- el modelo físico compartido (faceplate, altura U, span de columnas,
  422. -- color y puertos con posición). Los montajes con device_mac NULL son
  423. -- accesorios (blank, shelf, patch panel, PDU): su tamaño lo define el
  424. -- faceplate del catálogo.
  425. CREATE TABLE IF NOT EXISTS racks (
  426. id TEXT PRIMARY KEY,
  427. name TEXT NOT NULL,
  428. u_height INTEGER NOT NULL,
  429. width_standard TEXT NOT NULL DEFAULT '19', -- '19' | '10'
  430. numbering TEXT NOT NULL DEFAULT 'bottom-up', -- solo cambia etiquetas, nunca la geometría
  431. style_json TEXT NOT NULL DEFAULT '{}',
  432. location TEXT,
  433. position_x REAL NOT NULL DEFAULT 0,
  434. position_y REAL NOT NULL DEFAULT 0
  435. );
  436. CREATE TABLE IF NOT EXISTS device_rack_profile (
  437. mac TEXT PRIMARY KEY,
  438. faceplate_id TEXT NOT NULL DEFAULT '',
  439. u_height INTEGER NOT NULL DEFAULT 1,
  440. col_span INTEGER NOT NULL DEFAULT 12,
  441. color TEXT NOT NULL DEFAULT '',
  442. ports_json TEXT NOT NULL DEFAULT '[]'
  443. );
  444. CREATE TABLE IF NOT EXISTS rack_mounts (
  445. id TEXT PRIMARY KEY,
  446. rack_id TEXT NOT NULL REFERENCES racks(id) ON DELETE CASCADE,
  447. device_mac TEXT REFERENCES device_rack_profile(mac) ON DELETE SET NULL, -- NULL = accesorio
  448. faceplate_id TEXT NOT NULL DEFAULT '', -- accesorios; el de dispositivos vive en device_rack_profile
  449. u_start INTEGER NOT NULL, -- 1-based, SIEMPRE contado desde el rail inferior
  450. col_start INTEGER NOT NULL DEFAULT 0, -- 0-based
  451. label TEXT,
  452. status_pin TEXT NOT NULL DEFAULT 'auto', -- 'auto' → seguir el estado que conoce el poller
  453. port_visibility TEXT NOT NULL DEFAULT 'auto'
  454. );
  455. CREATE INDEX IF NOT EXISTS idx_rack_mounts_rack ON rack_mounts(rack_id);
  456. -- Cables port-to-port (relación propia, no edges del canvas lógico).
  457. -- Pueden cruzar racks. Un puerto normal admite exactamente 1 cable; los
  458. -- patch panels (pass-through) admiten 2 (tirada de pared al rear + patch al
  459. -- switch al front). Cobre vs fibra se deriva del puerto de origen del patch.
  460. CREATE TABLE IF NOT EXISTS rack_cables (
  461. id TEXT PRIMARY KEY,
  462. from_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
  463. from_port TEXT NOT NULL,
  464. to_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
  465. to_port TEXT NOT NULL,
  466. type TEXT NOT NULL DEFAULT 'ethernet', -- 'ethernet' | 'fiber'
  467. label TEXT,
  468. properties_json TEXT NOT NULL DEFAULT '{}', -- key/value libre
  469. origin TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'imported' | 'detected'
  470. created_at INTEGER NOT NULL
  471. );
  472. CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
  473. CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
  474. -- External router integrations (#1674): pushers de routers externos
  475. -- (MikroTik RouterOS, Asuswrt) gestionados desde la app. El slug es el id
  476. -- del router external asociado (push autenticado por Bearer token de agente,
  477. -- agent.token.<slug>). La contraseña nunca se persiste: vive en el fichero
  478. -- de entorno <data>/integrations/<slug>.env (0600).
  479. CREATE TABLE IF NOT EXISTS router_integrations (
  480. slug TEXT PRIMARY KEY,
  481. vendor TEXT NOT NULL,
  482. mode TEXT NOT NULL,
  483. host TEXT NOT NULL,
  484. username TEXT NOT NULL,
  485. version TEXT NOT NULL DEFAULT '',
  486. asset TEXT NOT NULL DEFAULT '',
  487. arch TEXT NOT NULL,
  488. interval_s INTEGER NOT NULL,
  489. enabled INTEGER NOT NULL DEFAULT 0,
  490. state TEXT NOT NULL DEFAULT 'pending',
  491. last_error TEXT NOT NULL DEFAULT '',
  492. last_start_ms INTEGER NOT NULL DEFAULT 0,
  493. created_at INTEGER NOT NULL,
  494. updated_at INTEGER NOT NULL
  495. );
  496. CREATE INDEX IF NOT EXISTS idx_router_integrations_vendor ON router_integrations(vendor);
  497. -- Agregado horario del query log de AdGuard (#2078): por dispositivo (MAC) y
  498. -- dominio. MAC vacía = sin atribuir (IP sin correspondencia en device_seen).
  499. -- Nunca se guarda el log crudo. Retención: 7 días (Maintenance).
  500. CREATE TABLE IF NOT EXISTS dns_activity (
  501. mac TEXT NOT NULL,
  502. domain TEXT NOT NULL,
  503. hour_ts INTEGER NOT NULL, -- inicio de la hora, ms epoch
  504. queries INTEGER NOT NULL DEFAULT 0,
  505. blocked INTEGER NOT NULL DEFAULT 0,
  506. first_seen INTEGER NOT NULL,
  507. last_seen INTEGER NOT NULL,
  508. PRIMARY KEY (mac, domain, hour_ts)
  509. );
  510. CREATE INDEX IF NOT EXISTS idx_dns_activity_hour ON dns_activity(hour_ts);
  511. CREATE INDEX IF NOT EXISTS idx_dns_activity_domain ON dns_activity(domain, hour_ts);
  512. -- Primera vez que se vio cada dominio (#2078): alimenta el aviso de dominios
  513. -- nuevos. Retención: 90 días (Maintenance).
  514. CREATE TABLE IF NOT EXISTS dns_domain_first (
  515. domain TEXT PRIMARY KEY,
  516. first_seen INTEGER NOT NULL,
  517. mac TEXT NOT NULL DEFAULT ''
  518. );
  519. CREATE INDEX IF NOT EXISTS idx_dns_domain_first_ts ON dns_domain_first(first_seen);
  520. `
  521. // DB envuelve *sql.DB con los jobs y helpers de paridad.
  522. type DB struct {
  523. *sql.DB
  524. Path string
  525. stop chan struct{}
  526. wg sync.WaitGroup
  527. close sync.Once
  528. // rollbackJournal: escape hatch (#1700) para journal DELETE (comportamiento
  529. // on-box previo). Los wal_checkpoint de mantenimiento se omiten en este
  530. // modo; en WAL (el default de todos los despliegues) sí corren.
  531. rollbackJournal bool
  532. // PortSeries: per-port time series store (issue #302).
  533. PortSeries *portseries.Store
  534. // WGSeries: contadores por peer de WireGuard con ventana real (#2019).
  535. WGSeries *wgseries.Store
  536. // ClientBW: per-client bandwidth store (issue #337/#551). Wiring añadido
  537. // en el #551: la ingesta escribe samples delta por (mac, router).
  538. ClientBW *clientbw.Store
  539. }
  540. // NowMS devuelve el epoch actual en milisegundos (como Date.now()).
  541. func NowMS() int64 { return time.Now().UnixMilli() }
  542. // OpenOption configura Open (variádica: los callers existentes no cambian).
  543. type OpenOption func(*openOptions)
  544. type openOptions struct {
  545. rollbackJournal bool
  546. // tempStore: 'memory'|'file'|'default' (#1700). Vacío = memory.
  547. tempStore string
  548. }
  549. // WithRollbackJournal: `journal_mode=DELETE` + `synchronous=FULL` en vez de
  550. // WAL+NORMAL. Histórico modo on-box (Fase 9 R6): se pensaba que el fichero
  551. // -wal y sus checkpoints eran el churn caro, pero las medidas de la issue
  552. // #1700 demostraron lo contrario (45 GB/día en DELETE+FULL frente a 13.7 en
  553. // WAL con la misma flota: cada transacción reescribía páginas + journal y
  554. // ext4 duplicaba todo con su propio journal). Desde #1700 TODOS los
  555. // despliegues van en WAL+NORMAL por defecto y esta opción es solo el escape
  556. // hatch para restaurar el modo anterior (NETPULSE_DB_ROLLBACK_JOURNAL=1).
  557. // Los wal_checkpoint de mantenimiento se omiten en este modo.
  558. func WithRollbackJournal() OpenOption {
  559. return func(o *openOptions) { o.rollbackJournal = true }
  560. }
  561. // WithTempStore fija PRAGMA temp_store: 'memory'|'file'|'default' (#1700).
  562. // Por defecto TODOS los despliegues van en 'memory': las agregaciones
  563. // (GROUP BY/ORDER BY sobre expresiones, p. ej. buckets de métricas y
  564. // channel plan) hacen spill a ficheros temporales etilqs_*; el reporte
  565. // midió ~9 GB/día de escrituras en esos temporales con una BD de ~100 MB.
  566. // El coste en RAM de guardarlos (unos MB por query) es trivial frente a ese
  567. // volumen, y crítico en un USB (on-box). 'file'/'default' quedan para
  568. // diagnosticar con el comportamiento clásico.
  569. func WithTempStore(mode string) OpenOption {
  570. return func(o *openOptions) { o.tempStore = strings.ToLower(mode) }
  571. }
  572. // Open abre (o crea) dir/netpulse.db, ejecuta la migración Node→Go si la
  573. // DB ya existía con esquema Node (backup atómico antes de tocar nada),
  574. // aplica pragmas, crea el schema y arranca el mantenimiento horario. dir es
  575. // DB_DIR, que por defecto es DATA_DIR.
  576. func Open(dir string, opts ...OpenOption) (*DB, error) {
  577. var o openOptions
  578. for _, opt := range opts {
  579. opt(&o)
  580. }
  581. // #1795: el grupo del servicio puede leer backups y datos sin ser owner.
  582. if err := os.MkdirAll(dir, 0o770); err != nil {
  583. return nil, err
  584. }
  585. if err := os.Chmod(dir, 0o770); err != nil {
  586. return nil, err
  587. }
  588. dbPath := filepath.Join(dir, databaseFile)
  589. // Migración Node→Go (§12 del SPEC): si el fichero ya existe con esquema
  590. // Node, backup + importación (preserva users/kv/sessions/routers/metrics).
  591. rep, err := MigrateNodeDB(dbPath)
  592. if err != nil {
  593. return nil, fmt.Errorf("Node→Go migration: %w", err)
  594. }
  595. if rep != nil {
  596. rep.Log()
  597. }
  598. // Una sola conexión: better-sqlite3 es síncrono/serial; con maxOpenConns=1
  599. // Go serializa igual y evita SQLITE_BUSY en WAL.
  600. sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
  601. if err != nil {
  602. return nil, err
  603. }
  604. sqldb.SetMaxOpenConns(1)
  605. pragmas := []string{
  606. "PRAGMA journal_mode = WAL",
  607. "PRAGMA synchronous = NORMAL",
  608. "PRAGMA foreign_keys = ON",
  609. }
  610. if o.rollbackJournal {
  611. // Escape hatch (#1700, antes modo on-box): una DB previa en WAL se
  612. // convierte sola: con una única conexión el cambio de journal_mode
  613. // hace checkpoint y elimina el -wal.
  614. pragmas = []string{
  615. "PRAGMA journal_mode = DELETE",
  616. "PRAGMA synchronous = FULL",
  617. "PRAGMA foreign_keys = ON",
  618. }
  619. }
  620. // PRAGMA temp_store (#1700): con MaxOpenConns(1) la única conexión
  621. // compartida hereda el pragma para todas las queries (si el pool la
  622. // recrea tras un error, SQLite vuelve al default; caso marginal).
  623. switch o.tempStore {
  624. case "", "memory":
  625. pragmas = append(pragmas, "PRAGMA temp_store = MEMORY")
  626. case "file":
  627. pragmas = append(pragmas, "PRAGMA temp_store = FILE")
  628. case "default":
  629. // sin pragma: comportamiento SQLite por defecto (fichero)
  630. }
  631. for _, p := range pragmas {
  632. if _, err := sqldb.Exec(p); err != nil {
  633. sqldb.Close()
  634. return nil, fmt.Errorf("pragma %q: %w", p, err)
  635. }
  636. }
  637. // Log del modo efectivo (#1700): lo que manda es lo que SQLite aceptó
  638. // (p. ej. un filesystem sin soporte WAL dejaría DELETE); una línea al
  639. // arrancar evita diagnosticar a ciegas el volumen de escrituras.
  640. var jMode any
  641. var tMode any
  642. _ = sqldb.QueryRow("PRAGMA journal_mode").Scan(&jMode)
  643. _ = sqldb.QueryRow("PRAGMA temp_store").Scan(&tMode)
  644. log.Printf("[netpulse] db: journal_mode=%v temp_store=%v", jMode, tMode)
  645. if _, err := sqldb.Exec(schemaSQL); err != nil {
  646. sqldb.Close()
  647. return nil, fmt.Errorf("schema: %w", err)
  648. }
  649. // Migraciones tolerantes (ALTER solo si falta la columna; errores tragados)
  650. migrate(sqldb, "sessions", "ua", "ALTER TABLE sessions ADD COLUMN ua TEXT")
  651. migrate(sqldb, "sessions", "user_id", "ALTER TABLE sessions ADD COLUMN user_id INTEGER")
  652. // #1334: dueño autenticado e idioma efectivo de la UI por suscripción push.
  653. migrate(sqldb, "push_subscriptions", "user_id", "ALTER TABLE push_subscriptions ADD COLUMN user_id INTEGER")
  654. migrate(sqldb, "push_subscriptions", "language", "ALTER TABLE push_subscriptions ADD COLUMN language TEXT")
  655. migrate(sqldb, "users", "language", "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
  656. // SPEC-65 D65-5: nombre visible por usuario ("" = usar el username).
  657. migrate(sqldb, "users", "display_name", "ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''")
  658. migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
  659. // #1917: modo de inventario por unidad. ""/"auto" = comportamiento de
  660. // siempre (agente si lo hay, SSH si no), "agent" = solo agente (el antiguo
  661. // agent_only), "ssh" = nunca esperar agente: se inventaria por SSH y no
  662. // alerta por la ausencia de un agente que no va a existir.
  663. migrate(sqldb, "routers", "inventory_mode", "ALTER TABLE routers ADD COLUMN inventory_mode TEXT NOT NULL DEFAULT ''")
  664. migrate(sqldb, "routers", "discovery_overrides", "ALTER TABLE routers ADD COLUMN discovery_overrides TEXT NOT NULL DEFAULT ''")
  665. // issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
  666. migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
  667. // Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.
  668. migrate(sqldb, "wifi_scans", "width_mhz", "ALTER TABLE wifi_scans ADD COLUMN width_mhz INTEGER NOT NULL DEFAULT 0")
  669. // #1349: el evento resuelto NO se borra del log: queda marcado con su
  670. // ts de resolución para revisión posterior (y el evento de cierre lo
  671. // referencia con `resolves`). 0 = activo/no resuelto.
  672. migrate(sqldb, "alert_log", "resolved_ts", "ALTER TABLE alert_log ADD COLUMN resolved_ts INTEGER NOT NULL DEFAULT 0")
  673. // #1466: `resolves` (IDs de los eventos que un cierre resolvió) en JSON.
  674. // Sin persistirlo, tras un reinicio el evento de cierre perdía sus
  675. // referencias y el bloque "Resuelve N eventos" desaparecía del log.
  676. migrate(sqldb, "alert_log", "resolves", "ALTER TABLE alert_log ADD COLUMN resolves TEXT NOT NULL DEFAULT ''")
  677. // issue #241: target de firmware por router (string libre; NULL/"" = sin comprobar).
  678. migrate(sqldb, "routers", "firmware_target", "ALTER TABLE routers ADD COLUMN firmware_target TEXT")
  679. // issue #309: SNMP polling for managed switches.
  680. migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
  681. // #1145: último nombre conocido del cliente (retención indefinida).
  682. migrate(sqldb, "device_seen", "name", "ALTER TABLE device_seen ADD COLUMN name TEXT NOT NULL DEFAULT ''")
  683. // #2163: evidencia que produjo el nombre elegido; vacía en filas antiguas.
  684. migrate(sqldb, "device_seen", "name_source", "ALTER TABLE device_seen ADD COLUMN name_source TEXT NOT NULL DEFAULT ''")
  685. // #1151: última IP conocida (los fantasmas la conservan para la lista y
  686. // las sugerencias de enlace).
  687. migrate(sqldb, "device_seen", "ip", "ALTER TABLE device_seen ADD COLUMN ip TEXT NOT NULL DEFAULT ''")
  688. // #1315: último tipo inferido (no override) del cliente: al expirar el
  689. // lease la clasificación viva cae en "desconocido" y el icono se perdía;
  690. // el valor retenido lo conserva (stickiness del tipo, solo se escribe
  691. // cuando la inferencia viva no es el genérico).
  692. migrate(sqldb, "device_seen", "device_type", "ALTER TABLE device_seen ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
  693. // issue #863: sondeo HTTP de la consola de switches RTLPlayground. DEFAULT 1
  694. // = comportamiento previo; se desactiva por router (la consola del firmware
  695. // tiene una sola sesión global y cada login tumba la sesión humana).
  696. migrate(sqldb, "routers", "console_polling", "ALTER TABLE routers ADD COLUMN console_polling INTEGER NOT NULL DEFAULT 1")
  697. migrate(sqldb, "routers", "snmp_community", "ALTER TABLE routers ADD COLUMN snmp_community TEXT")
  698. migrate(sqldb, "routers", "snmp_port", "ALTER TABLE routers ADD COLUMN snmp_port INTEGER NOT NULL DEFAULT 0")
  699. // issue #414: intervalo de polling SNMP configurable (segundos; default 60).
  700. migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
  701. // #2042: versión de SNMP por unidad ("1", "2c" o "3"). DEFAULT '2c' deja
  702. // las filas existentes con el comportamiento actual (comunidad).
  703. migrate(sqldb, "routers", "snmp_version", "ALTER TABLE routers ADD COLUMN snmp_version TEXT NOT NULL DEFAULT '2c'")
  704. // #2042: credenciales USM para SNMPv3. Sin usuario no hay v3 posible, así
  705. // que "" = v3 sin configurar. Los dos passphrases son secretos: no salen
  706. // nunca por HTTP (mismo criterio que snmp_community).
  707. migrate(sqldb, "routers", "snmp_v3_user", "ALTER TABLE routers ADD COLUMN snmp_v3_user TEXT NOT NULL DEFAULT ''")
  708. migrate(sqldb, "routers", "snmp_v3_security_level", "ALTER TABLE routers ADD COLUMN snmp_v3_security_level TEXT NOT NULL DEFAULT 'authPriv'")
  709. migrate(sqldb, "routers", "snmp_v3_auth_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_proto TEXT NOT NULL DEFAULT 'SHA'")
  710. migrate(sqldb, "routers", "snmp_v3_auth_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_pass TEXT NOT NULL DEFAULT ''")
  711. migrate(sqldb, "routers", "snmp_v3_priv_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_proto TEXT NOT NULL DEFAULT 'AES'")
  712. migrate(sqldb, "routers", "snmp_v3_priv_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_pass TEXT NOT NULL DEFAULT ''")
  713. migrate(sqldb, "routers", "agent_interval", "ALTER TABLE routers ADD COLUMN agent_interval INTEGER NOT NULL DEFAULT 0")
  714. // issue #605: puerto SSH por router (dropbear en puerto no estándar).
  715. migrate(sqldb, "routers", "ssh_port", "ALTER TABLE routers ADD COLUMN ssh_port INTEGER NOT NULL DEFAULT 22")
  716. // issue #1085: pausa de una unidad de flota (sin sondeo ni alertas, con
  717. // insignia en la lista y fuera de los desplegables; el histórico se
  718. // conserva). 0/ausente (columna nueva) = activa.
  719. migrate(sqldb, "routers", "disabled", "ALTER TABLE routers ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0")
  720. // issue #716: umbral de alerta por temperatura alta (°C). NULL = 65 default.
  721. migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
  722. // issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
  723. migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
  724. // issue #761: motor del upgrade ("" = clásico URL+checksum, "owut" = ASU).
  725. migrate(sqldb, "firmware_upgrades", "engine", "ALTER TABLE firmware_upgrades ADD COLUMN engine TEXT NOT NULL DEFAULT ''")
  726. // issue #797: nombre visible y tipo de dispositivo sobreescritos a mano.
  727. migrate(sqldb, "device_overrides", "name", "ALTER TABLE device_overrides ADD COLUMN name TEXT NOT NULL DEFAULT ''")
  728. migrate(sqldb, "device_overrides", "device_type", "ALTER TABLE device_overrides ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
  729. // issue #1354: opt-in alert when a marked device goes offline (0 = off).
  730. migrate(sqldb, "device_overrides", "notify_offline", "ALTER TABLE device_overrides ADD COLUMN notify_offline INTEGER NOT NULL DEFAULT 0")
  731. // #2163: fuente de nombre elegida a mano para un cliente ('' = automática).
  732. migrate(sqldb, "device_overrides", "name_source", "ALTER TABLE device_overrides ADD COLUMN name_source TEXT NOT NULL DEFAULT ''")
  733. // #1354: las filas de alert_log tipadas "device-offline" son eventos de
  734. // ROUTER offline (ese slug lo emitía trackRouterOffline antes de partirlo
  735. // en router-offline). Discriminador idempotente: las filas del router
  736. // llevan "host" en vars; las de cliente nuevas, no (vars = device/router).
  737. if _, err := sqldb.Exec(`UPDATE alert_log SET type = 'router-offline' WHERE type = 'device-offline' AND vars LIKE '%"host"%'`); err != nil {
  738. log.Printf("[netpulse] warning: could not migrate router-offline alert type: %v", err)
  739. }
  740. // #817: port_series_raw tenía dos índices idénticos a su PK, creados por
  741. // error en db.go y portseries.go. Se eliminan de forma idempotente (no se
  742. // vuelven a crear); el VACUUM nocturno recupera el espacio en las DBs ya
  743. // existentes (~33 MB en una instancia de 266 MB).
  744. for _, idx := range []string{"idx_port_series_raw_rpt", "idx_port_series_raw_router_port_ts"} {
  745. if _, err := sqldb.Exec("DROP INDEX IF EXISTS " + idx); err != nil {
  746. log.Printf("[netpulse] warning: could not drop index %s: %v", idx, err)
  747. }
  748. }
  749. // RouterOS and Asuswrt/Merlin moved to external integrations (#1574,
  750. // #1579). Keep existing units visible until their owner deploys the
  751. // pusher. Legacy credential columns remain in place as inert schema.
  752. if _, err := sqldb.Exec(`UPDATE routers SET type = 'external', agent_only = 1 WHERE type IN ('routeros', 'asuswrt')`); err != nil {
  753. log.Printf("[netpulse] warning: could not migrate RouterOS/Asuswrt routers to external: %v", err)
  754. }
  755. // #1129: las MACs de roam_events se ingirieron en minúsculas (así vienen
  756. // en los logs hostapd/dawn/usteer) mientras el resto de la app canonicaliza
  757. // a MAYÚSCULAS (#960): el filtro por cliente no casaba con el histórico.
  758. // Normalización one-shot de las filas existentes (la ingesta nueva ya
  759. // normaliza, ver roamevents.ParseLogreadLine).
  760. if _, err := sqldb.Exec("UPDATE roam_events SET mac = UPPER(mac) WHERE mac IS NOT NULL AND mac != UPPER(mac)"); err != nil {
  761. log.Printf("[netpulse] warning: could not normalize roam_events MACs: %v", err)
  762. }
  763. // Si no hubo migración Node (instalación fresca creada por Go), marca la
  764. // DB para que el siguiente arranque no dispare una "migración" espuria
  765. // (backup + reset de login_attempts) sobre una DB ya Go.
  766. if rep == nil {
  767. _, _ = sqldb.Exec(
  768. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
  769. migrationMarkerKey, time.Now().Format(time.RFC3339),
  770. )
  771. }
  772. d := &DB{DB: sqldb, Path: dbPath, stop: make(chan struct{}), rollbackJournal: o.rollbackJournal}
  773. ps, err := portseries.NewStore(sqldb)
  774. if err != nil {
  775. sqldb.Close()
  776. return nil, fmt.Errorf("port_series store: %w", err)
  777. }
  778. d.PortSeries = ps
  779. wg, err := wgseries.NewStore(sqldb)
  780. if err != nil {
  781. sqldb.Close()
  782. return nil, fmt.Errorf("wg_peer_series store: %w", err)
  783. }
  784. d.WGSeries = wg
  785. cb, err := clientbw.NewStore(sqldb)
  786. if err != nil {
  787. sqldb.Close()
  788. return nil, fmt.Errorf("client_bw store: %w", err)
  789. }
  790. d.ClientBW = cb
  791. migrateLowercaseMACTables(sqldb)
  792. d.wg.Add(1)
  793. go d.maintenanceLoop()
  794. return d, nil
  795. }
  796. // migrateLowercaseMACTables pasa a la forma canónica en mayúsculas
  797. // (AA:BB:CC:DD:EE:FF) las tablas que históricamente guardaban MACs en
  798. // minúsculas. Corre tras clientbw.NewStore para que client_bw_* ya existan.
  799. // Corre una sola vez: todos los pasos van en una transacción que, al terminar
  800. // bien, deja la marca macUpperMigratedKey en kv; los arranques siguientes no
  801. // vuelven a recorrer client_bw_* (millones de filas). Si un paso falla, se
  802. // registra un warning, se deshace todo y se reintenta en el siguiente arranque;
  803. // el arranque nunca se aborta.
  804. func migrateLowercaseMACTables(sqldb *sql.DB) {
  805. var done int
  806. if err := sqldb.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", macUpperMigratedKey).Scan(&done); err == nil && done > 0 {
  807. return
  808. }
  809. type step struct {
  810. name string
  811. sql string
  812. }
  813. steps := []step{
  814. // device_overrides: PK (mac), sobrevive la fila con updated_at más reciente
  815. // (empate: la que ya esté en forma canónica, luego mayor rowid).
  816. {
  817. name: "dedup device_overrides MACs",
  818. sql: `DELETE FROM device_overrides
  819. WHERE ` + macOnlyMatch("mac") + `
  820. AND EXISTS (
  821. SELECT 1 FROM device_overrides o2
  822. WHERE ` + macOnlyMatch("o2.mac") + `
  823. AND UPPER(REPLACE(o2.mac, '-', ':')) = UPPER(REPLACE(device_overrides.mac, '-', ':'))
  824. AND o2.rowid != device_overrides.rowid
  825. AND (
  826. o2.updated_at > device_overrides.updated_at
  827. OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) > (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))))
  828. OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) = (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))) AND o2.rowid > device_overrides.rowid)
  829. )
  830. )`,
  831. },
  832. {
  833. name: "normalize device_overrides MACs",
  834. sql: `UPDATE device_overrides
  835. SET mac = UPPER(REPLACE(mac, '-', ':'))
  836. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  837. },
  838. // topology_overrides: PK (id = mac). mac y parent solo se reescriben si
  839. // son una MAC con ':'; cualquier otra cosa es un id de router (#1485,
  840. // #690) y se deja como está.
  841. {
  842. name: "dedup topology_overrides MACs",
  843. sql: `DELETE FROM topology_overrides
  844. WHERE mac GLOB '` + colonMACGlob + `'
  845. AND EXISTS (
  846. SELECT 1 FROM topology_overrides t2
  847. WHERE t2.mac GLOB '` + colonMACGlob + `'
  848. AND UPPER(REPLACE(t2.mac, '-', ':')) = UPPER(REPLACE(topology_overrides.mac, '-', ':'))
  849. AND t2.rowid != topology_overrides.rowid
  850. AND (
  851. t2.updated_at > topology_overrides.updated_at
  852. OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) > (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))))
  853. OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) = (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))) AND t2.rowid > topology_overrides.rowid)
  854. )
  855. )`,
  856. },
  857. {
  858. name: "normalize topology_overrides MACs",
  859. sql: `UPDATE topology_overrides
  860. SET id = UPPER(REPLACE(mac, '-', ':')),
  861. mac = UPPER(REPLACE(mac, '-', ':'))
  862. WHERE mac GLOB '` + colonMACGlob + `'
  863. AND (mac != UPPER(REPLACE(mac, '-', ':')) OR id != UPPER(REPLACE(mac, '-', ':')))`,
  864. },
  865. {
  866. name: "normalize topology_overrides parent MACs",
  867. // main guardaba el parent tal cual llegaba, sin recortar espacios.
  868. // TRIM sin segundo argumento solo quita ' '; se recortan también
  869. // '\t', '\n' y '\r', como strings.TrimSpace.
  870. sql: `UPDATE topology_overrides
  871. SET parent = UPPER(` + trimWS("parent") + `)
  872. WHERE parent IS NOT NULL
  873. AND ` + trimWS("parent") + ` GLOB '` + colonMACGlob + `'
  874. AND parent != UPPER(` + trimWS("parent") + `)`,
  875. },
  876. // client_bw_raw, client_bw_5m, client_bw_daily: en colisión sobre
  877. // (mac, router_id, ts/bucket_ts/date) sobrevive la fila ya canónica.
  878. {
  879. // Tablas grandes: el duplicado canónico se busca por la clave
  880. // primaria (índice), no con una subconsulta que recorra la tabla.
  881. name: "dedup client_bw_raw MACs",
  882. sql: `DELETE FROM client_bw_raw
  883. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
  884. AND EXISTS (
  885. SELECT 1 FROM client_bw_raw b2
  886. WHERE b2.mac = UPPER(REPLACE(client_bw_raw.mac, '-', ':'))
  887. AND b2.router_id = client_bw_raw.router_id
  888. AND b2.ts = client_bw_raw.ts
  889. )`,
  890. },
  891. {
  892. // OR IGNORE: dos variantes no canónicas de la misma clave (no
  893. // ocurre con datos reales) no deben abortar el resto; la que queda
  894. // sin actualizar se borra en el paso siguiente.
  895. name: "normalize client_bw_raw MACs",
  896. sql: `UPDATE OR IGNORE client_bw_raw
  897. SET mac = UPPER(REPLACE(mac, '-', ':'))
  898. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  899. },
  900. {
  901. name: "drop leftover client_bw_raw MAC variants",
  902. sql: `DELETE FROM client_bw_raw
  903. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  904. },
  905. {
  906. // Tablas grandes: el duplicado canónico se busca por la clave
  907. // primaria (índice), no con una subconsulta que recorra la tabla.
  908. name: "dedup client_bw_5m MACs",
  909. sql: `DELETE FROM client_bw_5m
  910. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
  911. AND EXISTS (
  912. SELECT 1 FROM client_bw_5m b2
  913. WHERE b2.mac = UPPER(REPLACE(client_bw_5m.mac, '-', ':'))
  914. AND b2.router_id = client_bw_5m.router_id
  915. AND b2.bucket_ts = client_bw_5m.bucket_ts
  916. )`,
  917. },
  918. {
  919. // OR IGNORE: dos variantes no canónicas de la misma clave (no
  920. // ocurre con datos reales) no deben abortar el resto; la que queda
  921. // sin actualizar se borra en el paso siguiente.
  922. name: "normalize client_bw_5m MACs",
  923. sql: `UPDATE OR IGNORE client_bw_5m
  924. SET mac = UPPER(REPLACE(mac, '-', ':'))
  925. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  926. },
  927. {
  928. name: "drop leftover client_bw_5m MAC variants",
  929. sql: `DELETE FROM client_bw_5m
  930. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  931. },
  932. {
  933. // Tablas grandes: el duplicado canónico se busca por la clave
  934. // primaria (índice), no con una subconsulta que recorra la tabla.
  935. name: "dedup client_bw_daily MACs",
  936. sql: `DELETE FROM client_bw_daily
  937. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
  938. AND EXISTS (
  939. SELECT 1 FROM client_bw_daily b2
  940. WHERE b2.mac = UPPER(REPLACE(client_bw_daily.mac, '-', ':'))
  941. AND b2.router_id = client_bw_daily.router_id
  942. AND b2.date = client_bw_daily.date
  943. )`,
  944. },
  945. {
  946. // OR IGNORE: dos variantes no canónicas de la misma clave (no
  947. // ocurre con datos reales) no deben abortar el resto; la que queda
  948. // sin actualizar se borra en el paso siguiente.
  949. name: "normalize client_bw_daily MACs",
  950. sql: `UPDATE OR IGNORE client_bw_daily
  951. SET mac = UPPER(REPLACE(mac, '-', ':'))
  952. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  953. },
  954. {
  955. name: "drop leftover client_bw_daily MAC variants",
  956. sql: `DELETE FROM client_bw_daily
  957. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  958. },
  959. // device_rack_profile y rack_mounts: rack_mounts.device_mac tiene
  960. // REFERENCES device_rack_profile(mac) ON DELETE SET NULL con
  961. // foreign_keys=ON. Primero se inserta la fila canónica en
  962. // device_rack_profile (INSERT OR IGNORE preserva la ya mayúscula si
  963. // existían ambas), luego se reasigna rack_mounts.device_mac y por
  964. // último se borran los perfiles no canónicos sin disparar SET NULL.
  965. {
  966. name: "copy device_rack_profile MACs to canonical",
  967. sql: `INSERT OR IGNORE INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json)
  968. SELECT UPPER(REPLACE(mac, '-', ':')), faceplate_id, u_height, col_span, color, ports_json
  969. FROM device_rack_profile
  970. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  971. },
  972. {
  973. name: "normalize rack_mounts device_mac",
  974. sql: `UPDATE rack_mounts
  975. SET device_mac = UPPER(REPLACE(device_mac, '-', ':'))
  976. WHERE device_mac IS NOT NULL
  977. AND ` + macOnlyMatch("device_mac") + `
  978. AND device_mac != UPPER(REPLACE(device_mac, '-', ':'))`,
  979. },
  980. {
  981. name: "delete non-canonical device_rack_profile MACs",
  982. sql: `DELETE FROM device_rack_profile
  983. WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
  984. },
  985. }
  986. start := time.Now()
  987. tx, err := sqldb.Begin()
  988. if err != nil {
  989. log.Printf("[netpulse] warning: could not start the MAC migration: %v", err)
  990. return
  991. }
  992. for _, s := range steps {
  993. if _, err := tx.Exec(s.sql); err != nil {
  994. _ = tx.Rollback()
  995. log.Printf("[netpulse] warning: could not %s, MAC migration rolled back: %v", s.name, err)
  996. return
  997. }
  998. }
  999. if _, err := tx.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
  1000. macUpperMigratedKey, time.Now().Format(time.RFC3339)); err != nil {
  1001. _ = tx.Rollback()
  1002. log.Printf("[netpulse] warning: could not mark the MAC migration done: %v", err)
  1003. return
  1004. }
  1005. if err := tx.Commit(); err != nil {
  1006. log.Printf("[netpulse] warning: could not commit the MAC migration: %v", err)
  1007. return
  1008. }
  1009. log.Printf("[netpulse] db: MACs in overrides, rack and client_bw tables upper-cased (%v)", time.Since(start).Round(time.Millisecond))
  1010. }
  1011. // macUpperMigratedKey marca en kv que migrateLowercaseMACTables ya corrió.
  1012. const macUpperMigratedKey = "mac_upper_tables_migrated"
  1013. // Patrones GLOB de una MAC de 17 caracteres. topology_overrides solo admite la
  1014. // forma con ':', porque sus columnas también guardan ids de router (slugs con
  1015. // '-', que pueden parecer una MAC con guiones); las demás tablas solo guardan
  1016. // MACs y aceptan también '-'. Como macaddr.Normalize, el separador debe ser el
  1017. // mismo en las cinco posiciones: "aa-bb:cc-…" no es una MAC.
  1018. var (
  1019. colonMACGlob = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]:", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
  1020. dashMACGlob = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]-", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
  1021. )
  1022. // trimWS devuelve la expresión SQL que recorta espacios, tabuladores y saltos
  1023. // de línea a ambos lados de col.
  1024. func trimWS(col string) string {
  1025. return "TRIM(" + col + ", ' ' || char(9) || char(10) || char(13))"
  1026. }
  1027. // macOnlyMatch devuelve la condición SQL "col es una MAC con ':' o con '-'",
  1028. // para las tablas que solo guardan MACs.
  1029. func macOnlyMatch(col string) string {
  1030. return "(" + col + " GLOB '" + colonMACGlob + "' OR " + col + " GLOB '" + dashMACGlob + "')"
  1031. }
  1032. // migrate replica src/db.js:143-150: introspección PRAGMA table_info y DDL
  1033. // tragándose errores.
  1034. func migrate(db *sql.DB, table, column, ddl string) {
  1035. rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
  1036. if err != nil {
  1037. return
  1038. }
  1039. defer rows.Close()
  1040. found := false
  1041. for rows.Next() {
  1042. var cid int
  1043. var name, ctype string
  1044. var notnull, pk int
  1045. var dflt sql.NullString
  1046. if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err == nil && name == column {
  1047. found = true
  1048. }
  1049. }
  1050. if !found {
  1051. _, _ = db.Exec(ddl) // errores tragados (paridad)
  1052. }
  1053. }
  1054. // Maintenance ejecuta una pasada de limpieza (paridad src/db.js:107-120):
  1055. // retención 7 días en metrics/adguard_stats, sesiones expiradas, atributos de
  1056. // dispositivos sin verse en 90 días (issue #206) y checkpoint.
  1057. func (d *DB) Maintenance() {
  1058. cutoff := NowMS() - RetentionMS
  1059. steps := []string{
  1060. "DELETE FROM metrics WHERE ts < ?",
  1061. "DELETE FROM adguard_stats WHERE ts < ?",
  1062. }
  1063. for _, q := range steps {
  1064. if _, err := d.Exec(q, cutoff); err != nil {
  1065. log.Printf("[netpulse] DB maintenance error: %v", err)
  1066. }
  1067. }
  1068. if _, err := d.Exec("DELETE FROM sessions WHERE expires_at < ?", NowMS()); err != nil {
  1069. log.Printf("[netpulse] DB maintenance error: %v", err)
  1070. }
  1071. // Atributos de dispositivos que no se ven desde hace 90 días (se fueron
  1072. // para siempre): sin esta purga device_attrib crece sin límite y alimenta
  1073. // el listado de dispositivos offline (issue #206).
  1074. attribCutoff := NowMS() - AttribRetentionMS
  1075. if _, err := d.Exec("DELETE FROM device_attrib WHERE last_seen < ?", attribCutoff); err != nil {
  1076. log.Printf("[netpulse] DB maintenance error: %v", err)
  1077. }
  1078. // Purga de buckets > 1 año (el raw ya se purgó arriba; daily nunca).
  1079. bucketCutoff := NowMS() - BucketsRetentionMS
  1080. if _, err := d.Exec("DELETE FROM metrics_buckets WHERE bucket_ts < ?", bucketCutoff); err != nil {
  1081. log.Printf("[netpulse] DB maintenance error: %v", err)
  1082. }
  1083. // Agregado DNS (#2078): 7 días de detalle horario y 90 días de "primera
  1084. // vez visto". Son ventanas distintas a propósito: el detalle caduca rápido,
  1085. // el histórico de dominios nuevos solo crece con dominios nuevos.
  1086. if _, err := d.Exec("DELETE FROM dns_activity WHERE hour_ts < ?", NowMS()-DNSActivityRetentionMS); err != nil {
  1087. log.Printf("[netpulse] DB maintenance error: %v", err)
  1088. }
  1089. if _, err := d.Exec("DELETE FROM dns_domain_first WHERE first_seen < ?", NowMS()-DNSFirstsRetentionMS); err != nil {
  1090. log.Printf("[netpulse] DB maintenance error: %v", err)
  1091. }
  1092. if !d.rollbackJournal {
  1093. if _, err := d.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
  1094. log.Printf("[netpulse] DB maintenance error: %v", err)
  1095. }
  1096. }
  1097. }
  1098. // NightlyJob ejecuta el rollup de la escalera de retención:
  1099. // samples→buckets (ventana = retención raw, 7d) →
  1100. // buckets→daily (solape 35 días) → checkpoint → optimize. Orden obligatorio:
  1101. // agregar antes de purgar; idempotente (INSERT OR REPLACE) por si el daemon
  1102. // estuvo caído.
  1103. func (d *DB) NightlyJob() {
  1104. start := time.Now()
  1105. log.Printf("[netpulse] nightly rollup: start")
  1106. // 1) samples → buckets 5 min. Ventana = retención raw (#812): recubre
  1107. // caídas de hasta 7 días; con la antigua ventana fija de 48h el tramo
  1108. // 48h..7d quedaba sin agregar y se perdía al purgar el raw.
  1109. if err := d.rollupSamplesToBuckets(rollupRawWindow); err != nil {
  1110. log.Printf("[netpulse] error rollup samples→buckets: %v", err)
  1111. } else {
  1112. log.Printf("[netpulse] rollup samples→buckets OK (%s)", time.Since(start).Round(time.Millisecond))
  1113. }
  1114. // 2) buckets → daily (ventana: últimos 35 días con solape)
  1115. if err := d.rollupBucketsToDaily(35 * 24 * time.Hour); err != nil {
  1116. log.Printf("[netpulse] error rollup buckets→daily: %v", err)
  1117. } else {
  1118. log.Printf("[netpulse] rollup buckets→daily OK (%s)", time.Since(start).Round(time.Millisecond))
  1119. }
  1120. // 3) checkpoint tras los DELETE/INSERT grandes (concentra el WAL);
  1121. // en rollback-journal (on-box) no hay WAL que consolidar.
  1122. if !d.rollbackJournal {
  1123. _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
  1124. }
  1125. // 4) optimize + ANALYZE (estadísticas del planner tras la purga)
  1126. _, _ = d.Exec("PRAGMA optimize")
  1127. _, _ = d.Exec("ANALYZE")
  1128. // 5) VACUUM solo si el freelist creció (> ~4 MB con page_size 4096)
  1129. var freelist int
  1130. if err := d.QueryRow("PRAGMA freelist_count").Scan(&freelist); err == nil && freelist > 1024 {
  1131. if _, err := d.Exec("VACUUM"); err != nil {
  1132. log.Printf("[netpulse] warning: VACUUM failed: %v", err)
  1133. } else {
  1134. log.Printf("[netpulse] rollup nocturno: VACUUM tras freelist=%d", freelist)
  1135. }
  1136. }
  1137. // 6) roam_events: retención fija de 30 días (Fase 14.5). OJO: la
  1138. // retención CONFIGURABLE del usuario es presence.retention_days y la
  1139. // aplica el loop de poda de main; este DELETE solo recoge lo que ese
  1140. // loop pueda dejar (defensa en profundidad, #907).
  1141. cutoff := NowMS() - 30*24*60*60*1000
  1142. if res, err := d.Exec("DELETE FROM roam_events WHERE ts_ms < ?", cutoff); err == nil {
  1143. if n, _ := res.RowsAffected(); n > 0 {
  1144. log.Printf("[netpulse] roam_events: purgados %d eventos >30d", n)
  1145. }
  1146. }
  1147. // 7) device_events: misma retención 30 días (issue #184).
  1148. if res, err := d.Exec("DELETE FROM device_events WHERE ts_ms < ?", cutoff); err == nil {
  1149. if n, _ := res.RowsAffected(); n > 0 {
  1150. log.Printf("[netpulse] device_events: purgados %d eventos >30d", n)
  1151. }
  1152. }
  1153. log.Printf("[netpulse] rollup nocturno: fin (%s)", time.Since(start).Round(time.Millisecond))
  1154. // Per-port time series rollup (issue #302).
  1155. if d.PortSeries != nil {
  1156. d.PortSeries.NightlyJob()
  1157. }
  1158. // Per-client bandwidth rollup (#337/#551).
  1159. if d.ClientBW != nil {
  1160. d.ClientBW.NightlyJob()
  1161. }
  1162. // Per-peer WireGuard counters (#2019).
  1163. if d.WGSeries != nil {
  1164. d.WGSeries.NightlyJob()
  1165. }
  1166. }
  1167. // BucketMS es el tamaño del bucket medio en ms (5 minutos).
  1168. const BucketMS = 5 * 60 * 1000
  1169. // BucketsRetentionMS: 1 año en ms.
  1170. const BucketsRetentionMS = 365 * 24 * 60 * 60 * 1000
  1171. func (d *DB) rollupSamplesToBuckets(window time.Duration) error {
  1172. // Ventana con solape: recomputa buckets de los últimos `window` para
  1173. // cubrir caídas del daemon de hasta ese tiempo. INSERT OR REPLACE idempotente.
  1174. since := NowMS() - window.Milliseconds()
  1175. _, err := d.Exec(`
  1176. INSERT OR REPLACE INTO metrics_buckets
  1177. (router_id, bucket_ts, n, min_ts,
  1178. cpu_min, cpu_max, cpu_avg, ram_min, ram_max, ram_avg,
  1179. temp_min, temp_max, temp_avg, lat_min, lat_max, lat_avg,
  1180. rx_min, rx_max, rx_avg, tx_min, tx_max, tx_avg)
  1181. SELECT
  1182. router_id,
  1183. (ts / ?) * ?,
  1184. COUNT(*),
  1185. MIN(ts),
  1186. MIN(cpu), MAX(cpu), AVG(cpu),
  1187. MIN(ram), MAX(ram), AVG(ram),
  1188. MIN(temp), MAX(temp), AVG(temp),
  1189. MIN(latency_ms), MAX(latency_ms), AVG(latency_ms),
  1190. MIN(rx_bps), MAX(rx_bps), AVG(rx_bps),
  1191. MIN(tx_bps), MAX(tx_bps), AVG(tx_bps)
  1192. FROM metrics
  1193. WHERE ts >= ?
  1194. GROUP BY router_id, (ts / ?)`,
  1195. BucketMS, BucketMS, since, BucketMS)
  1196. return err
  1197. }
  1198. func (d *DB) rollupBucketsToDaily(window time.Duration) error {
  1199. // Agrega buckets → daily por router y día (epoch-UTC). Solape de 35 días
  1200. // para cubrir caídas; INSERT OR REPLACE idempotente.
  1201. since := NowMS() - window.Milliseconds()
  1202. _, err := d.Exec(`
  1203. INSERT OR REPLACE INTO metrics_daily
  1204. (router_id, date, n,
  1205. cpu_avg, ram_avg, temp_avg, lat_avg, rx_avg, tx_avg,
  1206. rx_total, tx_total, up_min, up_count)
  1207. SELECT
  1208. router_id,
  1209. strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch'),
  1210. SUM(n),
  1211. AVG(cpu_avg), AVG(ram_avg), AVG(temp_avg),
  1212. AVG(lat_avg), AVG(rx_avg), AVG(tx_avg),
  1213. SUM(rx_avg * n), SUM(tx_avg * n),
  1214. SUM(n) * 5 / 60, COUNT(*)
  1215. FROM metrics_buckets
  1216. WHERE bucket_ts >= ?
  1217. GROUP BY router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch')`,
  1218. since)
  1219. return err
  1220. }
  1221. // ShouldRunNightly decide si toca ejecutar el rollup: una vez al día en hora
  1222. // valle (03:00-04:00 local). Hora local del host (como la UI).
  1223. func ShouldRunNightly(now time.Time) bool {
  1224. return now.Hour() == 3
  1225. }
  1226. func (d *DB) maintenanceLoop() {
  1227. defer d.wg.Done()
  1228. t := time.NewTicker(Maintenance)
  1229. defer t.Stop()
  1230. // El ticker arranca en Maintenance; el primer fire llega a la 1ª hora.
  1231. // No ejecutar el rollup al arrancar: los datos raw de los últimos 7 días
  1232. // ya están; el siguiente 03:00 los consolida. Evita competir con el
  1233. // arranque (migraciones, primer poll).
  1234. for {
  1235. select {
  1236. case <-d.stop:
  1237. return
  1238. case now := <-t.C:
  1239. if ShouldRunNightly(now) {
  1240. d.NightlyJob()
  1241. } else {
  1242. d.Maintenance()
  1243. }
  1244. }
  1245. }
  1246. }
  1247. // CheckHealth replica dbHandle.checkHealth(): SELECT 1.
  1248. func (d *DB) CheckHealth() bool {
  1249. var ok int
  1250. if err := d.QueryRow("SELECT 1").Scan(&ok); err != nil {
  1251. return false
  1252. }
  1253. return ok == 1
  1254. }
  1255. // Close para el timer, checkpoint TRUNCATE (best-effort) y cierra.
  1256. func (d *DB) Close() error {
  1257. var err error
  1258. d.close.Do(func() {
  1259. close(d.stop)
  1260. d.wg.Wait()
  1261. _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
  1262. err = d.DB.Close()
  1263. })
  1264. return err
  1265. }
  1266. // ShutdownContext cierra el pool con contexto (para el salvavidas de 3 s).
  1267. func (d *DB) ShutdownContext(ctx context.Context) error {
  1268. done := make(chan error, 1)
  1269. go func() { done <- d.Close() }()
  1270. select {
  1271. case err := <-done:
  1272. return err
  1273. case <-ctx.Done():
  1274. return ctx.Err()
  1275. }
  1276. }
  1277. // KnownMac es una fila de la allowlist (issue #196).
  1278. type KnownMac struct {
  1279. MAC string
  1280. Name string
  1281. Note string
  1282. CreatedAt int64
  1283. }
  1284. // ListKnownMacs devuelve la allowlist ordenada por MAC.
  1285. func (d *DB) ListKnownMacs() ([]KnownMac, error) {
  1286. rows, err := d.Query("SELECT mac, name, note, created_at FROM known_macs ORDER BY mac")
  1287. if err != nil {
  1288. return nil, err
  1289. }
  1290. defer rows.Close()
  1291. out := []KnownMac{}
  1292. for rows.Next() {
  1293. var k KnownMac
  1294. var note sql.NullString
  1295. if err := rows.Scan(&k.MAC, &k.Name, &note, &k.CreatedAt); err == nil {
  1296. k.Note = note.String
  1297. out = append(out, k)
  1298. }
  1299. }
  1300. return out, rows.Err()
  1301. }
  1302. // UpsertKnownMac inserta o actualiza una MAC de la allowlist (por MAC).
  1303. func (d *DB) UpsertKnownMac(k KnownMac) error {
  1304. _, err := d.Exec(
  1305. `INSERT INTO known_macs (mac, name, note, created_at) VALUES (?, ?, ?, ?)
  1306. ON CONFLICT(mac) DO UPDATE SET name=excluded.name, note=excluded.note`,
  1307. k.MAC, k.Name, k.Note, NowMS())
  1308. return err
  1309. }
  1310. // AddDeletedClient registra una lápida: el usuario borró este cliente a mano
  1311. // y NO quiere que vuelva a alta solo (#1278).
  1312. func (d *DB) AddDeletedClient(mac string) error {
  1313. _, err := d.Exec("INSERT INTO deleted_clients (mac, deleted_at) VALUES (?, ?) ON CONFLICT(mac) DO UPDATE SET deleted_at=excluded.deleted_at", mac, NowMS())
  1314. return err
  1315. }
  1316. // DeletedClients devuelve el set de MACs enterradas.
  1317. func (d *DB) DeletedClients() (map[string]bool, error) {
  1318. rows, err := d.Query("SELECT mac FROM deleted_clients")
  1319. if err != nil {
  1320. return nil, err
  1321. }
  1322. defer rows.Close()
  1323. out := map[string]bool{}
  1324. for rows.Next() {
  1325. var mac string
  1326. if err := rows.Scan(&mac); err != nil {
  1327. continue
  1328. }
  1329. out[mac] = true
  1330. }
  1331. return out, rows.Err()
  1332. }
  1333. // DeleteDeletedClient quita la lápida: el usuario vuelve a dar de alta la
  1334. // MAC (allowlist/alta guiada), así que puede reaparecer con normalidad.
  1335. func (d *DB) DeleteDeletedClient(mac string) error {
  1336. _, err := d.Exec("DELETE FROM deleted_clients WHERE mac = ?", mac)
  1337. return err
  1338. }
  1339. // DeleteKnownMac quita una MAC de la allowlist.
  1340. func (d *DB) DeleteKnownMac(mac string) error {
  1341. _, err := d.Exec("DELETE FROM known_macs WHERE mac = ?", mac)
  1342. return err
  1343. }