db.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. created_at INTEGER NOT NULL,
  278. updated_at INTEGER NOT NULL
  279. );
  280. -- Per-port time series (issue #302): raw (7d) -> 5m (1y) -> daily (forever).
  281. CREATE TABLE IF NOT EXISTS port_series_raw (
  282. router_id TEXT NOT NULL,
  283. port_id TEXT NOT NULL,
  284. ts INTEGER NOT NULL,
  285. rx_bytes INTEGER NOT NULL DEFAULT 0,
  286. tx_bytes INTEGER NOT NULL DEFAULT 0,
  287. rx_errors INTEGER NOT NULL DEFAULT 0,
  288. tx_errors INTEGER NOT NULL DEFAULT 0,
  289. rx_frames INTEGER NOT NULL DEFAULT 0,
  290. tx_frames INTEGER NOT NULL DEFAULT 0,
  291. rx_bps REAL NOT NULL DEFAULT 0,
  292. tx_bps REAL NOT NULL DEFAULT 0,
  293. speed_mbps INTEGER NOT NULL DEFAULT 0,
  294. PRIMARY KEY (router_id, port_id, ts)
  295. );
  296. -- #817: solo el índice por ts (retención). El PK (router_id, port_id, ts) ya
  297. -- cubre las consultas por router/puerto; idx_port_series_raw_rpt era idéntico
  298. -- al PK y se elimina (DROP INDEX en Open para las DBs existentes).
  299. CREATE INDEX IF NOT EXISTS idx_port_series_raw_ts ON port_series_raw(ts);
  300. CREATE TABLE IF NOT EXISTS port_series_5m (
  301. router_id TEXT NOT NULL,
  302. port_id TEXT NOT NULL,
  303. bucket_ts INTEGER NOT NULL,
  304. n INTEGER NOT NULL,
  305. rx_bytes INTEGER NOT NULL DEFAULT 0,
  306. tx_bytes INTEGER NOT NULL DEFAULT 0,
  307. rx_errors INTEGER NOT NULL DEFAULT 0,
  308. tx_errors INTEGER NOT NULL DEFAULT 0,
  309. rx_frames INTEGER NOT NULL DEFAULT 0,
  310. tx_frames INTEGER NOT NULL DEFAULT 0,
  311. rx_bps_min REAL NOT NULL DEFAULT 0,
  312. rx_bps_max REAL NOT NULL DEFAULT 0,
  313. rx_bps_avg REAL NOT NULL DEFAULT 0,
  314. tx_bps_min REAL NOT NULL DEFAULT 0,
  315. tx_bps_max REAL NOT NULL DEFAULT 0,
  316. tx_bps_avg REAL NOT NULL DEFAULT 0,
  317. speed_mbps INTEGER NOT NULL DEFAULT 0,
  318. PRIMARY KEY (router_id, port_id, bucket_ts)
  319. );
  320. CREATE INDEX IF NOT EXISTS idx_port_series_5m_ts ON port_series_5m(bucket_ts);
  321. CREATE TABLE IF NOT EXISTS port_series_daily (
  322. router_id TEXT NOT NULL,
  323. port_id TEXT NOT NULL,
  324. date TEXT NOT NULL,
  325. n INTEGER NOT NULL,
  326. rx_bytes INTEGER NOT NULL DEFAULT 0,
  327. tx_bytes INTEGER NOT NULL DEFAULT 0,
  328. rx_errors INTEGER NOT NULL DEFAULT 0,
  329. tx_errors INTEGER NOT NULL DEFAULT 0,
  330. rx_frames INTEGER NOT NULL DEFAULT 0,
  331. tx_frames INTEGER NOT NULL DEFAULT 0,
  332. rx_bps_avg REAL NOT NULL DEFAULT 0,
  333. tx_bps_avg REAL NOT NULL DEFAULT 0,
  334. speed_mbps INTEGER NOT NULL DEFAULT 0,
  335. PRIMARY KEY (router_id, port_id, date)
  336. );
  337. -- wifi_scans: scans pasivos de vecinos recogidos por el agente (#452).
  338. -- Se guardan por push para poder hacer recomendaciones de canal.
  339. CREATE TABLE IF NOT EXISTS wifi_scans (
  340. id INTEGER PRIMARY KEY AUTOINCREMENT,
  341. router_id TEXT NOT NULL,
  342. iface TEXT NOT NULL,
  343. bssid TEXT NOT NULL,
  344. ssid TEXT NOT NULL DEFAULT '',
  345. channel INTEGER NOT NULL,
  346. freq INTEGER NOT NULL,
  347. signal_dbm INTEGER NOT NULL,
  348. width_mhz INTEGER NOT NULL DEFAULT 0,
  349. ts INTEGER NOT NULL
  350. );
  351. CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
  352. CREATE INDEX IF NOT EXISTS idx_wifi_scans_channel ON wifi_scans(channel, freq);
  353. -- wifi_scan_outcomes (#1848): ultimo resultado del scan de vecinos por
  354. -- interfaz. Guarda el motivo cuando el driver lo rechaza, para que la vista
  355. -- de canales no muestre una banda vacia sin explicacion. Es el ultimo estado
  356. -- conocido, no un historico: una fila por router e interfaz.
  357. CREATE TABLE IF NOT EXISTS wifi_scan_outcomes (
  358. router_id TEXT NOT NULL,
  359. iface TEXT NOT NULL,
  360. phy INTEGER NOT NULL DEFAULT -1,
  361. bss INTEGER NOT NULL DEFAULT 0,
  362. err TEXT NOT NULL DEFAULT '',
  363. ts INTEGER NOT NULL,
  364. PRIMARY KEY (router_id, iface)
  365. );
  366. -- Firmware upgrades de routers OpenWrt (#453).
  367. -- firmware_targets: información de firmware soportado por router.
  368. CREATE TABLE IF NOT EXISTS firmware_targets (
  369. router_id TEXT PRIMARY KEY,
  370. model TEXT NOT NULL,
  371. current_version TEXT NOT NULL DEFAULT '',
  372. target_version TEXT NOT NULL DEFAULT '',
  373. target_url TEXT NOT NULL DEFAULT '',
  374. checksum TEXT NOT NULL DEFAULT '',
  375. updated_at INTEGER NOT NULL
  376. );
  377. -- firmware_upgrades: historial y estado de upgrades en curso.
  378. CREATE TABLE IF NOT EXISTS firmware_upgrades (
  379. id INTEGER PRIMARY KEY AUTOINCREMENT,
  380. router_id TEXT NOT NULL,
  381. target_version TEXT NOT NULL,
  382. target_url TEXT NOT NULL,
  383. checksum TEXT NOT NULL DEFAULT '',
  384. status TEXT NOT NULL DEFAULT 'idle',
  385. error TEXT NOT NULL DEFAULT '',
  386. backup_path TEXT,
  387. started_at INTEGER NOT NULL,
  388. finished_at INTEGER,
  389. -- #494: programación de upgrades desatendidos (epoch ms UTC; NULL = flujo
  390. -- manual/inmediato sin programar). started_at/finished_at siguen en segundos.
  391. scheduled_for INTEGER
  392. );
  393. CREATE INDEX IF NOT EXISTS idx_firmware_upgrades_router_started ON firmware_upgrades(router_id, started_at DESC);
  394. -- Log de alertas persistido (issue #798): el historial sobrevive a reinicios
  395. -- (el self-update del updater reinicia el proceso y antes se perdía entero).
  396. -- La lista en memoria sigue acotada a los 100 más recientes; aquí se guardan
  397. -- hasta 500 para poder restaurarlos. read_flag va aparte en kv (readSet), pero
  398. -- se espeja en la columna para restaurarlo al cargar. (OJO: "read" crudo es
  399. -- problemático como nombre de columna; por eso read_flag.)
  400. CREATE TABLE IF NOT EXISTS alert_log (
  401. id TEXT PRIMARY KEY,
  402. ts INTEGER NOT NULL,
  403. category TEXT NOT NULL,
  404. type TEXT NOT NULL DEFAULT '',
  405. severity TEXT NOT NULL DEFAULT '',
  406. urgent INTEGER NOT NULL DEFAULT 0,
  407. title TEXT NOT NULL,
  408. description TEXT NOT NULL DEFAULT '',
  409. hint TEXT NOT NULL DEFAULT '',
  410. router_id TEXT NOT NULL DEFAULT '',
  411. suppressed_by TEXT NOT NULL DEFAULT '',
  412. vars TEXT NOT NULL DEFAULT '',
  413. read_flag INTEGER NOT NULL DEFAULT 0,
  414. resolves TEXT NOT NULL DEFAULT ''
  415. );
  416. CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
  417. -- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
  418. -- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):
  419. -- rack_mounts.device_mac apunta a esa identidad y device_rack_profile guarda
  420. -- el modelo físico compartido (faceplate, altura U, span de columnas,
  421. -- color y puertos con posición). Los montajes con device_mac NULL son
  422. -- accesorios (blank, shelf, patch panel, PDU): su tamaño lo define el
  423. -- faceplate del catálogo.
  424. CREATE TABLE IF NOT EXISTS racks (
  425. id TEXT PRIMARY KEY,
  426. name TEXT NOT NULL,
  427. u_height INTEGER NOT NULL,
  428. width_standard TEXT NOT NULL DEFAULT '19', -- '19' | '10'
  429. numbering TEXT NOT NULL DEFAULT 'bottom-up', -- solo cambia etiquetas, nunca la geometría
  430. style_json TEXT NOT NULL DEFAULT '{}',
  431. location TEXT,
  432. position_x REAL NOT NULL DEFAULT 0,
  433. position_y REAL NOT NULL DEFAULT 0
  434. );
  435. CREATE TABLE IF NOT EXISTS device_rack_profile (
  436. mac TEXT PRIMARY KEY,
  437. faceplate_id TEXT NOT NULL DEFAULT '',
  438. u_height INTEGER NOT NULL DEFAULT 1,
  439. col_span INTEGER NOT NULL DEFAULT 12,
  440. color TEXT NOT NULL DEFAULT '',
  441. ports_json TEXT NOT NULL DEFAULT '[]'
  442. );
  443. CREATE TABLE IF NOT EXISTS rack_mounts (
  444. id TEXT PRIMARY KEY,
  445. rack_id TEXT NOT NULL REFERENCES racks(id) ON DELETE CASCADE,
  446. device_mac TEXT REFERENCES device_rack_profile(mac) ON DELETE SET NULL, -- NULL = accesorio
  447. faceplate_id TEXT NOT NULL DEFAULT '', -- accesorios; el de dispositivos vive en device_rack_profile
  448. u_start INTEGER NOT NULL, -- 1-based, SIEMPRE contado desde el rail inferior
  449. col_start INTEGER NOT NULL DEFAULT 0, -- 0-based
  450. label TEXT,
  451. status_pin TEXT NOT NULL DEFAULT 'auto', -- 'auto' → seguir el estado que conoce el poller
  452. port_visibility TEXT NOT NULL DEFAULT 'auto'
  453. );
  454. CREATE INDEX IF NOT EXISTS idx_rack_mounts_rack ON rack_mounts(rack_id);
  455. -- Cables port-to-port (relación propia, no edges del canvas lógico).
  456. -- Pueden cruzar racks. Un puerto normal admite exactamente 1 cable; los
  457. -- patch panels (pass-through) admiten 2 (tirada de pared al rear + patch al
  458. -- switch al front). Cobre vs fibra se deriva del puerto de origen del patch.
  459. CREATE TABLE IF NOT EXISTS rack_cables (
  460. id TEXT PRIMARY KEY,
  461. from_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
  462. from_port TEXT NOT NULL,
  463. to_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
  464. to_port TEXT NOT NULL,
  465. type TEXT NOT NULL DEFAULT 'ethernet', -- 'ethernet' | 'fiber'
  466. label TEXT,
  467. properties_json TEXT NOT NULL DEFAULT '{}', -- key/value libre
  468. origin TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'imported' | 'detected'
  469. created_at INTEGER NOT NULL
  470. );
  471. CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
  472. CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
  473. -- External router integrations (#1674): pushers de routers externos
  474. -- (MikroTik RouterOS, Asuswrt) gestionados desde la app. El slug es el id
  475. -- del router external asociado (push autenticado por Bearer token de agente,
  476. -- agent.token.<slug>). La contraseña nunca se persiste: vive en el fichero
  477. -- de entorno <data>/integrations/<slug>.env (0600).
  478. CREATE TABLE IF NOT EXISTS router_integrations (
  479. slug TEXT PRIMARY KEY,
  480. vendor TEXT NOT NULL,
  481. mode TEXT NOT NULL,
  482. host TEXT NOT NULL,
  483. username TEXT NOT NULL,
  484. version TEXT NOT NULL DEFAULT '',
  485. asset TEXT NOT NULL DEFAULT '',
  486. arch TEXT NOT NULL,
  487. interval_s INTEGER NOT NULL,
  488. enabled INTEGER NOT NULL DEFAULT 0,
  489. state TEXT NOT NULL DEFAULT 'pending',
  490. last_error TEXT NOT NULL DEFAULT '',
  491. last_start_ms INTEGER NOT NULL DEFAULT 0,
  492. created_at INTEGER NOT NULL,
  493. updated_at INTEGER NOT NULL
  494. );
  495. CREATE INDEX IF NOT EXISTS idx_router_integrations_vendor ON router_integrations(vendor);
  496. -- Agregado horario del query log de AdGuard (#2078): por dispositivo (MAC) y
  497. -- dominio. MAC vacía = sin atribuir (IP sin correspondencia en device_seen).
  498. -- Nunca se guarda el log crudo. Retención: 7 días (Maintenance).
  499. CREATE TABLE IF NOT EXISTS dns_activity (
  500. mac TEXT NOT NULL,
  501. domain TEXT NOT NULL,
  502. hour_ts INTEGER NOT NULL, -- inicio de la hora, ms epoch
  503. queries INTEGER NOT NULL DEFAULT 0,
  504. blocked INTEGER NOT NULL DEFAULT 0,
  505. first_seen INTEGER NOT NULL,
  506. last_seen INTEGER NOT NULL,
  507. PRIMARY KEY (mac, domain, hour_ts)
  508. );
  509. CREATE INDEX IF NOT EXISTS idx_dns_activity_hour ON dns_activity(hour_ts);
  510. CREATE INDEX IF NOT EXISTS idx_dns_activity_domain ON dns_activity(domain, hour_ts);
  511. -- Primera vez que se vio cada dominio (#2078): alimenta el aviso de dominios
  512. -- nuevos. Retención: 90 días (Maintenance).
  513. CREATE TABLE IF NOT EXISTS dns_domain_first (
  514. domain TEXT PRIMARY KEY,
  515. first_seen INTEGER NOT NULL,
  516. mac TEXT NOT NULL DEFAULT ''
  517. );
  518. CREATE INDEX IF NOT EXISTS idx_dns_domain_first_ts ON dns_domain_first(first_seen);
  519. `
  520. // DB envuelve *sql.DB con los jobs y helpers de paridad.
  521. type DB struct {
  522. *sql.DB
  523. Path string
  524. stop chan struct{}
  525. wg sync.WaitGroup
  526. close sync.Once
  527. // rollbackJournal: escape hatch (#1700) para journal DELETE (comportamiento
  528. // on-box previo). Los wal_checkpoint de mantenimiento se omiten en este
  529. // modo; en WAL (el default de todos los despliegues) sí corren.
  530. rollbackJournal bool
  531. // PortSeries: per-port time series store (issue #302).
  532. PortSeries *portseries.Store
  533. // WGSeries: contadores por peer de WireGuard con ventana real (#2019).
  534. WGSeries *wgseries.Store
  535. // ClientBW: per-client bandwidth store (issue #337/#551). Wiring añadido
  536. // en el #551: la ingesta escribe samples delta por (mac, router).
  537. ClientBW *clientbw.Store
  538. }
  539. // NowMS devuelve el epoch actual en milisegundos (como Date.now()).
  540. func NowMS() int64 { return time.Now().UnixMilli() }
  541. // OpenOption configura Open (variádica: los callers existentes no cambian).
  542. type OpenOption func(*openOptions)
  543. type openOptions struct {
  544. rollbackJournal bool
  545. // tempStore: 'memory'|'file'|'default' (#1700). Vacío = memory.
  546. tempStore string
  547. }
  548. // WithRollbackJournal: `journal_mode=DELETE` + `synchronous=FULL` en vez de
  549. // WAL+NORMAL. Histórico modo on-box (Fase 9 R6): se pensaba que el fichero
  550. // -wal y sus checkpoints eran el churn caro, pero las medidas de la issue
  551. // #1700 demostraron lo contrario (45 GB/día en DELETE+FULL frente a 13.7 en
  552. // WAL con la misma flota: cada transacción reescribía páginas + journal y
  553. // ext4 duplicaba todo con su propio journal). Desde #1700 TODOS los
  554. // despliegues van en WAL+NORMAL por defecto y esta opción es solo el escape
  555. // hatch para restaurar el modo anterior (NETPULSE_DB_ROLLBACK_JOURNAL=1).
  556. // Los wal_checkpoint de mantenimiento se omiten en este modo.
  557. func WithRollbackJournal() OpenOption {
  558. return func(o *openOptions) { o.rollbackJournal = true }
  559. }
  560. // WithTempStore fija PRAGMA temp_store: 'memory'|'file'|'default' (#1700).
  561. // Por defecto TODOS los despliegues van en 'memory': las agregaciones
  562. // (GROUP BY/ORDER BY sobre expresiones, p. ej. buckets de métricas y
  563. // channel plan) hacen spill a ficheros temporales etilqs_*; el reporte
  564. // midió ~9 GB/día de escrituras en esos temporales con una BD de ~100 MB.
  565. // El coste en RAM de guardarlos (unos MB por query) es trivial frente a ese
  566. // volumen, y crítico en un USB (on-box). 'file'/'default' quedan para
  567. // diagnosticar con el comportamiento clásico.
  568. func WithTempStore(mode string) OpenOption {
  569. return func(o *openOptions) { o.tempStore = strings.ToLower(mode) }
  570. }
  571. // Open abre (o crea) dir/netpulse.db, ejecuta la migración Node→Go si la
  572. // DB ya existía con esquema Node (backup atómico antes de tocar nada),
  573. // aplica pragmas, crea el schema y arranca el mantenimiento horario. dir es
  574. // DB_DIR, que por defecto es DATA_DIR.
  575. func Open(dir string, opts ...OpenOption) (*DB, error) {
  576. var o openOptions
  577. for _, opt := range opts {
  578. opt(&o)
  579. }
  580. // #1795: el grupo del servicio puede leer backups y datos sin ser owner.
  581. if err := os.MkdirAll(dir, 0o770); err != nil {
  582. return nil, err
  583. }
  584. if err := os.Chmod(dir, 0o770); err != nil {
  585. return nil, err
  586. }
  587. dbPath := filepath.Join(dir, databaseFile)
  588. // Migración Node→Go (§12 del SPEC): si el fichero ya existe con esquema
  589. // Node, backup + importación (preserva users/kv/sessions/routers/metrics).
  590. rep, err := MigrateNodeDB(dbPath)
  591. if err != nil {
  592. return nil, fmt.Errorf("Node→Go migration: %w", err)
  593. }
  594. if rep != nil {
  595. rep.Log()
  596. }
  597. // Una sola conexión: better-sqlite3 es síncrono/serial; con maxOpenConns=1
  598. // Go serializa igual y evita SQLITE_BUSY en WAL.
  599. sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
  600. if err != nil {
  601. return nil, err
  602. }
  603. sqldb.SetMaxOpenConns(1)
  604. pragmas := []string{
  605. "PRAGMA journal_mode = WAL",
  606. "PRAGMA synchronous = NORMAL",
  607. "PRAGMA foreign_keys = ON",
  608. }
  609. if o.rollbackJournal {
  610. // Escape hatch (#1700, antes modo on-box): una DB previa en WAL se
  611. // convierte sola: con una única conexión el cambio de journal_mode
  612. // hace checkpoint y elimina el -wal.
  613. pragmas = []string{
  614. "PRAGMA journal_mode = DELETE",
  615. "PRAGMA synchronous = FULL",
  616. "PRAGMA foreign_keys = ON",
  617. }
  618. }
  619. // PRAGMA temp_store (#1700): con MaxOpenConns(1) la única conexión
  620. // compartida hereda el pragma para todas las queries (si el pool la
  621. // recrea tras un error, SQLite vuelve al default; caso marginal).
  622. switch o.tempStore {
  623. case "", "memory":
  624. pragmas = append(pragmas, "PRAGMA temp_store = MEMORY")
  625. case "file":
  626. pragmas = append(pragmas, "PRAGMA temp_store = FILE")
  627. case "default":
  628. // sin pragma: comportamiento SQLite por defecto (fichero)
  629. }
  630. for _, p := range pragmas {
  631. if _, err := sqldb.Exec(p); err != nil {
  632. sqldb.Close()
  633. return nil, fmt.Errorf("pragma %q: %w", p, err)
  634. }
  635. }
  636. // Log del modo efectivo (#1700): lo que manda es lo que SQLite aceptó
  637. // (p. ej. un filesystem sin soporte WAL dejaría DELETE); una línea al
  638. // arrancar evita diagnosticar a ciegas el volumen de escrituras.
  639. var jMode any
  640. var tMode any
  641. _ = sqldb.QueryRow("PRAGMA journal_mode").Scan(&jMode)
  642. _ = sqldb.QueryRow("PRAGMA temp_store").Scan(&tMode)
  643. log.Printf("[netpulse] db: journal_mode=%v temp_store=%v", jMode, tMode)
  644. if _, err := sqldb.Exec(schemaSQL); err != nil {
  645. sqldb.Close()
  646. return nil, fmt.Errorf("schema: %w", err)
  647. }
  648. // Migraciones tolerantes (ALTER solo si falta la columna; errores tragados)
  649. migrate(sqldb, "sessions", "ua", "ALTER TABLE sessions ADD COLUMN ua TEXT")
  650. migrate(sqldb, "sessions", "user_id", "ALTER TABLE sessions ADD COLUMN user_id INTEGER")
  651. // #1334: dueño autenticado e idioma efectivo de la UI por suscripción push.
  652. migrate(sqldb, "push_subscriptions", "user_id", "ALTER TABLE push_subscriptions ADD COLUMN user_id INTEGER")
  653. migrate(sqldb, "push_subscriptions", "language", "ALTER TABLE push_subscriptions ADD COLUMN language TEXT")
  654. migrate(sqldb, "users", "language", "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
  655. // SPEC-65 D65-5: nombre visible por usuario ("" = usar el username).
  656. migrate(sqldb, "users", "display_name", "ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''")
  657. migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
  658. // #1917: modo de inventario por unidad. ""/"auto" = comportamiento de
  659. // siempre (agente si lo hay, SSH si no), "agent" = solo agente (el antiguo
  660. // agent_only), "ssh" = nunca esperar agente: se inventaria por SSH y no
  661. // alerta por la ausencia de un agente que no va a existir.
  662. migrate(sqldb, "routers", "inventory_mode", "ALTER TABLE routers ADD COLUMN inventory_mode TEXT NOT NULL DEFAULT ''")
  663. // issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
  664. migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
  665. // Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.
  666. migrate(sqldb, "wifi_scans", "width_mhz", "ALTER TABLE wifi_scans ADD COLUMN width_mhz INTEGER NOT NULL DEFAULT 0")
  667. // #1349: el evento resuelto NO se borra del log: queda marcado con su
  668. // ts de resolución para revisión posterior (y el evento de cierre lo
  669. // referencia con `resolves`). 0 = activo/no resuelto.
  670. migrate(sqldb, "alert_log", "resolved_ts", "ALTER TABLE alert_log ADD COLUMN resolved_ts INTEGER NOT NULL DEFAULT 0")
  671. // #1466: `resolves` (IDs de los eventos que un cierre resolvió) en JSON.
  672. // Sin persistirlo, tras un reinicio el evento de cierre perdía sus
  673. // referencias y el bloque "Resuelve N eventos" desaparecía del log.
  674. migrate(sqldb, "alert_log", "resolves", "ALTER TABLE alert_log ADD COLUMN resolves TEXT NOT NULL DEFAULT ''")
  675. // issue #241: target de firmware por router (string libre; NULL/"" = sin comprobar).
  676. migrate(sqldb, "routers", "firmware_target", "ALTER TABLE routers ADD COLUMN firmware_target TEXT")
  677. // issue #309: SNMP polling for managed switches.
  678. migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
  679. // #1145: último nombre conocido del cliente (retención indefinida).
  680. migrate(sqldb, "device_seen", "name", "ALTER TABLE device_seen ADD COLUMN name TEXT NOT NULL DEFAULT ''")
  681. // #1151: última IP conocida (los fantasmas la conservan para la lista y
  682. // las sugerencias de enlace).
  683. migrate(sqldb, "device_seen", "ip", "ALTER TABLE device_seen ADD COLUMN ip TEXT NOT NULL DEFAULT ''")
  684. // #1315: último tipo inferido (no override) del cliente: al expirar el
  685. // lease la clasificación viva cae en "desconocido" y el icono se perdía;
  686. // el valor retenido lo conserva (stickiness del tipo, solo se escribe
  687. // cuando la inferencia viva no es el genérico).
  688. migrate(sqldb, "device_seen", "device_type", "ALTER TABLE device_seen ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
  689. // issue #863: sondeo HTTP de la consola de switches RTLPlayground. DEFAULT 1
  690. // = comportamiento previo; se desactiva por router (la consola del firmware
  691. // tiene una sola sesión global y cada login tumba la sesión humana).
  692. migrate(sqldb, "routers", "console_polling", "ALTER TABLE routers ADD COLUMN console_polling INTEGER NOT NULL DEFAULT 1")
  693. migrate(sqldb, "routers", "snmp_community", "ALTER TABLE routers ADD COLUMN snmp_community TEXT")
  694. migrate(sqldb, "routers", "snmp_port", "ALTER TABLE routers ADD COLUMN snmp_port INTEGER NOT NULL DEFAULT 0")
  695. // issue #414: intervalo de polling SNMP configurable (segundos; default 60).
  696. migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
  697. // #2042: versión de SNMP por unidad ("1", "2c" o "3"). DEFAULT '2c' deja
  698. // las filas existentes con el comportamiento actual (comunidad).
  699. migrate(sqldb, "routers", "snmp_version", "ALTER TABLE routers ADD COLUMN snmp_version TEXT NOT NULL DEFAULT '2c'")
  700. // #2042: credenciales USM para SNMPv3. Sin usuario no hay v3 posible, así
  701. // que "" = v3 sin configurar. Los dos passphrases son secretos: no salen
  702. // nunca por HTTP (mismo criterio que snmp_community).
  703. migrate(sqldb, "routers", "snmp_v3_user", "ALTER TABLE routers ADD COLUMN snmp_v3_user TEXT NOT NULL DEFAULT ''")
  704. migrate(sqldb, "routers", "snmp_v3_security_level", "ALTER TABLE routers ADD COLUMN snmp_v3_security_level TEXT NOT NULL DEFAULT 'authPriv'")
  705. migrate(sqldb, "routers", "snmp_v3_auth_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_proto TEXT NOT NULL DEFAULT 'SHA'")
  706. migrate(sqldb, "routers", "snmp_v3_auth_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_pass TEXT NOT NULL DEFAULT ''")
  707. migrate(sqldb, "routers", "snmp_v3_priv_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_proto TEXT NOT NULL DEFAULT 'AES'")
  708. migrate(sqldb, "routers", "snmp_v3_priv_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_pass TEXT NOT NULL DEFAULT ''")
  709. migrate(sqldb, "routers", "agent_interval", "ALTER TABLE routers ADD COLUMN agent_interval INTEGER NOT NULL DEFAULT 0")
  710. // issue #605: puerto SSH por router (dropbear en puerto no estándar).
  711. migrate(sqldb, "routers", "ssh_port", "ALTER TABLE routers ADD COLUMN ssh_port INTEGER NOT NULL DEFAULT 22")
  712. // issue #1085: pausa de una unidad de flota (sin sondeo ni alertas, con
  713. // insignia en la lista y fuera de los desplegables; el histórico se
  714. // conserva). 0/ausente (columna nueva) = activa.
  715. migrate(sqldb, "routers", "disabled", "ALTER TABLE routers ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0")
  716. // issue #716: umbral de alerta por temperatura alta (°C). NULL = 65 default.
  717. migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
  718. // issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
  719. migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
  720. // issue #761: motor del upgrade ("" = clásico URL+checksum, "owut" = ASU).
  721. migrate(sqldb, "firmware_upgrades", "engine", "ALTER TABLE firmware_upgrades ADD COLUMN engine TEXT NOT NULL DEFAULT ''")
  722. // issue #797: nombre visible y tipo de dispositivo sobreescritos a mano.
  723. migrate(sqldb, "device_overrides", "name", "ALTER TABLE device_overrides ADD COLUMN name TEXT NOT NULL DEFAULT ''")
  724. migrate(sqldb, "device_overrides", "device_type", "ALTER TABLE device_overrides ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
  725. // issue #1354: opt-in alert when a marked device goes offline (0 = off).
  726. migrate(sqldb, "device_overrides", "notify_offline", "ALTER TABLE device_overrides ADD COLUMN notify_offline INTEGER NOT NULL DEFAULT 0")
  727. // #1354: las filas de alert_log tipadas "device-offline" son eventos de
  728. // ROUTER offline (ese slug lo emitía trackRouterOffline antes de partirlo
  729. // en router-offline). Discriminador idempotente: las filas del router
  730. // llevan "host" en vars; las de cliente nuevas, no (vars = device/router).
  731. if _, err := sqldb.Exec(`UPDATE alert_log SET type = 'router-offline' WHERE type = 'device-offline' AND vars LIKE '%"host"%'`); err != nil {
  732. log.Printf("[netpulse] warning: could not migrate router-offline alert type: %v", err)
  733. }
  734. // #817: port_series_raw tenía dos índices idénticos a su PK, creados por
  735. // error en db.go y portseries.go. Se eliminan de forma idempotente (no se
  736. // vuelven a crear); el VACUUM nocturno recupera el espacio en las DBs ya
  737. // existentes (~33 MB en una instancia de 266 MB).
  738. for _, idx := range []string{"idx_port_series_raw_rpt", "idx_port_series_raw_router_port_ts"} {
  739. if _, err := sqldb.Exec("DROP INDEX IF EXISTS " + idx); err != nil {
  740. log.Printf("[netpulse] warning: could not drop index %s: %v", idx, err)
  741. }
  742. }
  743. // RouterOS and Asuswrt/Merlin moved to external integrations (#1574,
  744. // #1579). Keep existing units visible until their owner deploys the
  745. // pusher. Legacy credential columns remain in place as inert schema.
  746. if _, err := sqldb.Exec(`UPDATE routers SET type = 'external', agent_only = 1 WHERE type IN ('routeros', 'asuswrt')`); err != nil {
  747. log.Printf("[netpulse] warning: could not migrate RouterOS/Asuswrt routers to external: %v", err)
  748. }
  749. // #1129: las MACs de roam_events se ingirieron en minúsculas (así vienen
  750. // en los logs hostapd/dawn/usteer) mientras el resto de la app canonicaliza
  751. // a MAYÚSCULAS (#960): el filtro por cliente no casaba con el histórico.
  752. // Normalización one-shot de las filas existentes (la ingesta nueva ya
  753. // normaliza, ver roamevents.ParseLogreadLine).
  754. if _, err := sqldb.Exec("UPDATE roam_events SET mac = UPPER(mac) WHERE mac IS NOT NULL AND mac != UPPER(mac)"); err != nil {
  755. log.Printf("[netpulse] warning: could not normalize roam_events MACs: %v", err)
  756. }
  757. // Si no hubo migración Node (instalación fresca creada por Go), marca la
  758. // DB para que el siguiente arranque no dispare una "migración" espuria
  759. // (backup + reset de login_attempts) sobre una DB ya Go.
  760. if rep == nil {
  761. _, _ = sqldb.Exec(
  762. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
  763. migrationMarkerKey, time.Now().Format(time.RFC3339),
  764. )
  765. }
  766. d := &DB{DB: sqldb, Path: dbPath, stop: make(chan struct{}), rollbackJournal: o.rollbackJournal}
  767. ps, err := portseries.NewStore(sqldb)
  768. if err != nil {
  769. sqldb.Close()
  770. return nil, fmt.Errorf("port_series store: %w", err)
  771. }
  772. d.PortSeries = ps
  773. wg, err := wgseries.NewStore(sqldb)
  774. if err != nil {
  775. sqldb.Close()
  776. return nil, fmt.Errorf("wg_peer_series store: %w", err)
  777. }
  778. d.WGSeries = wg
  779. cb, err := clientbw.NewStore(sqldb)
  780. if err != nil {
  781. sqldb.Close()
  782. return nil, fmt.Errorf("client_bw store: %w", err)
  783. }
  784. d.ClientBW = cb
  785. d.wg.Add(1)
  786. go d.maintenanceLoop()
  787. return d, nil
  788. }
  789. // migrate replica src/db.js:143-150: introspección PRAGMA table_info y DDL
  790. // tragándose errores.
  791. func migrate(db *sql.DB, table, column, ddl string) {
  792. rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
  793. if err != nil {
  794. return
  795. }
  796. defer rows.Close()
  797. found := false
  798. for rows.Next() {
  799. var cid int
  800. var name, ctype string
  801. var notnull, pk int
  802. var dflt sql.NullString
  803. if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err == nil && name == column {
  804. found = true
  805. }
  806. }
  807. if !found {
  808. _, _ = db.Exec(ddl) // errores tragados (paridad)
  809. }
  810. }
  811. // Maintenance ejecuta una pasada de limpieza (paridad src/db.js:107-120):
  812. // retención 7 días en metrics/adguard_stats, sesiones expiradas, atributos de
  813. // dispositivos sin verse en 90 días (issue #206) y checkpoint.
  814. func (d *DB) Maintenance() {
  815. cutoff := NowMS() - RetentionMS
  816. steps := []string{
  817. "DELETE FROM metrics WHERE ts < ?",
  818. "DELETE FROM adguard_stats WHERE ts < ?",
  819. }
  820. for _, q := range steps {
  821. if _, err := d.Exec(q, cutoff); err != nil {
  822. log.Printf("[netpulse] DB maintenance error: %v", err)
  823. }
  824. }
  825. if _, err := d.Exec("DELETE FROM sessions WHERE expires_at < ?", NowMS()); err != nil {
  826. log.Printf("[netpulse] DB maintenance error: %v", err)
  827. }
  828. // Atributos de dispositivos que no se ven desde hace 90 días (se fueron
  829. // para siempre): sin esta purga device_attrib crece sin límite y alimenta
  830. // el listado de dispositivos offline (issue #206).
  831. attribCutoff := NowMS() - AttribRetentionMS
  832. if _, err := d.Exec("DELETE FROM device_attrib WHERE last_seen < ?", attribCutoff); err != nil {
  833. log.Printf("[netpulse] DB maintenance error: %v", err)
  834. }
  835. // Purga de buckets > 1 año (el raw ya se purgó arriba; daily nunca).
  836. bucketCutoff := NowMS() - BucketsRetentionMS
  837. if _, err := d.Exec("DELETE FROM metrics_buckets WHERE bucket_ts < ?", bucketCutoff); err != nil {
  838. log.Printf("[netpulse] DB maintenance error: %v", err)
  839. }
  840. // Agregado DNS (#2078): 7 días de detalle horario y 90 días de "primera
  841. // vez visto". Son ventanas distintas a propósito: el detalle caduca rápido,
  842. // el histórico de dominios nuevos solo crece con dominios nuevos.
  843. if _, err := d.Exec("DELETE FROM dns_activity WHERE hour_ts < ?", NowMS()-DNSActivityRetentionMS); err != nil {
  844. log.Printf("[netpulse] DB maintenance error: %v", err)
  845. }
  846. if _, err := d.Exec("DELETE FROM dns_domain_first WHERE first_seen < ?", NowMS()-DNSFirstsRetentionMS); err != nil {
  847. log.Printf("[netpulse] DB maintenance error: %v", err)
  848. }
  849. if !d.rollbackJournal {
  850. if _, err := d.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
  851. log.Printf("[netpulse] DB maintenance error: %v", err)
  852. }
  853. }
  854. }
  855. // NightlyJob ejecuta el rollup de la escalera de retención:
  856. // samples→buckets (ventana = retención raw, 7d) →
  857. // buckets→daily (solape 35 días) → checkpoint → optimize. Orden obligatorio:
  858. // agregar antes de purgar; idempotente (INSERT OR REPLACE) por si el daemon
  859. // estuvo caído.
  860. func (d *DB) NightlyJob() {
  861. start := time.Now()
  862. log.Printf("[netpulse] nightly rollup: start")
  863. // 1) samples → buckets 5 min. Ventana = retención raw (#812): recubre
  864. // caídas de hasta 7 días; con la antigua ventana fija de 48h el tramo
  865. // 48h..7d quedaba sin agregar y se perdía al purgar el raw.
  866. if err := d.rollupSamplesToBuckets(rollupRawWindow); err != nil {
  867. log.Printf("[netpulse] error rollup samples→buckets: %v", err)
  868. } else {
  869. log.Printf("[netpulse] rollup samples→buckets OK (%s)", time.Since(start).Round(time.Millisecond))
  870. }
  871. // 2) buckets → daily (ventana: últimos 35 días con solape)
  872. if err := d.rollupBucketsToDaily(35 * 24 * time.Hour); err != nil {
  873. log.Printf("[netpulse] error rollup buckets→daily: %v", err)
  874. } else {
  875. log.Printf("[netpulse] rollup buckets→daily OK (%s)", time.Since(start).Round(time.Millisecond))
  876. }
  877. // 3) checkpoint tras los DELETE/INSERT grandes (concentra el WAL);
  878. // en rollback-journal (on-box) no hay WAL que consolidar.
  879. if !d.rollbackJournal {
  880. _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
  881. }
  882. // 4) optimize + ANALYZE (estadísticas del planner tras la purga)
  883. _, _ = d.Exec("PRAGMA optimize")
  884. _, _ = d.Exec("ANALYZE")
  885. // 5) VACUUM solo si el freelist creció (> ~4 MB con page_size 4096)
  886. var freelist int
  887. if err := d.QueryRow("PRAGMA freelist_count").Scan(&freelist); err == nil && freelist > 1024 {
  888. if _, err := d.Exec("VACUUM"); err != nil {
  889. log.Printf("[netpulse] warning: VACUUM failed: %v", err)
  890. } else {
  891. log.Printf("[netpulse] rollup nocturno: VACUUM tras freelist=%d", freelist)
  892. }
  893. }
  894. // 6) roam_events: retención fija de 30 días (Fase 14.5). OJO: la
  895. // retención CONFIGURABLE del usuario es presence.retention_days y la
  896. // aplica el loop de poda de main; este DELETE solo recoge lo que ese
  897. // loop pueda dejar (defensa en profundidad, #907).
  898. cutoff := NowMS() - 30*24*60*60*1000
  899. if res, err := d.Exec("DELETE FROM roam_events WHERE ts_ms < ?", cutoff); err == nil {
  900. if n, _ := res.RowsAffected(); n > 0 {
  901. log.Printf("[netpulse] roam_events: purgados %d eventos >30d", n)
  902. }
  903. }
  904. // 7) device_events: misma retención 30 días (issue #184).
  905. if res, err := d.Exec("DELETE FROM device_events WHERE ts_ms < ?", cutoff); err == nil {
  906. if n, _ := res.RowsAffected(); n > 0 {
  907. log.Printf("[netpulse] device_events: purgados %d eventos >30d", n)
  908. }
  909. }
  910. log.Printf("[netpulse] rollup nocturno: fin (%s)", time.Since(start).Round(time.Millisecond))
  911. // Per-port time series rollup (issue #302).
  912. if d.PortSeries != nil {
  913. d.PortSeries.NightlyJob()
  914. }
  915. // Per-client bandwidth rollup (#337/#551).
  916. if d.ClientBW != nil {
  917. d.ClientBW.NightlyJob()
  918. }
  919. // Per-peer WireGuard counters (#2019).
  920. if d.WGSeries != nil {
  921. d.WGSeries.NightlyJob()
  922. }
  923. }
  924. // BucketMS es el tamaño del bucket medio en ms (5 minutos).
  925. const BucketMS = 5 * 60 * 1000
  926. // BucketsRetentionMS: 1 año en ms.
  927. const BucketsRetentionMS = 365 * 24 * 60 * 60 * 1000
  928. func (d *DB) rollupSamplesToBuckets(window time.Duration) error {
  929. // Ventana con solape: recomputa buckets de los últimos `window` para
  930. // cubrir caídas del daemon de hasta ese tiempo. INSERT OR REPLACE idempotente.
  931. since := NowMS() - window.Milliseconds()
  932. _, err := d.Exec(`
  933. INSERT OR REPLACE INTO metrics_buckets
  934. (router_id, bucket_ts, n, min_ts,
  935. cpu_min, cpu_max, cpu_avg, ram_min, ram_max, ram_avg,
  936. temp_min, temp_max, temp_avg, lat_min, lat_max, lat_avg,
  937. rx_min, rx_max, rx_avg, tx_min, tx_max, tx_avg)
  938. SELECT
  939. router_id,
  940. (ts / ?) * ?,
  941. COUNT(*),
  942. MIN(ts),
  943. MIN(cpu), MAX(cpu), AVG(cpu),
  944. MIN(ram), MAX(ram), AVG(ram),
  945. MIN(temp), MAX(temp), AVG(temp),
  946. MIN(latency_ms), MAX(latency_ms), AVG(latency_ms),
  947. MIN(rx_bps), MAX(rx_bps), AVG(rx_bps),
  948. MIN(tx_bps), MAX(tx_bps), AVG(tx_bps)
  949. FROM metrics
  950. WHERE ts >= ?
  951. GROUP BY router_id, (ts / ?)`,
  952. BucketMS, BucketMS, since, BucketMS)
  953. return err
  954. }
  955. func (d *DB) rollupBucketsToDaily(window time.Duration) error {
  956. // Agrega buckets → daily por router y día (epoch-UTC). Solape de 35 días
  957. // para cubrir caídas; INSERT OR REPLACE idempotente.
  958. since := NowMS() - window.Milliseconds()
  959. _, err := d.Exec(`
  960. INSERT OR REPLACE INTO metrics_daily
  961. (router_id, date, n,
  962. cpu_avg, ram_avg, temp_avg, lat_avg, rx_avg, tx_avg,
  963. rx_total, tx_total, up_min, up_count)
  964. SELECT
  965. router_id,
  966. strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch'),
  967. SUM(n),
  968. AVG(cpu_avg), AVG(ram_avg), AVG(temp_avg),
  969. AVG(lat_avg), AVG(rx_avg), AVG(tx_avg),
  970. SUM(rx_avg * n), SUM(tx_avg * n),
  971. SUM(n) * 5 / 60, COUNT(*)
  972. FROM metrics_buckets
  973. WHERE bucket_ts >= ?
  974. GROUP BY router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch')`,
  975. since)
  976. return err
  977. }
  978. // ShouldRunNightly decide si toca ejecutar el rollup: una vez al día en hora
  979. // valle (03:00-04:00 local). Hora local del host (como la UI).
  980. func ShouldRunNightly(now time.Time) bool {
  981. return now.Hour() == 3
  982. }
  983. func (d *DB) maintenanceLoop() {
  984. defer d.wg.Done()
  985. t := time.NewTicker(Maintenance)
  986. defer t.Stop()
  987. // El ticker arranca en Maintenance; el primer fire llega a la 1ª hora.
  988. // No ejecutar el rollup al arrancar: los datos raw de los últimos 7 días
  989. // ya están; el siguiente 03:00 los consolida. Evita competir con el
  990. // arranque (migraciones, primer poll).
  991. for {
  992. select {
  993. case <-d.stop:
  994. return
  995. case now := <-t.C:
  996. if ShouldRunNightly(now) {
  997. d.NightlyJob()
  998. } else {
  999. d.Maintenance()
  1000. }
  1001. }
  1002. }
  1003. }
  1004. // CheckHealth replica dbHandle.checkHealth(): SELECT 1.
  1005. func (d *DB) CheckHealth() bool {
  1006. var ok int
  1007. if err := d.QueryRow("SELECT 1").Scan(&ok); err != nil {
  1008. return false
  1009. }
  1010. return ok == 1
  1011. }
  1012. // Close para el timer, checkpoint TRUNCATE (best-effort) y cierra.
  1013. func (d *DB) Close() error {
  1014. var err error
  1015. d.close.Do(func() {
  1016. close(d.stop)
  1017. d.wg.Wait()
  1018. _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
  1019. err = d.DB.Close()
  1020. })
  1021. return err
  1022. }
  1023. // ShutdownContext cierra el pool con contexto (para el salvavidas de 3 s).
  1024. func (d *DB) ShutdownContext(ctx context.Context) error {
  1025. done := make(chan error, 1)
  1026. go func() { done <- d.Close() }()
  1027. select {
  1028. case err := <-done:
  1029. return err
  1030. case <-ctx.Done():
  1031. return ctx.Err()
  1032. }
  1033. }
  1034. // KnownMac es una fila de la allowlist (issue #196).
  1035. type KnownMac struct {
  1036. MAC string
  1037. Name string
  1038. Note string
  1039. CreatedAt int64
  1040. }
  1041. // ListKnownMacs devuelve la allowlist ordenada por MAC.
  1042. func (d *DB) ListKnownMacs() ([]KnownMac, error) {
  1043. rows, err := d.Query("SELECT mac, name, note, created_at FROM known_macs ORDER BY mac")
  1044. if err != nil {
  1045. return nil, err
  1046. }
  1047. defer rows.Close()
  1048. out := []KnownMac{}
  1049. for rows.Next() {
  1050. var k KnownMac
  1051. var note sql.NullString
  1052. if err := rows.Scan(&k.MAC, &k.Name, &note, &k.CreatedAt); err == nil {
  1053. k.Note = note.String
  1054. out = append(out, k)
  1055. }
  1056. }
  1057. return out, rows.Err()
  1058. }
  1059. // UpsertKnownMac inserta o actualiza una MAC de la allowlist (por MAC).
  1060. func (d *DB) UpsertKnownMac(k KnownMac) error {
  1061. _, err := d.Exec(
  1062. `INSERT INTO known_macs (mac, name, note, created_at) VALUES (?, ?, ?, ?)
  1063. ON CONFLICT(mac) DO UPDATE SET name=excluded.name, note=excluded.note`,
  1064. k.MAC, k.Name, k.Note, NowMS())
  1065. return err
  1066. }
  1067. // AddDeletedClient registra una lápida: el usuario borró este cliente a mano
  1068. // y NO quiere que vuelva a alta solo (#1278).
  1069. func (d *DB) AddDeletedClient(mac string) error {
  1070. _, err := d.Exec("INSERT INTO deleted_clients (mac, deleted_at) VALUES (?, ?) ON CONFLICT(mac) DO UPDATE SET deleted_at=excluded.deleted_at", mac, NowMS())
  1071. return err
  1072. }
  1073. // DeletedClients devuelve el set de MACs enterradas.
  1074. func (d *DB) DeletedClients() (map[string]bool, error) {
  1075. rows, err := d.Query("SELECT mac FROM deleted_clients")
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. defer rows.Close()
  1080. out := map[string]bool{}
  1081. for rows.Next() {
  1082. var mac string
  1083. if err := rows.Scan(&mac); err != nil {
  1084. continue
  1085. }
  1086. out[mac] = true
  1087. }
  1088. return out, rows.Err()
  1089. }
  1090. // DeleteDeletedClient quita la lápida: el usuario vuelve a dar de alta la
  1091. // MAC (allowlist/alta guiada), así que puede reaparecer con normalidad.
  1092. func (d *DB) DeleteDeletedClient(mac string) error {
  1093. _, err := d.Exec("DELETE FROM deleted_clients WHERE mac = ?", mac)
  1094. return err
  1095. }
  1096. // DeleteKnownMac quita una MAC de la allowlist.
  1097. func (d *DB) DeleteKnownMac(mac string) error {
  1098. _, err := d.Exec("DELETE FROM known_macs WHERE mac = ?", mac)
  1099. return err
  1100. }