// 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 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.). La contraseña nunca se persiste: vive en el fichero -- de entorno /integrations/.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 ''") // 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 ''") // #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") // #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 d.wg.Add(1) go d.maintenanceLoop() return d, nil } // 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 }