db.go 46 KB

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