"""Versioned, additive-only schema migrations for the component's SQLite database. The generic part (everything above "Migrations of this component") is the same in APP_CORE/migrations.py and APP_PROFILER/migrations.py: the components have separate build contexts and virtualenvs, so each carries its own copy. Keep them in sync. Safety rules: - a migration only adds (tables, columns, indexes); it never drops or rewrites data; - before the first change a consistent backup is made with the SQLite backup API ('.bak-'), unless the database is brand new; - every migration runs in its own savepoint inside one write-locked transaction, so two processes starting at the same time cannot race (the second one waits, then finds nothing pending); - afterwards PRAGMA integrity_check and the row counts of all pre-existing tables are compared with the backup; on a mismatch everything is rolled back; - a database with a higher schema version than the code knows is never touched. """ import logging import os import re import sqlite3 import stat import sys import urllib.parse from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Callable, Optional logger = logging.getLogger(__name__) BACKUPS_KEEP = 5 # number of '.bak-*' files kept per database LOCK_TIMEOUT = 60 # seconds a second process waits for the migration lock class MigrationError(Exception): """A migration could not be applied or verified.""" class SchemaTooNew(MigrationError): """The database was migrated by a newer release than this code.""" class MigrationPending(MigrationError): """Migrations are pending but automatic migration is disabled.""" @dataclass class Migration: version: int name: str apply: Callable[[sqlite3.Connection], None] # runs inside a transaction, no commit @dataclass class Status: db_path: str exists: bool fresh: bool # no tables and no recorded migrations applied: dict = field(default_factory=dict) # version -> name pending: list = field(default_factory=list) # [Migration] too_new: Optional[int] = None # highest version if above the code's @property def current(self): return max(self.applied) if self.applied else 0 @dataclass class Report: db_path: str version: int # schema version after the run applied: list = field(default_factory=list) # [(version, name)] applied by this run backup: Optional[str] = None created: bool = False # the database was new and got the current schema def latest_version(): return max((m.version for m in MIGRATIONS), default=0) def _resolve_path(target): """Accept a path or a SQLAlchemy engine.""" if isinstance(target, (str, os.PathLike)): return os.fspath(target) url = getattr(target, "url", None) if url is not None and url.database: return url.database raise TypeError(f"Cannot get a database path from {target!r}") def _quote(name): return '"' + name.replace('"', '""') + '"' def _tables(conn): rows = conn.execute( "SELECT name FROM sqlite_master WHERE type='table' " "AND substr(name, 1, 7) != 'sqlite_' ORDER BY name") return [r[0] for r in rows] def _read_status(conn, db_path): tables = _tables(conn) applied = {} if "schema_migrations" in tables: applied = {v: n for v, n in conn.execute("SELECT version, name FROM schema_migrations")} known = latest_version() too_new = max(applied) if applied and max(applied) > known else None pending = sorted((m for m in MIGRATIONS if m.version not in applied), key=lambda m: m.version) fresh = not [t for t in tables if t != "schema_migrations"] and not applied return Status(db_path, True, fresh, applied, pending, too_new) def _too_new_error(st): return SchemaTooNew( f"Database {st.db_path} has schema version {st.too_new}, but this release only knows " f"versions up to {latest_version()}. It was migrated by a newer release. The database " f"has not been touched and the service will not start. Install the newer release, or " f"restore a matching backup ('{st.db_path}.bak-*') with the services stopped.") def _quick_status(db_path): """Read-only look at the database, no lock and no changes. None if it cannot be read.""" if not os.path.exists(db_path): return Status(db_path, False, True, {}, sorted(MIGRATIONS, key=lambda m: m.version)) uri = "file:%s?mode=ro" % urllib.parse.quote(os.path.abspath(db_path)) try: conn = sqlite3.connect(uri, uri=True, timeout=LOCK_TIMEOUT) try: return _read_status(conn, db_path) finally: conn.close() except sqlite3.Error: return None def status(target): """Report applied and pending migrations without changing anything.""" db_path = _resolve_path(target) st = _quick_status(db_path) if st is None: raise MigrationError(f"Cannot read database {db_path} (not a SQLite database, or locked)") return st def _integrity_problems(conn): rows = [r[0] for r in conn.execute("PRAGMA integrity_check")] return [] if rows == ["ok"] else rows[:5] def _row_counts(conn): return {t: conn.execute(f"SELECT COUNT(*) FROM {_quote(t)}").fetchone()[0] for t in _tables(conn)} def _backup(conn, db_path): """Consistent copy through the SQLite backup API. Returns (path, row counts of the copy).""" stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") dest = f"{db_path}.bak-{stamp}" n = 0 while os.path.exists(dest): n += 1 dest = f"{db_path}.bak-{stamp}-{n}" tmp = dest + ".part" try: dst = sqlite3.connect(tmp) # A separate read-only connection: the backup API stalls when the source connection # itself holds the write lock. Nothing has been modified yet, so the copy is consistent. src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=LOCK_TIMEOUT) try: src.backup(dst) problems = _integrity_problems(dst) if problems: raise MigrationError("backup copy failed the integrity check: " + "; ".join(problems)) counts = _row_counts(dst) finally: src.close() dst.close() # The copy holds the same secrets as the database: same permissions os.chmod(tmp, stat.S_IMODE(os.stat(db_path).st_mode)) os.replace(tmp, dest) except Exception as e: try: os.remove(tmp) except OSError: pass raise MigrationError(f"Cannot back up {db_path} ({e}). Nothing was changed.") from e logger.info(f"Database backup created: {dest}") return dest, counts def _prune_backups(db_path, keep=BACKUPS_KEEP): """Keep the newest `keep` backups of this database only.""" directory = os.path.dirname(os.path.abspath(db_path)) pattern = re.compile(re.escape(os.path.basename(db_path)) + r"\.bak-(\d{8}T\d{6})(?:-(\d+))?$") found = [] for name in os.listdir(directory): m = pattern.match(name) if m: found.append((m.group(1), int(m.group(2) or 0), name)) found.sort() for _, _, name in (found[:-keep] if keep > 0 else found): try: os.remove(os.path.join(directory, name)) logger.info(f"Old database backup removed: {name}") except OSError as e: logger.warning(f"Cannot remove old backup {name}: {e}") def _stamp(conn, migration): conn.execute( "INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)", (migration.version, migration.name, datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))) def run(target, fresh_schema=None): """Apply pending migrations to the database (path or SQLAlchemy engine). fresh_schema(conn), if given, creates the complete current schema of a brand-new database; all migrations are then recorded as applied without running them. Raises SchemaTooNew / MigrationError; returns a Report.""" db_path = _resolve_path(target) if fresh_schema is None: fresh_schema = FRESH_SCHEMA # Fast path: nothing to do, no lock, no write st = _quick_status(db_path) if st is not None: if st.too_new: raise _too_new_error(st) if not st.pending: return Report(db_path, st.current) db_dir = os.path.dirname(db_path) if db_dir: os.makedirs(db_dir, exist_ok=True) try: conn = sqlite3.connect(db_path, timeout=LOCK_TIMEOUT, isolation_level=None) try: report = _run_locked(conn, db_path, fresh_schema) finally: conn.close() except sqlite3.Error as e: raise MigrationError(f"Database error while migrating {db_path}: {e}") from e if report.backup: _prune_backups(db_path) return report def _run_locked(conn, db_path, fresh_schema): # The write lock is taken before anything is read or changed: a second process # waits here, and then finds nothing pending (and makes no second backup) conn.execute("BEGIN IMMEDIATE") try: st = _read_status(conn, db_path) if st.too_new: raise _too_new_error(st) if not st.pending: conn.execute("ROLLBACK") return Report(db_path, st.current) problems = _integrity_problems(conn) if problems: raise MigrationError( f"Integrity check failed for {db_path}: {'; '.join(problems)}. Nothing was changed.") backup, before = None, {} if not st.fresh: backup, before = _backup(conn, db_path) where = f"backup: {backup}" if backup else "new database, no backup needed" conn.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (" "version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)") applied = [] if st.fresh and fresh_schema is not None: fresh_schema(conn) for m in st.pending: _stamp(conn, m) applied.append((m.version, m.name)) else: for m in st.pending: logger.info(f"Applying migration {m.version} ({m.name}) to {db_path}") conn.execute("SAVEPOINT migration") try: m.apply(conn) _stamp(conn, m) except Exception as e: conn.execute("ROLLBACK TO migration") conn.execute("RELEASE migration") # Migrations completed before this one stay (each is complete in itself) conn.execute("COMMIT" if applied else "ROLLBACK") raise MigrationError( f"Migration {m.version} ({m.name}) failed and was rolled back: {e} " f"[{where}]. The service will not start; fix the cause and run migrate.py " f"again.") from e conn.execute("RELEASE migration") applied.append((m.version, m.name)) # Verify before the commit: on any mismatch nothing is kept problems = _integrity_problems(conn) if problems: raise MigrationError( f"Integrity check failed after migration of {db_path}: {'; '.join(problems)}. " f"The changes were rolled back. Backup: {backup or 'none (new database)'}") after = _row_counts(conn) for table, count in before.items(): if table == "schema_migrations": continue # the bookkeeping table is expected to grow if after.get(table) != count: raise MigrationError( f"Row count of table '{table}' changed during migration ({count} -> " f"{after.get(table)}) in {db_path}. The changes were rolled back. " f"Backup: {backup}") conn.execute("COMMIT") for version, name in applied: logger.info(f"Migration {version} ({name}) applied to {db_path} [{where}]") return Report(db_path, applied[-1][0], applied, backup, st.fresh) except BaseException: if conn.in_transaction: conn.execute("ROLLBACK") raise def startup(target, fresh_schema=None): """Called when a service starts. Applies pending migrations, or, with OVPMON_AUTO_MIGRATE=0, only checks and refuses while any are pending.""" db_path = _resolve_path(target) if os.getenv("OVPMON_AUTO_MIGRATE", "1").strip() == "0": st = status(db_path) if st.too_new: raise _too_new_error(st) if st.pending: names = ", ".join(f"{m.version} ({m.name})" for m in st.pending) raise MigrationPending( f"Database {db_path} is at schema version {st.current}, pending migrations: " f"{names}. Automatic migration is disabled (OVPMON_AUTO_MIGRATE=0): run " f"'python migrate.py' first.") return Report(db_path, st.current) report = run(target, fresh_schema) logger.info(f"Database {db_path}: schema version {report.version}") return report def startup_or_exit(target, fresh_schema=None): """startup() for service entry points: a clear message and a non-zero exit instead of a traceback when the database must not be used.""" try: return startup(target, fresh_schema) except MigrationError as e: logger.critical(str(e)) print(f"FATAL: {e}", file=sys.stderr) sys.exit(1) # --- Migrations of this component ------------------------------------------- def _m001_baseline(conn): """Schema of the releases before versioning (formerly DatabaseManager.init_database): CREATE TABLE IF NOT EXISTS plus the 'add column if missing' steps. Idempotent.""" def _column_exists(table, column): return any(row[1] == column for row in conn.execute(f"PRAGMA table_info({table})")) def _ensure_column(table, column, type_def): if not _column_exists(table, column): logger.info(f"Adding missing column {column} to table {table}") conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}") # 1. Clients Table conn.execute(''' CREATE TABLE IF NOT EXISTS clients ( id INTEGER PRIMARY KEY AUTOINCREMENT, common_name TEXT UNIQUE NOT NULL, real_address TEXT, status TEXT DEFAULT 'Active', total_bytes_received INTEGER DEFAULT 0, total_bytes_sent INTEGER DEFAULT 0, last_bytes_received INTEGER DEFAULT 0, last_bytes_sent INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # 2. Raw Usage History conn.execute(''' CREATE TABLE IF NOT EXISTS usage_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, client_id INTEGER, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, bytes_received INTEGER, bytes_sent INTEGER, bytes_received_rate_mbps REAL, bytes_sent_rate_mbps REAL, FOREIGN KEY (client_id) REFERENCES clients (id) ) ''') conn.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)') # 2.1 Active Sessions (Temporary state table) conn.execute(''' CREATE TABLE IF NOT EXISTS active_sessions ( client_id INTEGER, common_name TEXT, real_address TEXT, bytes_received INTEGER, bytes_sent INTEGER, connected_since TIMESTAMP, last_seen TIMESTAMP, FOREIGN KEY (client_id) REFERENCES clients (id) ) ''') # 2.2 Users and Auth conn.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, totp_secret TEXT, is_2fa_enabled INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # 2.3 Login Attempts (Brute-force protection) conn.execute(''' CREATE TABLE IF NOT EXISTS login_attempts ( ip_address TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # 3. Aggregated Stats Tables tables = ['stats_5min', 'stats_15min', 'stats_hourly', 'stats_6h', 'stats_daily'] for table in tables: conn.execute(f''' CREATE TABLE IF NOT EXISTS {table} ( timestamp TEXT NOT NULL, client_id INTEGER NOT NULL, bytes_received INTEGER DEFAULT 0, bytes_sent INTEGER DEFAULT 0, PRIMARY KEY (timestamp, client_id), FOREIGN KEY (client_id) REFERENCES clients (id) ) ''') conn.execute(f'CREATE INDEX IF NOT EXISTS idx_{table}_ts ON {table}(timestamp)') # 4. Migrations (Ensure columns in existing tables) # If users table existed but was old, ensure it has 2FA columns if conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'").fetchone(): _ensure_column('users', 'totp_secret', 'TEXT') _ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0') def _m002_session_id(conn): """active_sessions.session_id: the Client ID of the session from the OpenVPN v2 status (part of the gatherer's session key). NULL is allowed: rows of an old snapshot and a status without the Client ID column.""" if not any(row[1] == "session_id" for row in conn.execute("PRAGMA table_info(active_sessions)")): conn.execute("ALTER TABLE active_sessions ADD COLUMN session_id TEXT") MIGRATIONS = [ Migration(1, "baseline", _m001_baseline), Migration(2, "session_id", _m002_session_id), ] # No separate "fresh" schema: the baseline migration creates everything on a new database FRESH_SCHEMA = None