| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423 |
- // Package db — SQLite (modernc.org/sqlite, sin CGO): schema literal de Node,
- // pragmas (WAL, synchronous NORMAL, foreign_keys ON), migraciones tolerantes
- // y jobs de mantenimiento (retención 7 días + wal_checkpoint(TRUNCATE) 1 h).
- // Paridad con server/src/db.js (SPEC §4).
- //
- // Epochs: TODOS los timestamps de la DB son milisegundos (created_at,
- // expires_at, metrics.ts, locked_until). Segundos solo en overview.ts.
- package db
- import (
- "context"
- "database/sql"
- "fmt"
- "log"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
- _ "modernc.org/sqlite"
- "github.com/gnacho/netpulse/server-go/internal/clientbw"
- "github.com/gnacho/netpulse/server-go/internal/portseries"
- "github.com/gnacho/netpulse/server-go/internal/wgseries"
- )
- const (
- RetentionMS = 7 * 24 * 60 * 60 * 1000 // 7 días
- Maintenance = time.Hour
- databaseFile = "netpulse.db"
- // AttribRetentionMS: 90 días sin verse para purgar device_attrib
- // (issue #206; dispositivos que se fueron para siempre).
- AttribRetentionMS = 90 * 24 * 60 * 60 * 1000
- // DNSActivityRetentionMS: detalle horario del query log (#2078).
- DNSActivityRetentionMS = 7 * 24 * 60 * 60 * 1000
- // DNSFirstsRetentionMS: histórico de "primera vez visto" por dominio (#2078).
- DNSFirstsRetentionMS = 90 * 24 * 60 * 60 * 1000
- )
- // rollupRawWindow (#812): el rollup raw→5m cubre TODA la retención raw (7d) en
- // lugar de una ventana fija de 48h. Con 48h, una caída de más de dos días
- // dejaba sin agregar los samples de 48h..7d, que al purgarse a los 7d
- // producían un hueco permanente en 5m/daily. El orden rollup→purga del job
- // nocturno garantiza que la ventana siempre encuentre el raw disponible.
- const rollupRawWindow = time.Duration(RetentionMS) * time.Millisecond
- // schemaSQL es el SQL literal de src/db.js:20-85.
- const schemaSQL = `
- -- Sesiones (cookie id.hmac)
- CREATE TABLE IF NOT EXISTS sessions (
- id TEXT PRIMARY KEY,
- created_at INTEGER NOT NULL,
- expires_at INTEGER NOT NULL,
- ua TEXT
- );
- -- Rate-limit de login por IP
- CREATE TABLE IF NOT EXISTS login_attempts (
- ip TEXT PRIMARY KEY,
- attempts INTEGER DEFAULT 0,
- locked_until INTEGER DEFAULT 0
- );
- -- Clave-valor (session_secret, auth_pass_hash, ...)
- CREATE TABLE IF NOT EXISTS kv (
- key TEXT PRIMARY KEY,
- value TEXT
- );
- -- Métricas por router y tick del poller
- CREATE TABLE IF NOT EXISTS metrics (
- router_id TEXT NOT NULL,
- ts INTEGER NOT NULL,
- cpu REAL, ram REAL, temp REAL,
- latency_ms REAL, rx_bps REAL, tx_bps REAL,
- PRIMARY KEY (router_id, ts)
- );
- CREATE INDEX IF NOT EXISTS idx_metrics_router_ts ON metrics(router_id, ts);
- -- Escalera de retención: raw 7 días → buckets
- -- 5 min 1 año → daily ∞. El job nocturno hace el rollup en este orden; el
- -- endpoint de histórico sirve largo plazo desde estos niveles.
- CREATE TABLE IF NOT EXISTS metrics_buckets (
- router_id TEXT NOT NULL,
- bucket_ts INTEGER NOT NULL,
- n INTEGER NOT NULL,
- min_ts INTEGER NOT NULL,
- cpu_min REAL, cpu_max REAL, cpu_avg REAL,
- ram_min REAL, ram_max REAL, ram_avg REAL,
- temp_min REAL, temp_max REAL, temp_avg REAL,
- lat_min REAL, lat_max REAL, lat_avg REAL,
- rx_min REAL, rx_max REAL, rx_avg REAL,
- tx_min REAL, tx_max REAL, tx_avg REAL,
- PRIMARY KEY (router_id, bucket_ts)
- );
- CREATE INDEX IF NOT EXISTS idx_metrics_buckets_ts ON metrics_buckets(bucket_ts);
- CREATE TABLE IF NOT EXISTS metrics_daily (
- router_id TEXT NOT NULL,
- date TEXT NOT NULL,
- n INTEGER NOT NULL,
- cpu_avg REAL, ram_avg REAL, temp_avg REAL,
- lat_avg REAL, rx_avg REAL, tx_avg REAL,
- rx_total REAL, tx_total REAL,
- -- up_min: LEGACY (#987). Minutos de recolección asumiendo poll de 5 s
- -- (SUM(n) * 5 / 60): con cualquier otro intervalo miente (con poll de 30 s
- -- da 240 min/día). Los informes ya no lo leen; usan up_count.
- up_min INTEGER NOT NULL DEFAULT 0,
- -- up_count: nº de buckets de 5 min con datos (288 = día completo). Es la
- -- base de la disponibilidad de los informes: agnóstica del intervalo de
- -- poll mientras este sea < 5 min.
- up_count INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (router_id, date)
- );
- -- Estadísticas AdGuard por tick
- CREATE TABLE IF NOT EXISTS adguard_stats (
- ts INTEGER NOT NULL,
- queries INTEGER, blocked INTEGER
- );
- CREATE INDEX IF NOT EXISTS idx_adguard_ts ON adguard_stats(ts);
- -- Usuarios (multiusuario: el admin gestiona altas/bajas/passwords)
- CREATE TABLE IF NOT EXISTS users (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- username TEXT UNIQUE NOT NULL,
- pass_hash TEXT NOT NULL,
- role TEXT NOT NULL DEFAULT 'user',
- created_at INTEGER NOT NULL
- );
- -- Última atribución conocida por MAC
- CREATE TABLE IF NOT EXISTS device_attrib (
- mac TEXT PRIMARY KEY,
- router_id TEXT,
- band TEXT,
- signal_dbm INTEGER,
- last_seen INTEGER NOT NULL
- );
- -- Primera/última vez que el server vio online a cada cliente (#954).
- -- A diferencia de device_events (transiciones, con retención) y de
- -- device_attrib (solo wireless), aquí entra TODA MAC vista online en el
- -- ciclo del poller; first_seen no se toca nunca tras el alta.
- CREATE TABLE IF NOT EXISTS device_seen (
- mac TEXT PRIMARY KEY,
- first_seen INTEGER NOT NULL,
- last_seen INTEGER NOT NULL
- );
- -- #1278: lápidas de clientes borrados a mano. Sin esto, cualquier fuente
- -- que vuelva a reportar la MAC online (una entrada cacheada del AP, un
- -- colector) la re-alta y el borrado "no funciona".
- CREATE TABLE IF NOT EXISTS deleted_clients (
- mac TEXT PRIMARY KEY,
- deleted_at INTEGER NOT NULL
- );
- -- #1151: cliente con varias MACs (un hostname, nunca simultáneas): cada fila
- -- dice "esta MAC es el mismo cliente que canonical". Clave = alias; el
- -- canónico no tiene fila propia (ausencia de fila = MAC canónica).
- CREATE TABLE IF NOT EXISTS device_links (
- mac TEXT PRIMARY KEY,
- canonical TEXT NOT NULL
- );
- -- Routers configurados
- CREATE TABLE IF NOT EXISTS routers (
- id TEXT PRIMARY KEY,
- name TEXT,
- host TEXT NOT NULL,
- type TEXT NOT NULL DEFAULT 'openwrt',
- is_gateway INTEGER NOT NULL DEFAULT 0,
- created_at INTEGER NOT NULL
- );
- -- Allowlist de dispositivos confiables (issue #196): una MAC conocida no
- -- dispara "dispositivo desconocido" y su name se usa como alias.
- CREATE TABLE IF NOT EXISTS known_macs (
- mac TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- note TEXT,
- created_at INTEGER NOT NULL
- );
- -- Suscripciones Web Push (Fase 3 Bloque C; sin paridad Node: el push es
- -- nuevo en Go). created_at en milisegundos como el resto de epochs.
- CREATE TABLE IF NOT EXISTS push_subscriptions (
- endpoint TEXT PRIMARY KEY,
- keys_auth TEXT NOT NULL,
- keys_p256dh TEXT NOT NULL,
- user_agent TEXT,
- created_at INTEGER NOT NULL
- );
- -- DLQ de webhooks salientes (Fase 8.7b): eventos no entregados tras agotar
- -- reintentos. event_id único (idempotencia del emisor).
- CREATE TABLE IF NOT EXISTS webhook_events (
- event_id TEXT PRIMARY KEY,
- payload TEXT NOT NULL,
- sent_at INTEGER NOT NULL,
- error TEXT
- );
- CREATE TABLE IF NOT EXISTS orchestr_plans (
- id TEXT PRIMARY KEY,
- router_id TEXT NOT NULL,
- resource TEXT NOT NULL,
- desired TEXT NOT NULL,
- diff TEXT NOT NULL,
- status TEXT NOT NULL DEFAULT 'pending',
- created_by TEXT NOT NULL,
- created_at INTEGER NOT NULL,
- applied_at INTEGER,
- result TEXT
- );
- CREATE TABLE IF NOT EXISTS orchestr_audit (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- plan_id TEXT NOT NULL,
- action TEXT NOT NULL,
- actor TEXT NOT NULL,
- detail TEXT,
- ts INTEGER NOT NULL
- );
- -- roam_events: feed continuo de eventos hostapd/DAWN (Fase 14.5).
- -- Ingesta cada 60s via logread grep; dedup por content_hash.
- CREATE TABLE IF NOT EXISTS roam_events (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- ts_ms INTEGER NOT NULL,
- router_id TEXT NOT NULL,
- type TEXT NOT NULL,
- mac TEXT,
- iface TEXT,
- detail TEXT,
- content_hash TEXT NOT NULL
- );
- CREATE UNIQUE INDEX IF NOT EXISTS idx_roam_events_dedup ON roam_events(content_hash);
- CREATE INDEX IF NOT EXISTS idx_roam_events_ts ON roam_events(ts_ms DESC);
- CREATE INDEX IF NOT EXISTS idx_roam_events_router_ts ON roam_events(router_id, ts_ms DESC);
- -- device_events: transiciones offline/online detectadas por el poller (issue #184).
- -- Generados por el adapter Live en el ciclo de buildDevices; consultables por API.
- CREATE TABLE IF NOT EXISTS device_events (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- ts_ms INTEGER NOT NULL,
- mac TEXT NOT NULL,
- router_id TEXT,
- state TEXT NOT NULL, -- 'offline' | 'online'
- signal_dbm INTEGER,
- detail TEXT
- );
- CREATE INDEX IF NOT EXISTS idx_device_events_ts ON device_events(ts_ms DESC);
- CREATE INDEX IF NOT EXISTS idx_device_events_mac_ts ON device_events(mac, ts_ms DESC);
- -- Overrides manuales de topología (issue #142, Fase A): capa 2 sobre el
- -- autodiscover. El builder los aplica DESPUÉS de inferTopology.
- -- kind 'hypervisor' (target MAC): el dispositivo es un hipervisor; los CTs
- -- con OUI de hipervisor del mismo puerto se anidan bajo él.
- -- kind 'switch' (target MAC): el dispositivo es un switch manual (sin LLDP);
- -- el puerto del target pasa a ser nodo managed con esa MAC.
- -- kind 'attach' (target MAC, parent MAC): el target cuelga del parent.
- CREATE TABLE IF NOT EXISTS topology_overrides (
- id TEXT PRIMARY KEY,
- mac TEXT NOT NULL, -- target normalizado (minúsculas, '-')
- kind TEXT NOT NULL, -- 'hypervisor' | 'switch' | 'attach'
- name TEXT, -- nombre personalizado (opcional)
- parent TEXT, -- kind='attach': MAC del padre
- enabled INTEGER NOT NULL DEFAULT 1,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS idx_topo_overrides_mac ON topology_overrides(mac);
- -- Historial de actualizaciones (issue #159): registro de cada apply del
- -- updater. En canal rolling main version_from/to son SHAs de commit.
- CREATE TABLE IF NOT EXISTS update_history (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- event_id TEXT NOT NULL,
- ts INTEGER NOT NULL,
- action TEXT NOT NULL,
- channel TEXT NOT NULL,
- version_from TEXT,
- version_to TEXT,
- initiated_by TEXT NOT NULL DEFAULT '',
- status TEXT NOT NULL DEFAULT 'running',
- duration_ms INTEGER,
- backup_path TEXT,
- error TEXT
- );
- CREATE INDEX IF NOT EXISTS idx_update_history_ts ON update_history(ts DESC);
- -- Overrides manuales de dispositivo (issue #437): alias, icono y estado de
- -- bloqueo por banda. La clave es la MAC normalizada (minúsculas, ':').
- -- #797: name (nombre visible) y device_type (override del tipo clasificado).
- CREATE TABLE IF NOT EXISTS device_overrides (
- mac TEXT PRIMARY KEY,
- icon TEXT,
- name TEXT NOT NULL DEFAULT '',
- device_type TEXT NOT NULL DEFAULT '',
- banned_bands TEXT NOT NULL DEFAULT '', -- lista separada por comas: '2.4,5,6'
- notify_offline INTEGER NOT NULL DEFAULT 0, -- issue #1354: alert opt-in cuando se desconecta
- name_source TEXT NOT NULL DEFAULT '', -- #2163: fuente de nombre elegida por cliente ('' = automática)
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- -- Per-port time series (issue #302): raw (7d) -> 5m (1y) -> daily (forever).
- CREATE TABLE IF NOT EXISTS port_series_raw (
- router_id TEXT NOT NULL,
- port_id TEXT NOT NULL,
- ts INTEGER NOT NULL,
- rx_bytes INTEGER NOT NULL DEFAULT 0,
- tx_bytes INTEGER NOT NULL DEFAULT 0,
- rx_errors INTEGER NOT NULL DEFAULT 0,
- tx_errors INTEGER NOT NULL DEFAULT 0,
- rx_frames INTEGER NOT NULL DEFAULT 0,
- tx_frames INTEGER NOT NULL DEFAULT 0,
- rx_bps REAL NOT NULL DEFAULT 0,
- tx_bps REAL NOT NULL DEFAULT 0,
- speed_mbps INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (router_id, port_id, ts)
- );
- -- #817: solo el índice por ts (retención). El PK (router_id, port_id, ts) ya
- -- cubre las consultas por router/puerto; idx_port_series_raw_rpt era idéntico
- -- al PK y se elimina (DROP INDEX en Open para las DBs existentes).
- CREATE INDEX IF NOT EXISTS idx_port_series_raw_ts ON port_series_raw(ts);
- CREATE TABLE IF NOT EXISTS port_series_5m (
- router_id TEXT NOT NULL,
- port_id TEXT NOT NULL,
- bucket_ts INTEGER NOT NULL,
- n INTEGER NOT NULL,
- rx_bytes INTEGER NOT NULL DEFAULT 0,
- tx_bytes INTEGER NOT NULL DEFAULT 0,
- rx_errors INTEGER NOT NULL DEFAULT 0,
- tx_errors INTEGER NOT NULL DEFAULT 0,
- rx_frames INTEGER NOT NULL DEFAULT 0,
- tx_frames INTEGER NOT NULL DEFAULT 0,
- rx_bps_min REAL NOT NULL DEFAULT 0,
- rx_bps_max REAL NOT NULL DEFAULT 0,
- rx_bps_avg REAL NOT NULL DEFAULT 0,
- tx_bps_min REAL NOT NULL DEFAULT 0,
- tx_bps_max REAL NOT NULL DEFAULT 0,
- tx_bps_avg REAL NOT NULL DEFAULT 0,
- speed_mbps INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (router_id, port_id, bucket_ts)
- );
- CREATE INDEX IF NOT EXISTS idx_port_series_5m_ts ON port_series_5m(bucket_ts);
- CREATE TABLE IF NOT EXISTS port_series_daily (
- router_id TEXT NOT NULL,
- port_id TEXT NOT NULL,
- date TEXT NOT NULL,
- n INTEGER NOT NULL,
- rx_bytes INTEGER NOT NULL DEFAULT 0,
- tx_bytes INTEGER NOT NULL DEFAULT 0,
- rx_errors INTEGER NOT NULL DEFAULT 0,
- tx_errors INTEGER NOT NULL DEFAULT 0,
- rx_frames INTEGER NOT NULL DEFAULT 0,
- tx_frames INTEGER NOT NULL DEFAULT 0,
- rx_bps_avg REAL NOT NULL DEFAULT 0,
- tx_bps_avg REAL NOT NULL DEFAULT 0,
- speed_mbps INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (router_id, port_id, date)
- );
- -- wifi_scans: scans pasivos de vecinos recogidos por el agente (#452).
- -- Se guardan por push para poder hacer recomendaciones de canal.
- CREATE TABLE IF NOT EXISTS wifi_scans (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- router_id TEXT NOT NULL,
- iface TEXT NOT NULL,
- bssid TEXT NOT NULL,
- ssid TEXT NOT NULL DEFAULT '',
- channel INTEGER NOT NULL,
- freq INTEGER NOT NULL,
- signal_dbm INTEGER NOT NULL,
- width_mhz INTEGER NOT NULL DEFAULT 0,
- ts INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
- CREATE INDEX IF NOT EXISTS idx_wifi_scans_channel ON wifi_scans(channel, freq);
- -- wifi_scan_outcomes (#1848): ultimo resultado del scan de vecinos por
- -- interfaz. Guarda el motivo cuando el driver lo rechaza, para que la vista
- -- de canales no muestre una banda vacia sin explicacion. Es el ultimo estado
- -- conocido, no un historico: una fila por router e interfaz.
- CREATE TABLE IF NOT EXISTS wifi_scan_outcomes (
- router_id TEXT NOT NULL,
- iface TEXT NOT NULL,
- phy INTEGER NOT NULL DEFAULT -1,
- bss INTEGER NOT NULL DEFAULT 0,
- err TEXT NOT NULL DEFAULT '',
- ts INTEGER NOT NULL,
- PRIMARY KEY (router_id, iface)
- );
- -- Firmware upgrades de routers OpenWrt (#453).
- -- firmware_targets: información de firmware soportado por router.
- CREATE TABLE IF NOT EXISTS firmware_targets (
- router_id TEXT PRIMARY KEY,
- model TEXT NOT NULL,
- current_version TEXT NOT NULL DEFAULT '',
- target_version TEXT NOT NULL DEFAULT '',
- target_url TEXT NOT NULL DEFAULT '',
- checksum TEXT NOT NULL DEFAULT '',
- updated_at INTEGER NOT NULL
- );
- -- firmware_upgrades: historial y estado de upgrades en curso.
- CREATE TABLE IF NOT EXISTS firmware_upgrades (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- router_id TEXT NOT NULL,
- target_version TEXT NOT NULL,
- target_url TEXT NOT NULL,
- checksum TEXT NOT NULL DEFAULT '',
- status TEXT NOT NULL DEFAULT 'idle',
- error TEXT NOT NULL DEFAULT '',
- backup_path TEXT,
- started_at INTEGER NOT NULL,
- finished_at INTEGER,
- -- #494: programación de upgrades desatendidos (epoch ms UTC; NULL = flujo
- -- manual/inmediato sin programar). started_at/finished_at siguen en segundos.
- scheduled_for INTEGER
- );
- CREATE INDEX IF NOT EXISTS idx_firmware_upgrades_router_started ON firmware_upgrades(router_id, started_at DESC);
- -- Log de alertas persistido (issue #798): el historial sobrevive a reinicios
- -- (el self-update del updater reinicia el proceso y antes se perdía entero).
- -- La lista en memoria sigue acotada a los 100 más recientes; aquí se guardan
- -- hasta 500 para poder restaurarlos. read_flag va aparte en kv (readSet), pero
- -- se espeja en la columna para restaurarlo al cargar. (OJO: "read" crudo es
- -- problemático como nombre de columna; por eso read_flag.)
- CREATE TABLE IF NOT EXISTS alert_log (
- id TEXT PRIMARY KEY,
- ts INTEGER NOT NULL,
- category TEXT NOT NULL,
- type TEXT NOT NULL DEFAULT '',
- severity TEXT NOT NULL DEFAULT '',
- urgent INTEGER NOT NULL DEFAULT 0,
- title TEXT NOT NULL,
- description TEXT NOT NULL DEFAULT '',
- hint TEXT NOT NULL DEFAULT '',
- router_id TEXT NOT NULL DEFAULT '',
- suppressed_by TEXT NOT NULL DEFAULT '',
- vars TEXT NOT NULL DEFAULT '',
- read_flag INTEGER NOT NULL DEFAULT 0,
- resolves TEXT NOT NULL DEFAULT ''
- );
- CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
- -- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
- -- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):
- -- rack_mounts.device_mac apunta a esa identidad y device_rack_profile guarda
- -- el modelo físico compartido (faceplate, altura U, span de columnas,
- -- color y puertos con posición). Los montajes con device_mac NULL son
- -- accesorios (blank, shelf, patch panel, PDU): su tamaño lo define el
- -- faceplate del catálogo.
- CREATE TABLE IF NOT EXISTS racks (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- u_height INTEGER NOT NULL,
- width_standard TEXT NOT NULL DEFAULT '19', -- '19' | '10'
- numbering TEXT NOT NULL DEFAULT 'bottom-up', -- solo cambia etiquetas, nunca la geometría
- style_json TEXT NOT NULL DEFAULT '{}',
- location TEXT,
- position_x REAL NOT NULL DEFAULT 0,
- position_y REAL NOT NULL DEFAULT 0
- );
- CREATE TABLE IF NOT EXISTS device_rack_profile (
- mac TEXT PRIMARY KEY,
- faceplate_id TEXT NOT NULL DEFAULT '',
- u_height INTEGER NOT NULL DEFAULT 1,
- col_span INTEGER NOT NULL DEFAULT 12,
- color TEXT NOT NULL DEFAULT '',
- ports_json TEXT NOT NULL DEFAULT '[]'
- );
- CREATE TABLE IF NOT EXISTS rack_mounts (
- id TEXT PRIMARY KEY,
- rack_id TEXT NOT NULL REFERENCES racks(id) ON DELETE CASCADE,
- device_mac TEXT REFERENCES device_rack_profile(mac) ON DELETE SET NULL, -- NULL = accesorio
- faceplate_id TEXT NOT NULL DEFAULT '', -- accesorios; el de dispositivos vive en device_rack_profile
- u_start INTEGER NOT NULL, -- 1-based, SIEMPRE contado desde el rail inferior
- col_start INTEGER NOT NULL DEFAULT 0, -- 0-based
- label TEXT,
- status_pin TEXT NOT NULL DEFAULT 'auto', -- 'auto' → seguir el estado que conoce el poller
- port_visibility TEXT NOT NULL DEFAULT 'auto'
- );
- CREATE INDEX IF NOT EXISTS idx_rack_mounts_rack ON rack_mounts(rack_id);
- -- Cables port-to-port (relación propia, no edges del canvas lógico).
- -- Pueden cruzar racks. Un puerto normal admite exactamente 1 cable; los
- -- patch panels (pass-through) admiten 2 (tirada de pared al rear + patch al
- -- switch al front). Cobre vs fibra se deriva del puerto de origen del patch.
- CREATE TABLE IF NOT EXISTS rack_cables (
- id TEXT PRIMARY KEY,
- from_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
- from_port TEXT NOT NULL,
- to_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
- to_port TEXT NOT NULL,
- type TEXT NOT NULL DEFAULT 'ethernet', -- 'ethernet' | 'fiber'
- label TEXT,
- properties_json TEXT NOT NULL DEFAULT '{}', -- key/value libre
- origin TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'imported' | 'detected'
- created_at INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
- CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
- -- External router integrations (#1674): pushers de routers externos
- -- (MikroTik RouterOS, Asuswrt) gestionados desde la app. El slug es el id
- -- del router external asociado (push autenticado por Bearer token de agente,
- -- agent.token.<slug>). La contraseña nunca se persiste: vive en el fichero
- -- de entorno <data>/integrations/<slug>.env (0600).
- CREATE TABLE IF NOT EXISTS router_integrations (
- slug TEXT PRIMARY KEY,
- vendor TEXT NOT NULL,
- mode TEXT NOT NULL,
- host TEXT NOT NULL,
- username TEXT NOT NULL,
- version TEXT NOT NULL DEFAULT '',
- asset TEXT NOT NULL DEFAULT '',
- arch TEXT NOT NULL,
- interval_s INTEGER NOT NULL,
- enabled INTEGER NOT NULL DEFAULT 0,
- state TEXT NOT NULL DEFAULT 'pending',
- last_error TEXT NOT NULL DEFAULT '',
- last_start_ms INTEGER NOT NULL DEFAULT 0,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- CREATE INDEX IF NOT EXISTS idx_router_integrations_vendor ON router_integrations(vendor);
- -- Agregado horario del query log de AdGuard (#2078): por dispositivo (MAC) y
- -- dominio. MAC vacía = sin atribuir (IP sin correspondencia en device_seen).
- -- Nunca se guarda el log crudo. Retención: 7 días (Maintenance).
- CREATE TABLE IF NOT EXISTS dns_activity (
- mac TEXT NOT NULL,
- domain TEXT NOT NULL,
- hour_ts INTEGER NOT NULL, -- inicio de la hora, ms epoch
- queries INTEGER NOT NULL DEFAULT 0,
- blocked INTEGER NOT NULL DEFAULT 0,
- first_seen INTEGER NOT NULL,
- last_seen INTEGER NOT NULL,
- PRIMARY KEY (mac, domain, hour_ts)
- );
- CREATE INDEX IF NOT EXISTS idx_dns_activity_hour ON dns_activity(hour_ts);
- CREATE INDEX IF NOT EXISTS idx_dns_activity_domain ON dns_activity(domain, hour_ts);
- -- Primera vez que se vio cada dominio (#2078): alimenta el aviso de dominios
- -- nuevos. Retención: 90 días (Maintenance).
- CREATE TABLE IF NOT EXISTS dns_domain_first (
- domain TEXT PRIMARY KEY,
- first_seen INTEGER NOT NULL,
- mac TEXT NOT NULL DEFAULT ''
- );
- CREATE INDEX IF NOT EXISTS idx_dns_domain_first_ts ON dns_domain_first(first_seen);
- `
- // DB envuelve *sql.DB con los jobs y helpers de paridad.
- type DB struct {
- *sql.DB
- Path string
- stop chan struct{}
- wg sync.WaitGroup
- close sync.Once
- // rollbackJournal: escape hatch (#1700) para journal DELETE (comportamiento
- // on-box previo). Los wal_checkpoint de mantenimiento se omiten en este
- // modo; en WAL (el default de todos los despliegues) sí corren.
- rollbackJournal bool
- // PortSeries: per-port time series store (issue #302).
- PortSeries *portseries.Store
- // WGSeries: contadores por peer de WireGuard con ventana real (#2019).
- WGSeries *wgseries.Store
- // ClientBW: per-client bandwidth store (issue #337/#551). Wiring añadido
- // en el #551: la ingesta escribe samples delta por (mac, router).
- ClientBW *clientbw.Store
- }
- // NowMS devuelve el epoch actual en milisegundos (como Date.now()).
- func NowMS() int64 { return time.Now().UnixMilli() }
- // OpenOption configura Open (variádica: los callers existentes no cambian).
- type OpenOption func(*openOptions)
- type openOptions struct {
- rollbackJournal bool
- // tempStore: 'memory'|'file'|'default' (#1700). Vacío = memory.
- tempStore string
- }
- // WithRollbackJournal: `journal_mode=DELETE` + `synchronous=FULL` en vez de
- // WAL+NORMAL. Histórico modo on-box (Fase 9 R6): se pensaba que el fichero
- // -wal y sus checkpoints eran el churn caro, pero las medidas de la issue
- // #1700 demostraron lo contrario (45 GB/día en DELETE+FULL frente a 13.7 en
- // WAL con la misma flota: cada transacción reescribía páginas + journal y
- // ext4 duplicaba todo con su propio journal). Desde #1700 TODOS los
- // despliegues van en WAL+NORMAL por defecto y esta opción es solo el escape
- // hatch para restaurar el modo anterior (NETPULSE_DB_ROLLBACK_JOURNAL=1).
- // Los wal_checkpoint de mantenimiento se omiten en este modo.
- func WithRollbackJournal() OpenOption {
- return func(o *openOptions) { o.rollbackJournal = true }
- }
- // WithTempStore fija PRAGMA temp_store: 'memory'|'file'|'default' (#1700).
- // Por defecto TODOS los despliegues van en 'memory': las agregaciones
- // (GROUP BY/ORDER BY sobre expresiones, p. ej. buckets de métricas y
- // channel plan) hacen spill a ficheros temporales etilqs_*; el reporte
- // midió ~9 GB/día de escrituras en esos temporales con una BD de ~100 MB.
- // El coste en RAM de guardarlos (unos MB por query) es trivial frente a ese
- // volumen, y crítico en un USB (on-box). 'file'/'default' quedan para
- // diagnosticar con el comportamiento clásico.
- func WithTempStore(mode string) OpenOption {
- return func(o *openOptions) { o.tempStore = strings.ToLower(mode) }
- }
- // Open abre (o crea) dir/netpulse.db, ejecuta la migración Node→Go si la
- // DB ya existía con esquema Node (backup atómico antes de tocar nada),
- // aplica pragmas, crea el schema y arranca el mantenimiento horario. dir es
- // DB_DIR, que por defecto es DATA_DIR.
- func Open(dir string, opts ...OpenOption) (*DB, error) {
- var o openOptions
- for _, opt := range opts {
- opt(&o)
- }
- // #1795: el grupo del servicio puede leer backups y datos sin ser owner.
- if err := os.MkdirAll(dir, 0o770); err != nil {
- return nil, err
- }
- if err := os.Chmod(dir, 0o770); err != nil {
- return nil, err
- }
- dbPath := filepath.Join(dir, databaseFile)
- // Migración Node→Go (§12 del SPEC): si el fichero ya existe con esquema
- // Node, backup + importación (preserva users/kv/sessions/routers/metrics).
- rep, err := MigrateNodeDB(dbPath)
- if err != nil {
- return nil, fmt.Errorf("Node→Go migration: %w", err)
- }
- if rep != nil {
- rep.Log()
- }
- // Una sola conexión: better-sqlite3 es síncrono/serial; con maxOpenConns=1
- // Go serializa igual y evita SQLITE_BUSY en WAL.
- sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
- if err != nil {
- return nil, err
- }
- sqldb.SetMaxOpenConns(1)
- pragmas := []string{
- "PRAGMA journal_mode = WAL",
- "PRAGMA synchronous = NORMAL",
- "PRAGMA foreign_keys = ON",
- }
- if o.rollbackJournal {
- // Escape hatch (#1700, antes modo on-box): una DB previa en WAL se
- // convierte sola: con una única conexión el cambio de journal_mode
- // hace checkpoint y elimina el -wal.
- pragmas = []string{
- "PRAGMA journal_mode = DELETE",
- "PRAGMA synchronous = FULL",
- "PRAGMA foreign_keys = ON",
- }
- }
- // PRAGMA temp_store (#1700): con MaxOpenConns(1) la única conexión
- // compartida hereda el pragma para todas las queries (si el pool la
- // recrea tras un error, SQLite vuelve al default; caso marginal).
- switch o.tempStore {
- case "", "memory":
- pragmas = append(pragmas, "PRAGMA temp_store = MEMORY")
- case "file":
- pragmas = append(pragmas, "PRAGMA temp_store = FILE")
- case "default":
- // sin pragma: comportamiento SQLite por defecto (fichero)
- }
- for _, p := range pragmas {
- if _, err := sqldb.Exec(p); err != nil {
- sqldb.Close()
- return nil, fmt.Errorf("pragma %q: %w", p, err)
- }
- }
- // Log del modo efectivo (#1700): lo que manda es lo que SQLite aceptó
- // (p. ej. un filesystem sin soporte WAL dejaría DELETE); una línea al
- // arrancar evita diagnosticar a ciegas el volumen de escrituras.
- var jMode any
- var tMode any
- _ = sqldb.QueryRow("PRAGMA journal_mode").Scan(&jMode)
- _ = sqldb.QueryRow("PRAGMA temp_store").Scan(&tMode)
- log.Printf("[netpulse] db: journal_mode=%v temp_store=%v", jMode, tMode)
- if _, err := sqldb.Exec(schemaSQL); err != nil {
- sqldb.Close()
- return nil, fmt.Errorf("schema: %w", err)
- }
- // Migraciones tolerantes (ALTER solo si falta la columna; errores tragados)
- migrate(sqldb, "sessions", "ua", "ALTER TABLE sessions ADD COLUMN ua TEXT")
- migrate(sqldb, "sessions", "user_id", "ALTER TABLE sessions ADD COLUMN user_id INTEGER")
- // #1334: dueño autenticado e idioma efectivo de la UI por suscripción push.
- migrate(sqldb, "push_subscriptions", "user_id", "ALTER TABLE push_subscriptions ADD COLUMN user_id INTEGER")
- migrate(sqldb, "push_subscriptions", "language", "ALTER TABLE push_subscriptions ADD COLUMN language TEXT")
- migrate(sqldb, "users", "language", "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
- // SPEC-65 D65-5: nombre visible por usuario ("" = usar el username).
- migrate(sqldb, "users", "display_name", "ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''")
- migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
- // #1917: modo de inventario por unidad. ""/"auto" = comportamiento de
- // siempre (agente si lo hay, SSH si no), "agent" = solo agente (el antiguo
- // agent_only), "ssh" = nunca esperar agente: se inventaria por SSH y no
- // alerta por la ausencia de un agente que no va a existir.
- migrate(sqldb, "routers", "inventory_mode", "ALTER TABLE routers ADD COLUMN inventory_mode TEXT NOT NULL DEFAULT ''")
- migrate(sqldb, "routers", "discovery_overrides", "ALTER TABLE routers ADD COLUMN discovery_overrides TEXT NOT NULL DEFAULT ''")
- // issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
- migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
- // Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.
- migrate(sqldb, "wifi_scans", "width_mhz", "ALTER TABLE wifi_scans ADD COLUMN width_mhz INTEGER NOT NULL DEFAULT 0")
- // #1349: el evento resuelto NO se borra del log: queda marcado con su
- // ts de resolución para revisión posterior (y el evento de cierre lo
- // referencia con `resolves`). 0 = activo/no resuelto.
- migrate(sqldb, "alert_log", "resolved_ts", "ALTER TABLE alert_log ADD COLUMN resolved_ts INTEGER NOT NULL DEFAULT 0")
- // #1466: `resolves` (IDs de los eventos que un cierre resolvió) en JSON.
- // Sin persistirlo, tras un reinicio el evento de cierre perdía sus
- // referencias y el bloque "Resuelve N eventos" desaparecía del log.
- migrate(sqldb, "alert_log", "resolves", "ALTER TABLE alert_log ADD COLUMN resolves TEXT NOT NULL DEFAULT ''")
- // issue #241: target de firmware por router (string libre; NULL/"" = sin comprobar).
- migrate(sqldb, "routers", "firmware_target", "ALTER TABLE routers ADD COLUMN firmware_target TEXT")
- // issue #309: SNMP polling for managed switches.
- migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
- // #1145: último nombre conocido del cliente (retención indefinida).
- migrate(sqldb, "device_seen", "name", "ALTER TABLE device_seen ADD COLUMN name TEXT NOT NULL DEFAULT ''")
- // #2163: evidencia que produjo el nombre elegido; vacía en filas antiguas.
- migrate(sqldb, "device_seen", "name_source", "ALTER TABLE device_seen ADD COLUMN name_source TEXT NOT NULL DEFAULT ''")
- // #1151: última IP conocida (los fantasmas la conservan para la lista y
- // las sugerencias de enlace).
- migrate(sqldb, "device_seen", "ip", "ALTER TABLE device_seen ADD COLUMN ip TEXT NOT NULL DEFAULT ''")
- // #1315: último tipo inferido (no override) del cliente: al expirar el
- // lease la clasificación viva cae en "desconocido" y el icono se perdía;
- // el valor retenido lo conserva (stickiness del tipo, solo se escribe
- // cuando la inferencia viva no es el genérico).
- migrate(sqldb, "device_seen", "device_type", "ALTER TABLE device_seen ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
- // issue #863: sondeo HTTP de la consola de switches RTLPlayground. DEFAULT 1
- // = comportamiento previo; se desactiva por router (la consola del firmware
- // tiene una sola sesión global y cada login tumba la sesión humana).
- migrate(sqldb, "routers", "console_polling", "ALTER TABLE routers ADD COLUMN console_polling INTEGER NOT NULL DEFAULT 1")
- migrate(sqldb, "routers", "snmp_community", "ALTER TABLE routers ADD COLUMN snmp_community TEXT")
- migrate(sqldb, "routers", "snmp_port", "ALTER TABLE routers ADD COLUMN snmp_port INTEGER NOT NULL DEFAULT 0")
- // issue #414: intervalo de polling SNMP configurable (segundos; default 60).
- migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
- // #2042: versión de SNMP por unidad ("1", "2c" o "3"). DEFAULT '2c' deja
- // las filas existentes con el comportamiento actual (comunidad).
- migrate(sqldb, "routers", "snmp_version", "ALTER TABLE routers ADD COLUMN snmp_version TEXT NOT NULL DEFAULT '2c'")
- // #2042: credenciales USM para SNMPv3. Sin usuario no hay v3 posible, así
- // que "" = v3 sin configurar. Los dos passphrases son secretos: no salen
- // nunca por HTTP (mismo criterio que snmp_community).
- migrate(sqldb, "routers", "snmp_v3_user", "ALTER TABLE routers ADD COLUMN snmp_v3_user TEXT NOT NULL DEFAULT ''")
- migrate(sqldb, "routers", "snmp_v3_security_level", "ALTER TABLE routers ADD COLUMN snmp_v3_security_level TEXT NOT NULL DEFAULT 'authPriv'")
- migrate(sqldb, "routers", "snmp_v3_auth_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_proto TEXT NOT NULL DEFAULT 'SHA'")
- migrate(sqldb, "routers", "snmp_v3_auth_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_auth_pass TEXT NOT NULL DEFAULT ''")
- migrate(sqldb, "routers", "snmp_v3_priv_proto", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_proto TEXT NOT NULL DEFAULT 'AES'")
- migrate(sqldb, "routers", "snmp_v3_priv_pass", "ALTER TABLE routers ADD COLUMN snmp_v3_priv_pass TEXT NOT NULL DEFAULT ''")
- migrate(sqldb, "routers", "agent_interval", "ALTER TABLE routers ADD COLUMN agent_interval INTEGER NOT NULL DEFAULT 0")
- // issue #605: puerto SSH por router (dropbear en puerto no estándar).
- migrate(sqldb, "routers", "ssh_port", "ALTER TABLE routers ADD COLUMN ssh_port INTEGER NOT NULL DEFAULT 22")
- // issue #1085: pausa de una unidad de flota (sin sondeo ni alertas, con
- // insignia en la lista y fuera de los desplegables; el histórico se
- // conserva). 0/ausente (columna nueva) = activa.
- migrate(sqldb, "routers", "disabled", "ALTER TABLE routers ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0")
- // issue #716: umbral de alerta por temperatura alta (°C). NULL = 65 default.
- migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
- // issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
- migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
- // issue #761: motor del upgrade ("" = clásico URL+checksum, "owut" = ASU).
- migrate(sqldb, "firmware_upgrades", "engine", "ALTER TABLE firmware_upgrades ADD COLUMN engine TEXT NOT NULL DEFAULT ''")
- // issue #797: nombre visible y tipo de dispositivo sobreescritos a mano.
- migrate(sqldb, "device_overrides", "name", "ALTER TABLE device_overrides ADD COLUMN name TEXT NOT NULL DEFAULT ''")
- migrate(sqldb, "device_overrides", "device_type", "ALTER TABLE device_overrides ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
- // issue #1354: opt-in alert when a marked device goes offline (0 = off).
- migrate(sqldb, "device_overrides", "notify_offline", "ALTER TABLE device_overrides ADD COLUMN notify_offline INTEGER NOT NULL DEFAULT 0")
- // #2163: fuente de nombre elegida a mano para un cliente ('' = automática).
- migrate(sqldb, "device_overrides", "name_source", "ALTER TABLE device_overrides ADD COLUMN name_source TEXT NOT NULL DEFAULT ''")
- // #1354: las filas de alert_log tipadas "device-offline" son eventos de
- // ROUTER offline (ese slug lo emitía trackRouterOffline antes de partirlo
- // en router-offline). Discriminador idempotente: las filas del router
- // llevan "host" en vars; las de cliente nuevas, no (vars = device/router).
- if _, err := sqldb.Exec(`UPDATE alert_log SET type = 'router-offline' WHERE type = 'device-offline' AND vars LIKE '%"host"%'`); err != nil {
- log.Printf("[netpulse] warning: could not migrate router-offline alert type: %v", err)
- }
- // #817: port_series_raw tenía dos índices idénticos a su PK, creados por
- // error en db.go y portseries.go. Se eliminan de forma idempotente (no se
- // vuelven a crear); el VACUUM nocturno recupera el espacio en las DBs ya
- // existentes (~33 MB en una instancia de 266 MB).
- for _, idx := range []string{"idx_port_series_raw_rpt", "idx_port_series_raw_router_port_ts"} {
- if _, err := sqldb.Exec("DROP INDEX IF EXISTS " + idx); err != nil {
- log.Printf("[netpulse] warning: could not drop index %s: %v", idx, err)
- }
- }
- // RouterOS and Asuswrt/Merlin moved to external integrations (#1574,
- // #1579). Keep existing units visible until their owner deploys the
- // pusher. Legacy credential columns remain in place as inert schema.
- if _, err := sqldb.Exec(`UPDATE routers SET type = 'external', agent_only = 1 WHERE type IN ('routeros', 'asuswrt')`); err != nil {
- log.Printf("[netpulse] warning: could not migrate RouterOS/Asuswrt routers to external: %v", err)
- }
- // #1129: las MACs de roam_events se ingirieron en minúsculas (así vienen
- // en los logs hostapd/dawn/usteer) mientras el resto de la app canonicaliza
- // a MAYÚSCULAS (#960): el filtro por cliente no casaba con el histórico.
- // Normalización one-shot de las filas existentes (la ingesta nueva ya
- // normaliza, ver roamevents.ParseLogreadLine).
- if _, err := sqldb.Exec("UPDATE roam_events SET mac = UPPER(mac) WHERE mac IS NOT NULL AND mac != UPPER(mac)"); err != nil {
- log.Printf("[netpulse] warning: could not normalize roam_events MACs: %v", err)
- }
- // Si no hubo migración Node (instalación fresca creada por Go), marca la
- // DB para que el siguiente arranque no dispare una "migración" espuria
- // (backup + reset de login_attempts) sobre una DB ya Go.
- if rep == nil {
- _, _ = sqldb.Exec(
- "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
- migrationMarkerKey, time.Now().Format(time.RFC3339),
- )
- }
- d := &DB{DB: sqldb, Path: dbPath, stop: make(chan struct{}), rollbackJournal: o.rollbackJournal}
- ps, err := portseries.NewStore(sqldb)
- if err != nil {
- sqldb.Close()
- return nil, fmt.Errorf("port_series store: %w", err)
- }
- d.PortSeries = ps
- wg, err := wgseries.NewStore(sqldb)
- if err != nil {
- sqldb.Close()
- return nil, fmt.Errorf("wg_peer_series store: %w", err)
- }
- d.WGSeries = wg
- cb, err := clientbw.NewStore(sqldb)
- if err != nil {
- sqldb.Close()
- return nil, fmt.Errorf("client_bw store: %w", err)
- }
- d.ClientBW = cb
- migrateLowercaseMACTables(sqldb)
- d.wg.Add(1)
- go d.maintenanceLoop()
- return d, nil
- }
- // migrateLowercaseMACTables pasa a la forma canónica en mayúsculas
- // (AA:BB:CC:DD:EE:FF) las tablas que históricamente guardaban MACs en
- // minúsculas. Corre tras clientbw.NewStore para que client_bw_* ya existan.
- // Corre una sola vez: todos los pasos van en una transacción que, al terminar
- // bien, deja la marca macUpperMigratedKey en kv; los arranques siguientes no
- // vuelven a recorrer client_bw_* (millones de filas). Si un paso falla, se
- // registra un warning, se deshace todo y se reintenta en el siguiente arranque;
- // el arranque nunca se aborta.
- func migrateLowercaseMACTables(sqldb *sql.DB) {
- var done int
- if err := sqldb.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", macUpperMigratedKey).Scan(&done); err == nil && done > 0 {
- return
- }
- type step struct {
- name string
- sql string
- }
- steps := []step{
- // device_overrides: PK (mac), sobrevive la fila con updated_at más reciente
- // (empate: la que ya esté en forma canónica, luego mayor rowid).
- {
- name: "dedup device_overrides MACs",
- sql: `DELETE FROM device_overrides
- WHERE ` + macOnlyMatch("mac") + `
- AND EXISTS (
- SELECT 1 FROM device_overrides o2
- WHERE ` + macOnlyMatch("o2.mac") + `
- AND UPPER(REPLACE(o2.mac, '-', ':')) = UPPER(REPLACE(device_overrides.mac, '-', ':'))
- AND o2.rowid != device_overrides.rowid
- AND (
- o2.updated_at > device_overrides.updated_at
- OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) > (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))))
- OR (o2.updated_at = device_overrides.updated_at AND (o2.mac = UPPER(REPLACE(o2.mac, '-', ':'))) = (device_overrides.mac = UPPER(REPLACE(device_overrides.mac, '-', ':'))) AND o2.rowid > device_overrides.rowid)
- )
- )`,
- },
- {
- name: "normalize device_overrides MACs",
- sql: `UPDATE device_overrides
- SET mac = UPPER(REPLACE(mac, '-', ':'))
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- // topology_overrides: PK (id = mac). mac y parent solo se reescriben si
- // son una MAC con ':'; cualquier otra cosa es un id de router (#1485,
- // #690) y se deja como está.
- {
- name: "dedup topology_overrides MACs",
- sql: `DELETE FROM topology_overrides
- WHERE mac GLOB '` + colonMACGlob + `'
- AND EXISTS (
- SELECT 1 FROM topology_overrides t2
- WHERE t2.mac GLOB '` + colonMACGlob + `'
- AND UPPER(REPLACE(t2.mac, '-', ':')) = UPPER(REPLACE(topology_overrides.mac, '-', ':'))
- AND t2.rowid != topology_overrides.rowid
- AND (
- t2.updated_at > topology_overrides.updated_at
- OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) > (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))))
- OR (t2.updated_at = topology_overrides.updated_at AND (t2.mac = UPPER(REPLACE(t2.mac, '-', ':'))) = (topology_overrides.mac = UPPER(REPLACE(topology_overrides.mac, '-', ':'))) AND t2.rowid > topology_overrides.rowid)
- )
- )`,
- },
- {
- name: "normalize topology_overrides MACs",
- sql: `UPDATE topology_overrides
- SET id = UPPER(REPLACE(mac, '-', ':')),
- mac = UPPER(REPLACE(mac, '-', ':'))
- WHERE mac GLOB '` + colonMACGlob + `'
- AND (mac != UPPER(REPLACE(mac, '-', ':')) OR id != UPPER(REPLACE(mac, '-', ':')))`,
- },
- {
- name: "normalize topology_overrides parent MACs",
- // main guardaba el parent tal cual llegaba, sin recortar espacios.
- // TRIM sin segundo argumento solo quita ' '; se recortan también
- // '\t', '\n' y '\r', como strings.TrimSpace.
- sql: `UPDATE topology_overrides
- SET parent = UPPER(` + trimWS("parent") + `)
- WHERE parent IS NOT NULL
- AND ` + trimWS("parent") + ` GLOB '` + colonMACGlob + `'
- AND parent != UPPER(` + trimWS("parent") + `)`,
- },
- // client_bw_raw, client_bw_5m, client_bw_daily: en colisión sobre
- // (mac, router_id, ts/bucket_ts/date) sobrevive la fila ya canónica.
- {
- // Tablas grandes: el duplicado canónico se busca por la clave
- // primaria (índice), no con una subconsulta que recorra la tabla.
- name: "dedup client_bw_raw MACs",
- sql: `DELETE FROM client_bw_raw
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
- AND EXISTS (
- SELECT 1 FROM client_bw_raw b2
- WHERE b2.mac = UPPER(REPLACE(client_bw_raw.mac, '-', ':'))
- AND b2.router_id = client_bw_raw.router_id
- AND b2.ts = client_bw_raw.ts
- )`,
- },
- {
- // OR IGNORE: dos variantes no canónicas de la misma clave (no
- // ocurre con datos reales) no deben abortar el resto; la que queda
- // sin actualizar se borra en el paso siguiente.
- name: "normalize client_bw_raw MACs",
- sql: `UPDATE OR IGNORE client_bw_raw
- SET mac = UPPER(REPLACE(mac, '-', ':'))
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- name: "drop leftover client_bw_raw MAC variants",
- sql: `DELETE FROM client_bw_raw
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- // Tablas grandes: el duplicado canónico se busca por la clave
- // primaria (índice), no con una subconsulta que recorra la tabla.
- name: "dedup client_bw_5m MACs",
- sql: `DELETE FROM client_bw_5m
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
- AND EXISTS (
- SELECT 1 FROM client_bw_5m b2
- WHERE b2.mac = UPPER(REPLACE(client_bw_5m.mac, '-', ':'))
- AND b2.router_id = client_bw_5m.router_id
- AND b2.bucket_ts = client_bw_5m.bucket_ts
- )`,
- },
- {
- // OR IGNORE: dos variantes no canónicas de la misma clave (no
- // ocurre con datos reales) no deben abortar el resto; la que queda
- // sin actualizar se borra en el paso siguiente.
- name: "normalize client_bw_5m MACs",
- sql: `UPDATE OR IGNORE client_bw_5m
- SET mac = UPPER(REPLACE(mac, '-', ':'))
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- name: "drop leftover client_bw_5m MAC variants",
- sql: `DELETE FROM client_bw_5m
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- // Tablas grandes: el duplicado canónico se busca por la clave
- // primaria (índice), no con una subconsulta que recorra la tabla.
- name: "dedup client_bw_daily MACs",
- sql: `DELETE FROM client_bw_daily
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))
- AND EXISTS (
- SELECT 1 FROM client_bw_daily b2
- WHERE b2.mac = UPPER(REPLACE(client_bw_daily.mac, '-', ':'))
- AND b2.router_id = client_bw_daily.router_id
- AND b2.date = client_bw_daily.date
- )`,
- },
- {
- // OR IGNORE: dos variantes no canónicas de la misma clave (no
- // ocurre con datos reales) no deben abortar el resto; la que queda
- // sin actualizar se borra en el paso siguiente.
- name: "normalize client_bw_daily MACs",
- sql: `UPDATE OR IGNORE client_bw_daily
- SET mac = UPPER(REPLACE(mac, '-', ':'))
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- name: "drop leftover client_bw_daily MAC variants",
- sql: `DELETE FROM client_bw_daily
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- // device_rack_profile y rack_mounts: rack_mounts.device_mac tiene
- // REFERENCES device_rack_profile(mac) ON DELETE SET NULL con
- // foreign_keys=ON. Primero se inserta la fila canónica en
- // device_rack_profile (INSERT OR IGNORE preserva la ya mayúscula si
- // existían ambas), luego se reasigna rack_mounts.device_mac y por
- // último se borran los perfiles no canónicos sin disparar SET NULL.
- {
- name: "copy device_rack_profile MACs to canonical",
- sql: `INSERT OR IGNORE INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json)
- SELECT UPPER(REPLACE(mac, '-', ':')), faceplate_id, u_height, col_span, color, ports_json
- FROM device_rack_profile
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- {
- name: "normalize rack_mounts device_mac",
- sql: `UPDATE rack_mounts
- SET device_mac = UPPER(REPLACE(device_mac, '-', ':'))
- WHERE device_mac IS NOT NULL
- AND ` + macOnlyMatch("device_mac") + `
- AND device_mac != UPPER(REPLACE(device_mac, '-', ':'))`,
- },
- {
- name: "delete non-canonical device_rack_profile MACs",
- sql: `DELETE FROM device_rack_profile
- WHERE ` + macOnlyMatch("mac") + ` AND mac != UPPER(REPLACE(mac, '-', ':'))`,
- },
- }
- start := time.Now()
- tx, err := sqldb.Begin()
- if err != nil {
- log.Printf("[netpulse] warning: could not start the MAC migration: %v", err)
- return
- }
- for _, s := range steps {
- if _, err := tx.Exec(s.sql); err != nil {
- _ = tx.Rollback()
- log.Printf("[netpulse] warning: could not %s, MAC migration rolled back: %v", s.name, err)
- return
- }
- }
- if _, err := tx.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
- macUpperMigratedKey, time.Now().Format(time.RFC3339)); err != nil {
- _ = tx.Rollback()
- log.Printf("[netpulse] warning: could not mark the MAC migration done: %v", err)
- return
- }
- if err := tx.Commit(); err != nil {
- log.Printf("[netpulse] warning: could not commit the MAC migration: %v", err)
- return
- }
- log.Printf("[netpulse] db: MACs in overrides, rack and client_bw tables upper-cased (%v)", time.Since(start).Round(time.Millisecond))
- }
- // macUpperMigratedKey marca en kv que migrateLowercaseMACTables ya corrió.
- const macUpperMigratedKey = "mac_upper_tables_migrated"
- // Patrones GLOB de una MAC de 17 caracteres. topology_overrides solo admite la
- // forma con ':', porque sus columnas también guardan ids de router (slugs con
- // '-', que pueden parecer una MAC con guiones); las demás tablas solo guardan
- // MACs y aceptan también '-'. Como macaddr.Normalize, el separador debe ser el
- // mismo en las cinco posiciones: "aa-bb:cc-…" no es una MAC.
- var (
- colonMACGlob = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]:", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
- dashMACGlob = strings.Repeat("[0-9A-Fa-f][0-9A-Fa-f]-", 5) + "[0-9A-Fa-f][0-9A-Fa-f]"
- )
- // trimWS devuelve la expresión SQL que recorta espacios, tabuladores y saltos
- // de línea a ambos lados de col.
- func trimWS(col string) string {
- return "TRIM(" + col + ", ' ' || char(9) || char(10) || char(13))"
- }
- // macOnlyMatch devuelve la condición SQL "col es una MAC con ':' o con '-'",
- // para las tablas que solo guardan MACs.
- func macOnlyMatch(col string) string {
- return "(" + col + " GLOB '" + colonMACGlob + "' OR " + col + " GLOB '" + dashMACGlob + "')"
- }
- // migrate replica src/db.js:143-150: introspección PRAGMA table_info y DDL
- // tragándose errores.
- func migrate(db *sql.DB, table, column, ddl string) {
- rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
- if err != nil {
- return
- }
- defer rows.Close()
- found := false
- for rows.Next() {
- var cid int
- var name, ctype string
- var notnull, pk int
- var dflt sql.NullString
- if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err == nil && name == column {
- found = true
- }
- }
- if !found {
- _, _ = db.Exec(ddl) // errores tragados (paridad)
- }
- }
- // Maintenance ejecuta una pasada de limpieza (paridad src/db.js:107-120):
- // retención 7 días en metrics/adguard_stats, sesiones expiradas, atributos de
- // dispositivos sin verse en 90 días (issue #206) y checkpoint.
- func (d *DB) Maintenance() {
- cutoff := NowMS() - RetentionMS
- steps := []string{
- "DELETE FROM metrics WHERE ts < ?",
- "DELETE FROM adguard_stats WHERE ts < ?",
- }
- for _, q := range steps {
- if _, err := d.Exec(q, cutoff); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- }
- if _, err := d.Exec("DELETE FROM sessions WHERE expires_at < ?", NowMS()); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- // Atributos de dispositivos que no se ven desde hace 90 días (se fueron
- // para siempre): sin esta purga device_attrib crece sin límite y alimenta
- // el listado de dispositivos offline (issue #206).
- attribCutoff := NowMS() - AttribRetentionMS
- if _, err := d.Exec("DELETE FROM device_attrib WHERE last_seen < ?", attribCutoff); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- // Purga de buckets > 1 año (el raw ya se purgó arriba; daily nunca).
- bucketCutoff := NowMS() - BucketsRetentionMS
- if _, err := d.Exec("DELETE FROM metrics_buckets WHERE bucket_ts < ?", bucketCutoff); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- // Agregado DNS (#2078): 7 días de detalle horario y 90 días de "primera
- // vez visto". Son ventanas distintas a propósito: el detalle caduca rápido,
- // el histórico de dominios nuevos solo crece con dominios nuevos.
- if _, err := d.Exec("DELETE FROM dns_activity WHERE hour_ts < ?", NowMS()-DNSActivityRetentionMS); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- if _, err := d.Exec("DELETE FROM dns_domain_first WHERE first_seen < ?", NowMS()-DNSFirstsRetentionMS); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- if !d.rollbackJournal {
- if _, err := d.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
- log.Printf("[netpulse] DB maintenance error: %v", err)
- }
- }
- }
- // NightlyJob ejecuta el rollup de la escalera de retención:
- // samples→buckets (ventana = retención raw, 7d) →
- // buckets→daily (solape 35 días) → checkpoint → optimize. Orden obligatorio:
- // agregar antes de purgar; idempotente (INSERT OR REPLACE) por si el daemon
- // estuvo caído.
- func (d *DB) NightlyJob() {
- start := time.Now()
- log.Printf("[netpulse] nightly rollup: start")
- // 1) samples → buckets 5 min. Ventana = retención raw (#812): recubre
- // caídas de hasta 7 días; con la antigua ventana fija de 48h el tramo
- // 48h..7d quedaba sin agregar y se perdía al purgar el raw.
- if err := d.rollupSamplesToBuckets(rollupRawWindow); err != nil {
- log.Printf("[netpulse] error rollup samples→buckets: %v", err)
- } else {
- log.Printf("[netpulse] rollup samples→buckets OK (%s)", time.Since(start).Round(time.Millisecond))
- }
- // 2) buckets → daily (ventana: últimos 35 días con solape)
- if err := d.rollupBucketsToDaily(35 * 24 * time.Hour); err != nil {
- log.Printf("[netpulse] error rollup buckets→daily: %v", err)
- } else {
- log.Printf("[netpulse] rollup buckets→daily OK (%s)", time.Since(start).Round(time.Millisecond))
- }
- // 3) checkpoint tras los DELETE/INSERT grandes (concentra el WAL);
- // en rollback-journal (on-box) no hay WAL que consolidar.
- if !d.rollbackJournal {
- _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
- }
- // 4) optimize + ANALYZE (estadísticas del planner tras la purga)
- _, _ = d.Exec("PRAGMA optimize")
- _, _ = d.Exec("ANALYZE")
- // 5) VACUUM solo si el freelist creció (> ~4 MB con page_size 4096)
- var freelist int
- if err := d.QueryRow("PRAGMA freelist_count").Scan(&freelist); err == nil && freelist > 1024 {
- if _, err := d.Exec("VACUUM"); err != nil {
- log.Printf("[netpulse] warning: VACUUM failed: %v", err)
- } else {
- log.Printf("[netpulse] rollup nocturno: VACUUM tras freelist=%d", freelist)
- }
- }
- // 6) roam_events: retención fija de 30 días (Fase 14.5). OJO: la
- // retención CONFIGURABLE del usuario es presence.retention_days y la
- // aplica el loop de poda de main; este DELETE solo recoge lo que ese
- // loop pueda dejar (defensa en profundidad, #907).
- cutoff := NowMS() - 30*24*60*60*1000
- if res, err := d.Exec("DELETE FROM roam_events WHERE ts_ms < ?", cutoff); err == nil {
- if n, _ := res.RowsAffected(); n > 0 {
- log.Printf("[netpulse] roam_events: purgados %d eventos >30d", n)
- }
- }
- // 7) device_events: misma retención 30 días (issue #184).
- if res, err := d.Exec("DELETE FROM device_events WHERE ts_ms < ?", cutoff); err == nil {
- if n, _ := res.RowsAffected(); n > 0 {
- log.Printf("[netpulse] device_events: purgados %d eventos >30d", n)
- }
- }
- log.Printf("[netpulse] rollup nocturno: fin (%s)", time.Since(start).Round(time.Millisecond))
- // Per-port time series rollup (issue #302).
- if d.PortSeries != nil {
- d.PortSeries.NightlyJob()
- }
- // Per-client bandwidth rollup (#337/#551).
- if d.ClientBW != nil {
- d.ClientBW.NightlyJob()
- }
- // Per-peer WireGuard counters (#2019).
- if d.WGSeries != nil {
- d.WGSeries.NightlyJob()
- }
- }
- // BucketMS es el tamaño del bucket medio en ms (5 minutos).
- const BucketMS = 5 * 60 * 1000
- // BucketsRetentionMS: 1 año en ms.
- const BucketsRetentionMS = 365 * 24 * 60 * 60 * 1000
- func (d *DB) rollupSamplesToBuckets(window time.Duration) error {
- // Ventana con solape: recomputa buckets de los últimos `window` para
- // cubrir caídas del daemon de hasta ese tiempo. INSERT OR REPLACE idempotente.
- since := NowMS() - window.Milliseconds()
- _, err := d.Exec(`
- INSERT OR REPLACE INTO metrics_buckets
- (router_id, bucket_ts, n, min_ts,
- cpu_min, cpu_max, cpu_avg, ram_min, ram_max, ram_avg,
- temp_min, temp_max, temp_avg, lat_min, lat_max, lat_avg,
- rx_min, rx_max, rx_avg, tx_min, tx_max, tx_avg)
- SELECT
- router_id,
- (ts / ?) * ?,
- COUNT(*),
- MIN(ts),
- MIN(cpu), MAX(cpu), AVG(cpu),
- MIN(ram), MAX(ram), AVG(ram),
- MIN(temp), MAX(temp), AVG(temp),
- MIN(latency_ms), MAX(latency_ms), AVG(latency_ms),
- MIN(rx_bps), MAX(rx_bps), AVG(rx_bps),
- MIN(tx_bps), MAX(tx_bps), AVG(tx_bps)
- FROM metrics
- WHERE ts >= ?
- GROUP BY router_id, (ts / ?)`,
- BucketMS, BucketMS, since, BucketMS)
- return err
- }
- func (d *DB) rollupBucketsToDaily(window time.Duration) error {
- // Agrega buckets → daily por router y día (epoch-UTC). Solape de 35 días
- // para cubrir caídas; INSERT OR REPLACE idempotente.
- since := NowMS() - window.Milliseconds()
- _, err := d.Exec(`
- INSERT OR REPLACE INTO metrics_daily
- (router_id, date, n,
- cpu_avg, ram_avg, temp_avg, lat_avg, rx_avg, tx_avg,
- rx_total, tx_total, up_min, up_count)
- SELECT
- router_id,
- strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch'),
- SUM(n),
- AVG(cpu_avg), AVG(ram_avg), AVG(temp_avg),
- AVG(lat_avg), AVG(rx_avg), AVG(tx_avg),
- SUM(rx_avg * n), SUM(tx_avg * n),
- SUM(n) * 5 / 60, COUNT(*)
- FROM metrics_buckets
- WHERE bucket_ts >= ?
- GROUP BY router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch')`,
- since)
- return err
- }
- // ShouldRunNightly decide si toca ejecutar el rollup: una vez al día en hora
- // valle (03:00-04:00 local). Hora local del host (como la UI).
- func ShouldRunNightly(now time.Time) bool {
- return now.Hour() == 3
- }
- func (d *DB) maintenanceLoop() {
- defer d.wg.Done()
- t := time.NewTicker(Maintenance)
- defer t.Stop()
- // El ticker arranca en Maintenance; el primer fire llega a la 1ª hora.
- // No ejecutar el rollup al arrancar: los datos raw de los últimos 7 días
- // ya están; el siguiente 03:00 los consolida. Evita competir con el
- // arranque (migraciones, primer poll).
- for {
- select {
- case <-d.stop:
- return
- case now := <-t.C:
- if ShouldRunNightly(now) {
- d.NightlyJob()
- } else {
- d.Maintenance()
- }
- }
- }
- }
- // CheckHealth replica dbHandle.checkHealth(): SELECT 1.
- func (d *DB) CheckHealth() bool {
- var ok int
- if err := d.QueryRow("SELECT 1").Scan(&ok); err != nil {
- return false
- }
- return ok == 1
- }
- // Close para el timer, checkpoint TRUNCATE (best-effort) y cierra.
- func (d *DB) Close() error {
- var err error
- d.close.Do(func() {
- close(d.stop)
- d.wg.Wait()
- _, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
- err = d.DB.Close()
- })
- return err
- }
- // ShutdownContext cierra el pool con contexto (para el salvavidas de 3 s).
- func (d *DB) ShutdownContext(ctx context.Context) error {
- done := make(chan error, 1)
- go func() { done <- d.Close() }()
- select {
- case err := <-done:
- return err
- case <-ctx.Done():
- return ctx.Err()
- }
- }
- // KnownMac es una fila de la allowlist (issue #196).
- type KnownMac struct {
- MAC string
- Name string
- Note string
- CreatedAt int64
- }
- // ListKnownMacs devuelve la allowlist ordenada por MAC.
- func (d *DB) ListKnownMacs() ([]KnownMac, error) {
- rows, err := d.Query("SELECT mac, name, note, created_at FROM known_macs ORDER BY mac")
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- out := []KnownMac{}
- for rows.Next() {
- var k KnownMac
- var note sql.NullString
- if err := rows.Scan(&k.MAC, &k.Name, ¬e, &k.CreatedAt); err == nil {
- k.Note = note.String
- out = append(out, k)
- }
- }
- return out, rows.Err()
- }
- // UpsertKnownMac inserta o actualiza una MAC de la allowlist (por MAC).
- func (d *DB) UpsertKnownMac(k KnownMac) error {
- _, err := d.Exec(
- `INSERT INTO known_macs (mac, name, note, created_at) VALUES (?, ?, ?, ?)
- ON CONFLICT(mac) DO UPDATE SET name=excluded.name, note=excluded.note`,
- k.MAC, k.Name, k.Note, NowMS())
- return err
- }
- // AddDeletedClient registra una lápida: el usuario borró este cliente a mano
- // y NO quiere que vuelva a alta solo (#1278).
- func (d *DB) AddDeletedClient(mac string) error {
- _, err := d.Exec("INSERT INTO deleted_clients (mac, deleted_at) VALUES (?, ?) ON CONFLICT(mac) DO UPDATE SET deleted_at=excluded.deleted_at", mac, NowMS())
- return err
- }
- // DeletedClients devuelve el set de MACs enterradas.
- func (d *DB) DeletedClients() (map[string]bool, error) {
- rows, err := d.Query("SELECT mac FROM deleted_clients")
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- out := map[string]bool{}
- for rows.Next() {
- var mac string
- if err := rows.Scan(&mac); err != nil {
- continue
- }
- out[mac] = true
- }
- return out, rows.Err()
- }
- // DeleteDeletedClient quita la lápida: el usuario vuelve a dar de alta la
- // MAC (allowlist/alta guiada), así que puede reaparecer con normalidad.
- func (d *DB) DeleteDeletedClient(mac string) error {
- _, err := d.Exec("DELETE FROM deleted_clients WHERE mac = ?", mac)
- return err
- }
- // DeleteKnownMac quita una MAC de la allowlist.
- func (d *DB) DeleteKnownMac(mac string) error {
- _, err := d.Exec("DELETE FROM known_macs WHERE mac = ?", mac)
- return err
- }
|