From e556d6d4b925dd49d3648bd03199407cd5d323ab Mon Sep 17 00:00:00 2001 From: ayurishchev Date: Mon, 5 Oct 2026 08:37:38 +0300 Subject: [PATCH] Database migrations with backup, integrity checks and downgrade protection - Profiler and monitoring: schema_migrations table, additive ordered migrations, single write lock, integrity check, consistent backup via the SQLite backup API (newest 5 kept), row-count verification before commit, refusal to start on a database newer than the code. - Profiler baseline migration is generated from the models and adds every missing column (replaces ensure_columns and the manual add_*.py scripts). - migrate.py in each component (--check exit 0/2/1, --db); services migrate at start, OVPMON_AUTO_MIGRATE=0 only checks. - Tests: test_migrations.py per component; verified on databases created by the code of commit 3836049 and on the live stand. - Docs: Database_Migrations reference, change summary, deployment scenarios plan, README, Index. Co-Authored-By: Claude Sonnet 5.5 --- APP_CORE/db.py | 117 +---- APP_CORE/migrate.py | 64 +++ APP_CORE/migrations.py | 467 ++++++++++++++++++ APP_CORE/requirements-dev.txt | 2 + APP_CORE/test_migrations.py | 246 +++++++++ APP_PROFILER/database.py | 13 +- APP_PROFILER/main.py | 12 +- APP_PROFILER/migrate.py | 64 +++ APP_PROFILER/migrations.py | 447 +++++++++++++++++ APP_PROFILER/test_migrations.py | 199 ++++++++ DOCS/Changes/2026-10-05_DB_Migrations.md | 43 ++ .../2026-10-05_Deployment_Scenarios_PLAN.md | 77 +++ DOCS/General/Database_Migrations.md | 103 ++++ DOCS/General/Index.md | 1 + README.md | 1 + 15 files changed, 1729 insertions(+), 127 deletions(-) create mode 100755 APP_CORE/migrate.py create mode 100644 APP_CORE/migrations.py create mode 100644 APP_CORE/requirements-dev.txt create mode 100644 APP_CORE/test_migrations.py create mode 100755 APP_PROFILER/migrate.py create mode 100644 APP_PROFILER/migrations.py create mode 100644 APP_PROFILER/test_migrations.py create mode 100644 DOCS/Changes/2026-10-05_DB_Migrations.md create mode 100644 DOCS/Changes/2026-10-05_Deployment_Scenarios_PLAN.md create mode 100644 DOCS/General/Database_Migrations.md diff --git a/APP_CORE/db.py b/APP_CORE/db.py index cd7a318..328b08e 100644 --- a/APP_CORE/db.py +++ b/APP_CORE/db.py @@ -3,6 +3,8 @@ import configparser import os import logging +import migrations + class DatabaseManager: def __init__(self, config_file='config.ini'): self.config_file = config_file @@ -26,7 +28,7 @@ class DatabaseManager: return sqlite3.connect(self.db_path) def init_database(self): - """Initialize the database schema""" + """Initialize the database schema (applies pending migrations)""" # Create directory if needed db_dir = os.path.dirname(self.db_path) if db_dir and not os.path.exists(db_dir): @@ -37,112 +39,7 @@ class DatabaseManager: self.logger.info(f"Using database: {self.db_path}") - conn = self.get_connection() - cursor = conn.cursor() - - def _column_exists(table, column): - cursor.execute(f"PRAGMA table_info({table})") - return any(row[1] == column for row in cursor.fetchall()) - - def _ensure_column(table, column, type_def): - if not _column_exists(table, column): - self.logger.info(f"Adding missing column {column} to table {table}") - cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}") - - try: - # 1. Clients Table - cursor.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 - cursor.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) - ) - ''') - cursor.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)') - - # 2.1 Active Sessions (Temporary state table) - cursor.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 - cursor.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) - cursor.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: - cursor.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) - ) - ''') - cursor.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 - cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'") - if cursor.fetchone(): - _ensure_column('users', 'totp_secret', 'TEXT') - _ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0') - - conn.commit() - self.logger.info("Database initialized with full schema and migrations") - except Exception as e: - self.logger.error(f"Database initialization error: {e}") - finally: - conn.close() + # Schema creation and upgrades live in migrations.py (versioned, with a backup before + # any change). Exits with a clear message if the database is newer than this code or + # migrations are pending while OVPMON_AUTO_MIGRATE=0. + migrations.startup_or_exit(self.db_path) diff --git a/APP_CORE/migrate.py b/APP_CORE/migrate.py new file mode 100755 index 0000000..c0af06f --- /dev/null +++ b/APP_CORE/migrate.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Apply pending database migrations (or only check for them). + + python migrate.py apply pending migrations (backup first) + python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new + python migrate.py --db PATH use this database file instead of the configured one + +Run it from the component directory with the component's virtualenv, like the service. +The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0). +""" +import argparse +import logging +import sys + +import migrations +from db import DatabaseManager + +EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2 + + +def default_db_path(): + return DatabaseManager().db_path + + +def main(argv=None): + parser = argparse.ArgumentParser(description="Database schema migrations") + parser.add_argument("--check", action="store_true", + help="only report: exit 0 = up to date, 2 = pending, 1 = error") + parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)") + args = parser.parse_args(argv) + + logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") + db_path = args.db or default_db_path() + + try: + st = migrations.status(db_path) + if st.too_new: + raise migrations._too_new_error(st) + print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)")) + if args.check: + print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})") + if not st.pending: + print("Pending: none, up to date") + return EXIT_OK + print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending)) + return EXIT_PENDING + before = st.current + report = migrations.run(db_path) + except migrations.MigrationError as e: + print(f"ERROR: {e}", file=sys.stderr) + return EXIT_ERROR + + print(f"Schema version: {before} -> {report.version}") + if report.applied: + print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied)) + else: + print("Applied: nothing, already up to date") + print(f"Backup: {report.backup or 'none'}" + + (" (new database)" if report.created else "")) + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/APP_CORE/migrations.py b/APP_CORE/migrations.py new file mode 100644 index 0000000..4741fe0 --- /dev/null +++ b/APP_CORE/migrations.py @@ -0,0 +1,467 @@ +"""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') + + +MIGRATIONS = [ + Migration(1, "baseline", _m001_baseline), +] + +# No separate "fresh" schema: the baseline migration creates everything on a new database +FRESH_SCHEMA = None diff --git a/APP_CORE/requirements-dev.txt b/APP_CORE/requirements-dev.txt new file mode 100644 index 0000000..26b77f6 --- /dev/null +++ b/APP_CORE/requirements-dev.txt @@ -0,0 +1,2 @@ +-r requirements.txt +pytest diff --git a/APP_CORE/test_migrations.py b/APP_CORE/test_migrations.py new file mode 100644 index 0000000..24091e0 --- /dev/null +++ b/APP_CORE/test_migrations.py @@ -0,0 +1,246 @@ +import glob +import hashlib +import sqlite3 +import threading + +import pytest + +import migrations +from db import DatabaseManager + +CLIENTS_SQL = """ +CREATE TABLE 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 +); +CREATE TABLE 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) +); +CREATE INDEX idx_usage_ts ON usage_history(timestamp); +""" + +STATS_SQL = "".join(f""" +CREATE TABLE {t} ( + 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) +); +CREATE INDEX idx_{t}_ts ON {t}(timestamp); +""" for t in ["stats_5min", "stats_15min", "stats_hourly", "stats_6h", "stats_daily"]) + +# Oldest schema: APP/db.py at commit c9af0a5 (no active_sessions, users, login_attempts), +# plus a legacy users table without the 2FA columns (the case _ensure_column was written for; +# no commit holds that table definition, it is reconstructed from the migration step) +OLDEST_SQL = CLIENTS_SQL + STATS_SQL + """ +CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +""" + +# Baseline: APP_CORE/db.py at commit 3836049 (identical to the schema today) +BASELINE_SQL = CLIENTS_SQL + STATS_SQL + """ +CREATE TABLE 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) +); +CREATE TABLE 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 +); +CREATE TABLE login_attempts ( + ip_address TEXT PRIMARY KEY, + attempts INTEGER DEFAULT 0, + last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +""" + +ROWS_SQL = """ +INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent) + VALUES (1, 'alice', '10.0.0.1:1000', 1000, 2000); +INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent) + VALUES (2, 'bob', '10.0.0.2:2000', 3000, 4000); +INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent) + VALUES (1, '2026-01-01 10:00:00', 10, 20); +INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent) + VALUES (2, '2026-01-01 10:00:10', 30, 40); +INSERT INTO stats_5min (timestamp, client_id, bytes_received, bytes_sent) + VALUES ('2026-01-01 10:00:00', 1, 10, 20); +INSERT INTO users (id, username, password_hash) VALUES (1, 'admin', 'hash'); +""" + +SCHEMAS = {"oldest_c9af0a5": OLDEST_SQL, "baseline_3836049": BASELINE_SQL} +DATA_QUERIES = [ + "SELECT * FROM clients ORDER BY id", + "SELECT * FROM usage_history ORDER BY id", + "SELECT * FROM stats_5min", + "SELECT id, username, password_hash FROM users", +] + + +@pytest.fixture(autouse=True) +def _auto_migrate(monkeypatch): + monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False) + + +def make_db(path, schema_sql, extra_sql=ROWS_SQL): + conn = sqlite3.connect(path) + conn.executescript(schema_sql + extra_sql) + conn.commit() + conn.close() + + +def query(path, sql): + conn = sqlite3.connect(path) + try: + return conn.execute(sql).fetchall() + finally: + conn.close() + + +def table_names(path): + return {r[0] for r in query(path, "SELECT name FROM sqlite_master WHERE type='table'")} + + +def sha(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +@pytest.mark.parametrize("schema", SCHEMAS) +def test_old_schema_is_migrated_without_data_loss(tmp_path, schema): + db = str(tmp_path / "old.db") + make_db(db, SCHEMAS[schema]) + before = [query(db, q) for q in DATA_QUERIES] + + report = migrations.run(db) + + # Original rows intact + assert [query(db, q) for q in DATA_QUERIES] == before + # Missing tables and columns are there, existing rows get the defaults + assert {"active_sessions", "users", "login_attempts"} <= table_names(db) + assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)] + # Stamped, and the backup is the untouched pre-migration copy + assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")] + backups = glob.glob(db + ".bak-*") + assert backups == [report.backup] + assert [query(backups[0], q) for q in DATA_QUERIES] == before + assert "schema_migrations" not in table_names(backups[0]) + assert query(backups[0], "PRAGMA integrity_check") == [("ok",)] + + +def test_second_run_is_a_noop(tmp_path): + db = str(tmp_path / "old.db") + make_db(db, OLDEST_SQL) + migrations.run(db) + first = sha(db) + + report = migrations.run(db) + + assert report.applied == [] and report.backup is None + assert len(glob.glob(db + ".bak-*")) == 1 + assert sha(db) == first + + +def test_too_new_database_is_not_touched(tmp_path, monkeypatch): + db = str(tmp_path / "new.db") + make_db(db, BASELINE_SQL, ROWS_SQL + """ + CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT); + INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z'); + """) + before = sha(db) + + with pytest.raises(migrations.SchemaTooNew): + migrations.run(db) + + # The service itself refuses to start: exit code 1, no traceback + monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", db) + with pytest.raises(SystemExit) as exc: + DatabaseManager(str(tmp_path / "none.ini")).init_database() + assert exc.value.code == 1 + + assert sha(db) == before + assert glob.glob(db + ".bak-*") == [] + assert len(query(db, "SELECT * FROM clients")) == 2 + + +def test_fresh_database_gets_full_schema_without_backup(tmp_path): + db = str(tmp_path / "fresh.db") + + report = migrations.run(db) + + assert report.created and report.backup is None + assert glob.glob(db + ".bak-*") == [] + assert {"clients", "usage_history", "active_sessions", "users", "login_attempts", + "stats_5min", "stats_daily", "schema_migrations"} <= table_names(db) + assert query(db, "SELECT version FROM schema_migrations") == [(1,)] + + +def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch): + db = str(tmp_path / "old.db") + make_db(db, OLDEST_SQL) + before = sha(db) + monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0") + + with pytest.raises(migrations.MigrationPending, match="migrate.py"): + migrations.startup(db) + assert sha(db) == before + + migrations.run(db) + migrations.startup(db) # up to date: allowed + + +def test_simultaneous_start_makes_one_backup(tmp_path): + db = str(tmp_path / "old.db") + make_db(db, OLDEST_SQL) + barrier = threading.Barrier(2) + reports, errors = [], [] + + def start(): + try: + barrier.wait() + reports.append(migrations.run(db)) + except Exception as e: # pragma: no cover + errors.append(e) + + threads = [threading.Thread(target=start) for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert errors == [] + assert len(glob.glob(db + ".bak-*")) == 1 + assert sorted(len(r.applied) for r in reports) == [0, 1] + assert query(db, "SELECT version FROM schema_migrations") == [(1,)] diff --git a/APP_PROFILER/database.py b/APP_PROFILER/database.py index a8d22f1..5331291 100644 --- a/APP_PROFILER/database.py +++ b/APP_PROFILER/database.py @@ -1,4 +1,4 @@ -from sqlalchemy import create_engine, inspect, text +from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker @@ -22,14 +22,3 @@ def get_db(): yield db finally: db.close() - -def ensure_columns(): - """Idempotent 'add column if missing' migration for existing databases. - create_all() creates new tables but never alters existing ones.""" - insp = inspect(engine) - if "user_profiles" not in insp.get_table_names(): - return - existing = {c["name"] for c in insp.get_columns("user_profiles")} - if "note" not in existing: - with engine.begin() as conn: - conn.execute(text("ALTER TABLE user_profiles ADD COLUMN note TEXT")) diff --git a/APP_PROFILER/main.py b/APP_PROFILER/main.py index 352d262..07575bd 100644 --- a/APP_PROFILER/main.py +++ b/APP_PROFILER/main.py @@ -7,17 +7,19 @@ import os import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) -from database import engine, Base, ensure_columns +from database import db_path +import migrations from routers import system, server, profiles, server_process from utils.logging import setup_logging from fastapi.middleware.cors import CORSMiddleware -# Create Database Tables -Base.metadata.create_all(bind=engine) -ensure_columns() - setup_logging() +# Create or upgrade the database schema (versioned migrations, backup before any change). +# Exits with a clear message if the database is newer than this code or migrations are +# pending while OVPMON_AUTO_MIGRATE=0. +migrations.startup_or_exit(db_path) + app = FastAPI( title="OpenVPN Profiler API", description="REST API for managing OpenVPN profiles and configuration", diff --git a/APP_PROFILER/migrate.py b/APP_PROFILER/migrate.py new file mode 100755 index 0000000..eb7b544 --- /dev/null +++ b/APP_PROFILER/migrate.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Apply pending database migrations (or only check for them). + + python migrate.py apply pending migrations (backup first) + python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new + python migrate.py --db PATH use this database file instead of the configured one + +Run it from the component directory with the component's virtualenv, like the service. +The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0). +""" +import argparse +import logging +import sys + +import migrations +from database import db_path as configured_db_path + +EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2 + + +def default_db_path(): + return configured_db_path + + +def main(argv=None): + parser = argparse.ArgumentParser(description="Database schema migrations") + parser.add_argument("--check", action="store_true", + help="only report: exit 0 = up to date, 2 = pending, 1 = error") + parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)") + args = parser.parse_args(argv) + + logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") + db_path = args.db or default_db_path() + + try: + st = migrations.status(db_path) + if st.too_new: + raise migrations._too_new_error(st) + print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)")) + if args.check: + print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})") + if not st.pending: + print("Pending: none, up to date") + return EXIT_OK + print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending)) + return EXIT_PENDING + before = st.current + report = migrations.run(db_path) + except migrations.MigrationError as e: + print(f"ERROR: {e}", file=sys.stderr) + return EXIT_ERROR + + print(f"Schema version: {before} -> {report.version}") + if report.applied: + print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied)) + else: + print("Applied: nothing, already up to date") + print(f"Backup: {report.backup or 'none'}" + + (" (new database)" if report.created else "")) + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/APP_PROFILER/migrations.py b/APP_PROFILER/migrations.py new file mode 100644 index 0000000..e5bf1dc --- /dev/null +++ b/APP_PROFILER/migrations.py @@ -0,0 +1,447 @@ +"""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 ------------------------------------------- + +import json # noqa: E402 + + +def _dialect(): + from sqlalchemy.dialects import sqlite + return sqlite.dialect() + + +def _metadata(): + """Model metadata (imported lazily: models import database, which stays free of this module).""" + import models # noqa: F401 registers the tables + from database import Base + return Base.metadata + + +def _default_clause(column): + """'DEFAULT ' for a scalar Python default, so existing rows get the value. + JSON/list defaults become '[]'. Anything not constant (timestamps) stays NULL.""" + default = column.default + if default is None: + return "" + if getattr(default, "is_scalar", False): + value = default.arg + elif getattr(default, "is_callable", False): + try: + value = default.arg(None) + except Exception: + return "" + else: + return "" + if isinstance(value, bool): + return f" DEFAULT {int(value)}" + if isinstance(value, (int, float)): + return f" DEFAULT {value}" + if isinstance(value, str): + return " DEFAULT '%s'" % value.replace("'", "''") + if isinstance(value, (list, dict)): + return " DEFAULT '%s'" % json.dumps(value) + return "" + + +def _create_table(conn, table): + from sqlalchemy.schema import CreateIndex, CreateTable + dialect = _dialect() + conn.execute(str(CreateTable(table).compile(dialect=dialect))) + for index in table.indexes: + conn.execute(str(CreateIndex(index).compile(dialect=dialect))) + + +def _create_all(conn): + """Same effect as Base.metadata.create_all(), on the migration's own connection.""" + existing = set(_tables(conn)) + for table in _metadata().sorted_tables: + if table.name not in existing: + _create_table(conn, table) + + +def _m001_baseline(conn): + """Bring any database created by an earlier release up to the current models: + create missing tables, add missing columns (type and default from the metadata). + Replaces the standalone scripts add_columns.py and scripts/add_*.py and the old + ensure_columns(). Idempotent.""" + dialect = _dialect() + existing = set(_tables(conn)) + for table in _metadata().sorted_tables: + if table.name not in existing: + logger.info(f"Creating missing table {table.name}") + _create_table(conn, table) + continue + have = {r[1] for r in conn.execute(f"PRAGMA table_info({_quote(table.name)})")} + for column in table.columns: + if column.name in have: + continue + if column.primary_key: + raise MigrationError(f"Cannot add primary key column {table.name}.{column.name}") + ddl = (f"ALTER TABLE {_quote(table.name)} ADD COLUMN {_quote(column.name)} " + f"{column.type.compile(dialect=dialect)}{_default_clause(column)}") + logger.info(f"Adding missing column {column.name} to table {table.name}") + conn.execute(ddl) + + +MIGRATIONS = [ + Migration(1, "baseline", _m001_baseline), +] + + +# A brand-new database gets the complete current schema at once (create_all equivalent) +FRESH_SCHEMA = _create_all diff --git a/APP_PROFILER/test_migrations.py b/APP_PROFILER/test_migrations.py new file mode 100644 index 0000000..502debf --- /dev/null +++ b/APP_PROFILER/test_migrations.py @@ -0,0 +1,199 @@ +import glob +import hashlib +import os +import sqlite3 +import tempfile + +import pytest + +# The DB path must be set before database.py is imported (the migration reads the models) +_tmp = tempfile.TemporaryDirectory() +os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db") + +import migrations + +PKI_SQL = """ +CREATE TABLE pki_settings ( + id INTEGER NOT NULL, fqdn_ca VARCHAR, fqdn_server VARCHAR, easyrsa_dn VARCHAR, + easyrsa_req_country VARCHAR, easyrsa_req_province VARCHAR, easyrsa_req_city VARCHAR, + easyrsa_req_org VARCHAR, easyrsa_req_email VARCHAR, easyrsa_req_ou VARCHAR, + easyrsa_key_size INTEGER, easyrsa_ca_expire INTEGER, easyrsa_cert_expire INTEGER, + easyrsa_cert_renew INTEGER, easyrsa_crl_days INTEGER, easyrsa_batch BOOLEAN, + PRIMARY KEY (id) +); +CREATE INDEX ix_pki_settings_id ON pki_settings (id); +""" + +SYSTEM_COLUMNS = """ + id INTEGER NOT NULL, protocol VARCHAR, port INTEGER, vpn_network VARCHAR, + vpn_netmask VARCHAR, tunnel_type VARCHAR, split_routes JSON, duplicate_cn BOOLEAN, + crl_verify BOOLEAN, client_to_client BOOLEAN, user_defined_dns BOOLEAN, dns_servers JSON, + user_defined_cdscripts BOOLEAN, connect_script VARCHAR, disconnect_script VARCHAR, + management_interface BOOLEAN, management_interface_address VARCHAR, management_port INTEGER +""" + +# Oldest schema: reconstructed from what the standalone scripts (add_columns.py, +# scripts/add_*.py) had to add later. Git history has no older models.py than fcb8f6b. +ANCIENT_SQL = PKI_SQL + f""" +CREATE TABLE system_settings ({SYSTEM_COLUMNS}, PRIMARY KEY (id)); +CREATE INDEX ix_system_settings_id ON system_settings (id); +CREATE TABLE user_profiles ( + id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME, + revoked_at DATETIME, file_path VARCHAR, PRIMARY KEY (id) +); +CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username); +CREATE INDEX ix_user_profiles_id ON user_profiles (id); +""" + +# Baseline: models.py at commit 3836049 (everything except user_profiles.note) +BASELINE_SQL = PKI_SQL + f""" +CREATE TABLE system_settings ( + {SYSTEM_COLUMNS}, public_ip VARCHAR, tun_mtu INTEGER, mssfix INTEGER, PRIMARY KEY (id) +); +CREATE INDEX ix_system_settings_id ON system_settings (id); +CREATE TABLE user_profiles ( + id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME, + revoked_at DATETIME, expiration_date DATETIME, is_revoked BOOLEAN, is_expired BOOLEAN, + file_path VARCHAR, PRIMARY KEY (id) +); +CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username); +CREATE INDEX ix_user_profiles_id ON user_profiles (id); +""" + +ROWS_SQL = """ +INSERT INTO pki_settings (id, fqdn_ca, easyrsa_key_size) VALUES (1, 'my-ca', 4096); +INSERT INTO system_settings (id, protocol, port, tunnel_type) VALUES (1, 'tcp', 443, 'SPLIT'); +INSERT INTO user_profiles (id, username, status, created_at, file_path) + VALUES (1, 'alice', 'active', '2026-01-01 10:00:00', '/p/alice.ovpn'); +INSERT INTO user_profiles (id, username, status, created_at, file_path) + VALUES (2, 'bob', 'revoked', '2026-01-02 10:00:00', '/p/bob.ovpn'); +""" + +SCHEMAS = {"ancient": ANCIENT_SQL, "baseline_3836049": BASELINE_SQL} + + +@pytest.fixture(autouse=True) +def _auto_migrate(monkeypatch): + monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False) + + +def make_db(path, schema_sql, extra_sql=ROWS_SQL): + conn = sqlite3.connect(path) + conn.executescript(schema_sql + extra_sql) + conn.commit() + conn.close() + + +def query(path, sql): + conn = sqlite3.connect(path) + try: + return conn.execute(sql).fetchall() + finally: + conn.close() + + +def columns(path, table): + return [r[1] for r in query(path, f"PRAGMA table_info({table})")] + + +def sha(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +@pytest.mark.parametrize("schema", SCHEMAS) +def test_old_schema_is_migrated_without_data_loss(tmp_path, schema): + db = str(tmp_path / "old.db") + make_db(db, SCHEMAS[schema]) + users_before = query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles") + + report = migrations.run(db) + + # Original rows intact + assert query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before + assert query(db, "SELECT fqdn_ca, easyrsa_key_size FROM pki_settings") == [("my-ca", 4096)] + assert query(db, "SELECT protocol, port, tunnel_type FROM system_settings") == [("tcp", 443, "SPLIT")] + # New columns exist; existing rows get the defaults + assert {"note", "is_revoked", "is_expired", "expiration_date"} <= set(columns(db, "user_profiles")) + assert {"public_ip", "tun_mtu", "mssfix"} <= set(columns(db, "system_settings")) + # Columns added now get the default; columns that already existed keep their values + flags = (0, 0) if schema == "ancient" else (None, None) + assert query(db, "SELECT is_revoked, is_expired, expiration_date, note FROM user_profiles") == [ + flags + (None, None), flags + (None, None)] + assert query(db, "SELECT public_ip, tun_mtu, mssfix FROM system_settings") == [(None, None, None)] + # Stamped, and the backup is the untouched pre-migration copy + assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")] + backups = glob.glob(db + ".bak-*") + assert backups == [report.backup] + assert query(backups[0], "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before + assert "note" not in columns(backups[0], "user_profiles") + assert query(backups[0], "PRAGMA integrity_check") == [("ok",)] + + +def test_second_run_is_a_noop(tmp_path): + db = str(tmp_path / "old.db") + make_db(db, BASELINE_SQL) + migrations.run(db) + first = sha(db) + + report = migrations.run(db) + + assert report.applied == [] and report.backup is None + assert len(glob.glob(db + ".bak-*")) == 1 + assert sha(db) == first + + +def test_too_new_database_is_not_touched(tmp_path): + db = str(tmp_path / "new.db") + make_db(db, BASELINE_SQL, ROWS_SQL + """ + CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT); + INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z'); + """) + before = sha(db) + + with pytest.raises(migrations.SchemaTooNew): + migrations.run(db) + with pytest.raises(migrations.SchemaTooNew): + migrations.startup(db) + + assert sha(db) == before + assert glob.glob(db + ".bak-*") == [] + assert len(query(db, "SELECT * FROM user_profiles")) == 2 + + +def test_fresh_database_gets_full_schema_without_backup(tmp_path): + db = str(tmp_path / "fresh.db") + + report = migrations.run(db) + + assert report.created and report.backup is None + assert glob.glob(db + ".bak-*") == [] + assert {"note", "is_revoked"} <= set(columns(db, "user_profiles")) + assert {"public_ip", "mssfix"} <= set(columns(db, "system_settings")) + assert "ix_user_profiles_username" in [r[1] for r in query(db, "PRAGMA index_list(user_profiles)")] + assert query(db, "SELECT version FROM schema_migrations") == [(1,)] + + +def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch): + db = str(tmp_path / "old.db") + make_db(db, BASELINE_SQL) + before = sha(db) + monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0") + + with pytest.raises(migrations.MigrationPending, match="migrate.py"): + migrations.startup(db) + assert sha(db) == before + + migrations.run(db) + migrations.startup(db) # up to date: allowed + + +def test_default_clause_from_model_defaults(): + import models + t = models.SystemSettings.__table__.c + assert migrations._default_clause(t.split_routes) == " DEFAULT '[]'" + assert migrations._default_clause(t.duplicate_cn) == " DEFAULT 0" + assert migrations._default_clause(t.port) == " DEFAULT 1194" + assert migrations._default_clause(t.protocol) == " DEFAULT 'udp'" + assert migrations._default_clause(t.tun_mtu) == "" + assert migrations._default_clause(models.UserProfile.__table__.c.created_at) == "" diff --git a/DOCS/Changes/2026-10-05_DB_Migrations.md b/DOCS/Changes/2026-10-05_DB_Migrations.md new file mode 100644 index 0000000..07e8632 --- /dev/null +++ b/DOCS/Changes/2026-10-05_DB_Migrations.md @@ -0,0 +1,43 @@ +# Database migrations, phase 1 (2026-10-05) + +Goal: a database from an older version survives an update without data loss. Phase 1 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md); the container and system-service scenarios follow as separate phases. Reference: [Database migrations](../General/Database_Migrations.md). + +## Problem found + +The Profiler added only the `note` column automatically; `public_ip`, `tun_mtu`, `mssfix`, `is_revoked`, `is_expired`, `expiration_date` were added by manual scripts, so an older database broke after an update. The monitoring database had no schema version, no backup and no integrity check. + +## Changes + +| Area | Change | +|---|---| +| `APP_PROFILER/migrations.py`, `APP_CORE/migrations.py` | Same engine in both components: table `schema_migrations`, ordered additive migrations, one write lock for all processes, integrity check, consistent backup (SQLite backup API, newest 5 kept), per-migration savepoint, verification (integrity and row counts against the backup) before the commit, downgrade protection | +| Profiler baseline migration | Generated from the SQLAlchemy models: creates missing tables and adds every missing column (with defaults for existing rows); replaces `ensure_columns()` and the manual scripts | +| Monitoring baseline migration | The former `init_database()` SQL, behaviour unchanged | +| `migrate.py` (both components) | Standalone phase: `migrate.py` applies, `--check` reports (exit 0 up to date, 2 pending, 1 error or database too new), `--db PATH` | +| Service start | Pending migrations are applied automatically after the backup. `OVPMON_AUTO_MIGRATE=0`: the service only checks and refuses to start while migrations are pending. A database newer than the code: the service refuses to start and does not touch it | +| Tests | `test_migrations.py` in each component (oldest reconstructed schema and baseline schema `3836049`; data intact, backup, stamp, no-op rerun, too-new database, race of two processes in the monitoring component) | +| Fix during review | The backup was taken through the connection that holds the write lock and hung; it now reads through a separate read-only connection (the data is not modified at that point, so the copy is consistent) | + +## Verification (containers) + +| Check | Result | +|---|---| +| pytest: migrations (Profiler 7, monitoring 7) and the three earlier Profiler tests | all passed | +| Databases created and filled by the real old code (commit `3836049`), then `migrate.py --check` | exit 2, pending baseline (both) | +| `migrate.py` | version 0 → 1, backup created, backups open, rows intact (profiles, settings, clients, usage, users) | +| Second run | `up to date`, no new backup, `--check` exit 0 | +| New Profiler on the migrated database | `GET /api/profiles` returns the old profiles | +| Database marked version 9999 | `migrate.py` exit 1 and the service refuses to start, file untouched | +| Live stand: restart of Profiler, API and gatherer on databases without a version | one backup per database, schema version 1, race between API and gatherer handled, data intact (profile kept) | + +## Notes + +- Behaviour change: the monitoring component used to swallow schema errors and keep starting; now a migration or integrity problem stops the start. +- Migrations only add; nothing is dropped or rewritten. Existing columns keep their values (for example `NULL` flags in old rows). +- Oldest schemas in the tests are partly reconstructed (git has no `models.py` before `fcb8f6b`). +- The service user needs write access to the database directory for the backup files. +- The old standalone scripts (`add_columns.py`, `scripts/add_*.py`) are superseded and left in place. + +## Existing installations + +Nothing to do: the first start of the new version backs up and migrates each database. For a controlled update run `migrate.py --check` and `migrate.py` from the component directory with the service stopped (the update scripts of the next phases do this as a separate step). diff --git a/DOCS/Changes/2026-10-05_Deployment_Scenarios_PLAN.md b/DOCS/Changes/2026-10-05_Deployment_Scenarios_PLAN.md new file mode 100644 index 0000000..3339f1e --- /dev/null +++ b/DOCS/Changes/2026-10-05_Deployment_Scenarios_PLAN.md @@ -0,0 +1,77 @@ +# Deployment scenarios and safe upgrade: plan (2026-10-05) + +Goal: two documented, scripted scenarios. +- **Scenario 1, containers:** A) all components in one container; B) one container per component. +- **Scenario 2, system services, install and update:** A) Alpine, B) Debian, C) Ubuntu. + +Priority: **an update must not damage the databases; a database must survive the migration** that a new version needs. + +(The request lists "variant A" three times for scenario 2; this plan reads them as A, B, C.) + +## What exists today +- Containers: `docker-compose.yml` (four services, variant B) and `DOCS/General/Deployment_Docker.md`. No single-container variant. +- System services: manual guide `Deployment_Native.md` (tested on Alpine only), systemd units, OpenRC scripts, privilege-separation helper with `doas`. No install or update script. +- Database migration is incomplete: + - Profiler: `create_all` plus `ensure_columns()` for the single column `note`. The other columns that models have (`public_ip`, `tun_mtu`, `mssfix`, `is_revoked`, `is_expired`, `expiration_date`, ...) are added only by standalone manual scripts in `APP_PROFILER/scripts` and `add_columns.py`. **A database from an older version breaks after an update unless someone runs them.** + - Monitoring (`APP_CORE/db.py`): `CREATE TABLE IF NOT EXISTS` plus `_ensure_column`. No schema version, no backup, no integrity check. +- Found blockers for Debian/Ubuntu: + 1. `ovpmon-helper` calls `/sbin/rc-service openvpn` only; `process.py` uses `systemctl openvpn` for non-Alpine, but on Debian/Ubuntu the real unit is `openvpn-server@server` and the config is expected in `/etc/openvpn/server/`. + 2. `doas` is not installed by default (`opendoas` package; Ubuntu and Debian have it, version differs). + 3. The UI build needs Node 20.19+ (Vite 7); Debian 12 and Ubuntu 22.04 ship older Node. + 4. Nginx paths and Python versions differ (`/etc/nginx/http.d` on Alpine, `conf.d` or `sites-available` on Debian/Ubuntu). + +## Steps + +### 1. Database migration (foundation, done first) +- One migration mechanism for both databases: table `schema_migrations(version, applied_at)`, ordered idempotent migrations in code (`APP_PROFILER/migrations.py`, `APP_CORE/migrations.py`), applied in a transaction at startup and by the CLI `migrate` used in the update script. +- Migration 1 for the Profiler adds every column that the current models need and a pre-versioned database lacks (generated from the models, not hand-written); `note` moves into it. Migration for `APP_CORE` stamps the baseline after checking the existing schema. +- Safety rules: + - Before any migration: `PRAGMA integrity_check`, then a consistent backup through the SQLite backup API (`.bak-`), kept. + - The migration never drops or rewrites data; only `ADD COLUMN` and `CREATE ... IF NOT EXISTS`, with defaults. + - A database **newer** than the application is not touched: the service refuses to start with a clear message (downgrade protection). + - After the migration: integrity check and row counts compared with the backup; on failure the backup is restored automatically by the update script. +- One `VERSION` file is written on install and update and logged on start. +- Test: one pytest builds a database with the **old** schema (taken from the baseline commit `3836049`), puts data into it, migrates, checks that the data is intact, the columns exist and a second run changes nothing. + +### 2. Scenario 1: containers +- **B (distributed):** existing `docker-compose.yml`, hardened: named volumes kept on update, `.env` template, health checks, documented `docker compose pull/build && up -d`; the migration runs at the start of the Profiler and the API; pre-update volume backup command (`docker run ... tar`). +- **A (one container):** new `deploy/allinone/Dockerfile` and `docker-compose.allinone.yml`: Alpine, `supervisord` (or OpenRC-free supervisor) running nginx, gunicorn, gatherer, uvicorn and OpenVPN; same environment variables, one data volume (databases, PKI, client config, `/etc/openvpn`), ports 80 and 1194/udp. +- Script `deploy/docker/install.sh` and `update.sh` (idempotent: generates the secret, asks for the admin once, creates the backup, rebuilds, waits for health, prints the result). +- Document: `DOCS/Deployment/Scenario1_Containers.md` (A and B, install, update, backup and restore, rollback). + +### 3. Scenario 2: system services (Alpine, Debian, Ubuntu) +- `deploy/native/install.sh` and `update.sh` with an OS adapter (detects Alpine / Debian / Ubuntu; package names, service manager, nginx paths, doas package): + - install: packages, `ovpmon` user, directories, venvs, environment file (random secret), services (OpenRC or systemd), root helper and doas rules, Nginx with a self-signed certificate, firewall hints; + - update: preflight (free space, version, services state) → backup (databases through the backup API, `/etc/ovpmon`, PKI, client config, `server.conf`, code version) → stop → new code → dependencies → **database migration** → UI → start → health check → on failure automatic rollback (code and databases) with a log. +- Debian/Ubuntu support in the code: `ovpmon-helper` and `process.py` choose the service manager (OpenRC `openvpn`, systemd `openvpn-server@server`) and the config location; the helper rules are checked on both. +- UI build: the script builds `dist` in a Node 20 container (or uses a prebuilt archive) so that the host does not need a recent Node. +- Document: `DOCS/Deployment/Scenario2_System_Services.md` with one section per OS, the update procedure, backup, rollback and a "what is preserved" table. + +### 4. Verification (containers, no real host is touched) +- Scenario 1: build and start A and B, log in, initialize PKI, create a client; then **update from the old version** (baseline `3836049` data volume) to the new one and check that data and PKI survive. +- Scenario 2: run `install.sh` and then `update.sh` inside Alpine 3.23, Debian 12 and Ubuntu 24.04 containers with an init system (OpenRC / systemd); seed an old database and PKI before the update; check migration, health check and rollback (forced failure). +- Limit to state in the report: a container is not a full host (no real firewall, `tun` and service-manager details can differ); a final run on a VM of each OS is recommended before production. + +### 5. Documentation +- The two scenario documents, links from `README.md`, `DOCS/General/Index.md`; the old `Deployment_Docker.md` and `Deployment_Native.md` become short pointers to the new documents; summary `DOCS/Changes/2026-10-05_Deployment_Scenarios.md`. + +## Decisions for the owner +1. **Form:** scripts (`install.sh`, `update.sh`) plus documents (recommended), or documents only. +2. **Order of work:** database migration first, then Scenario 1, then Scenario 2 (recommended), or all in one step. +3. **Debian/Ubuntu service manager:** use `openvpn-server@server` and `/etc/openvpn/server/server.conf` (the distribution convention, recommended) instead of the Alpine-style `openvpn.conf`. +4. **UI build:** in a Node 20 container (recommended) or require Node 20+ on the host. + +## Out of scope +High availability, PostgreSQL instead of SQLite, automatic OS package upgrades, Windows hosts, a real-host run (needs a VM). + +## Decisions of the owner (2026-10-05) +1. Scripts `install.sh` and `update.sh` plus documents. +2. **The database migration phase is separated from the component update.** Phase 1 (this stage): migration mechanism, standalone `migrate` command, backup, checks, tests; it also runs by itself at service start. Phase 2: scenario 1 (containers). Phase 3: scenario 2 (system services). The update scripts call the migration as its own, separate step before the components are replaced or restarted. +3. Debian and Ubuntu: `openvpn-server@server` and `/etc/openvpn/server/server.conf`. +4. The UI is built in a Node 20 container. + +## Phase 1 details (migration) +- Each component has its own build context and virtualenv, so the small migration helper is a separate copy in `APP_PROFILER/` and `APP_CORE/` (same behaviour). +- Service start applies pending migrations automatically (after the backup); `OVPMON_AUTO_MIGRATE=0` makes the service only check and refuse to start while migrations are pending (used by the update scripts). The standalone command: `migrate.py [--check]` in each component, exit codes 0 / 2 (pending) / 1 (error). +- Old standalone scripts (`add_columns.py`, `scripts/add_*.py`) stay in place and are marked as superseded in the documentation. +- Tests: one file per component, with the oldest and the baseline (`3836049`) schemas embedded as SQL. diff --git a/DOCS/General/Database_Migrations.md b/DOCS/General/Database_Migrations.md new file mode 100644 index 0000000..fa1c5d7 --- /dev/null +++ b/DOCS/General/Database_Migrations.md @@ -0,0 +1,103 @@ +# Database Migrations + +Both SQLite databases are upgraded by one mechanism: versioned, additive-only migrations with an automatic backup. A database from an older release is brought up to date at service start (or by `migrate.py`); a database is never dropped, rewritten or downgraded. + +| Component | Database (default) | Module | Standalone command | Started by | +|---|---|---|---|---| +| `APP_PROFILER` | `ovpn_profiler.db` (`OVPMON_PROFILER_DB_PATH`) | `migrations.py` | `migrate.py` | `main.py` at import | +| `APP_CORE` | `openvpn_monitor.db` (`OVPMON_OPENVPN_MONITOR_DB_PATH`) | `migrations.py` | `migrate.py` | API and gatherer (`DatabaseManager.init_database`) | + +The two components have separate build contexts and virtualenvs, so `migrations.py` is a separate copy in each (the generic part is identical). Keep them in sync when changing it. + +## How it works + +The table `schema_migrations(version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)` records the applied migrations. The migrations are an ordered list in code (`MIGRATIONS`). A run does this: + +1. Reads the state without a lock. Nothing pending: done, no write, no backup. +2. Takes a write lock (`BEGIN IMMEDIATE`, wait up to 60 s) and re-reads the state. This is what makes the API and the gatherer safe to start at the same time: the second process waits, then finds nothing pending and makes no second backup. +3. Refuses if the database is newer than the code (see Downgrade protection). +4. `PRAGMA integrity_check`. If it fails, nothing is changed. +5. If the database already holds tables: a consistent backup with the SQLite backup API to `.bak-` (same file permissions as the database), before anything is touched. A brand-new database gets no backup. +6. Applies each pending migration in its own savepoint. If one fails, it is rolled back, the run stops, the backup stays, and the service does not start (clear error naming the migration and the backup). Migrations that were completed before it are kept. +7. Before the commit: `PRAGMA integrity_check` and a comparison of the row count of every pre-existing table with the backup. On a mismatch everything is rolled back and the error names the backup file. +8. After a successful run that made a backup, only the newest 5 `.bak-*` files of this database are kept; older ones are deleted. + +Migrations only add (`CREATE TABLE IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN`, `CREATE INDEX IF NOT EXISTS`). They never drop or rewrite data. + +## Startup behaviour + +| Setting | Behaviour at service start | +|---|---| +| default (`OVPMON_AUTO_MIGRATE` unset or `1`) | Pending migrations are applied automatically, after the backup. | +| `OVPMON_AUTO_MIGRATE=0` | The service only checks. While migrations are pending it refuses to start (log and stderr message "run 'python migrate.py' first", exit code 1). Used by update scripts that run `migrate.py` as a separate step. | + +Whenever the database cannot be used (too new, pending with auto-migrate off, failed migration, failed integrity check) the service logs a critical message, prints `FATAL: ...` to stderr and exits with code 1. There is no traceback. Note: the previous `init_database()` of `APP_CORE` only logged schema errors and went on; now a schema problem stops the start. + +The service user needs write access to the database directory (backups are created next to the database). + +## Standalone command: `migrate.py` + +Run it from the component directory, with the component's virtualenv and the same environment as the service (it uses the same configuration to find the database). No extra dependencies. + +```sh +cd APP_PROFILER # or APP_CORE +python migrate.py # apply pending migrations (backup first) +python migrate.py --check # only report, change nothing +python migrate.py --db /path/to/other.db # override the configured database file +``` + +| Exit code | Meaning | +|---|---| +| 0 | Done / up to date | +| 2 | `--check` only: migrations are pending | +| 1 | Error, or the database is newer than the code | + +Output: database path, schema version (before -> after), applied migrations, backup path. Run it as the user that owns the database files, so new backups keep the right owner. + +## Backups and restore + +Backups are `.bak-` (UTC) next to the database, for example `ovpn_profiler.db.bak-20261005T101500`. They are made only when migrations are pending and the database is not new. To restore: + +```sh +# 1. stop the services that use this database +# 2. keep the current file for analysis, then put the backup back +mv ovpn_profiler.db ovpn_profiler.db.broken +cp ovpn_profiler.db.bak-20261005T101500 ovpn_profiler.db +# 3. start the services of the OLD release (the backup has the old schema) +``` + +The backup is a normal SQLite file and holds the same secrets as the database (password hashes, 2FA secrets); it has the same permissions. Restoring a backup to run the new release again is fine: the pending migrations are applied again at start. + +## Downgrade protection + +If `schema_migrations` holds a version higher than the code knows (the database was migrated by a newer release and then an older release was started), the database is not touched and the service does not start. The message tells to install the newer release or to restore a matching backup. `migrate.py --check` exits with 1 in this case. + +## Adding a migration + +In the component's `migrations.py`: + +1. Write a function `_m002_(conn)`. It gets the `sqlite3` connection inside a transaction: do not commit, do not open another connection. Only additive statements, idempotent (`IF NOT EXISTS`, check `PRAGMA table_info` before `ADD COLUMN`). +2. Append `Migration(2, "", _m002_)` to `MIGRATIONS`. Versions are consecutive and are never changed or removed after release. +3. `APP_PROFILER`: a brand-new database is created from the models (`FRESH_SCHEMA`, the `create_all` equivalent) and all migrations are recorded without running them, so the models must already contain the change. Migrations 2+ only serve existing databases. +4. `APP_CORE`: there is no separate fresh schema; migration 1 plus the following ones run on a new database. Keep migration 1 unchanged and do the new work in the new migration. +5. Add a case to `test_migrations.py` (an old schema in, rows kept, new column present). + +## Pre-versioned databases + +A database from a release before this mechanism has the tables but no `schema_migrations`. It is treated as "nothing applied": the backup is made, migration 1 (baseline) runs and the result is recorded. + +- `APP_PROFILER` migration 1 is generated from the SQLAlchemy models: tables that are missing are created, every missing model column is added with `ALTER TABLE ... ADD COLUMN`. The type comes from the column type; a scalar default becomes `DEFAULT ` (so existing rows get it: Boolean `0`/`1`, numbers, strings), a JSON/list default becomes `'[]'`; other columns stay `NULL`. It covers all columns that the old scripts added (`is_revoked`, `is_expired`, `expiration_date` in `user_profiles`; `public_ip`, `tun_mtu`, `mssfix` in `system_settings`) and `note`. Existing indexes and constraints of existing tables are not touched. +- `APP_CORE` migration 1 is the former `init_database()`: `CREATE TABLE IF NOT EXISTS` for all tables and indexes, and the missing `users.totp_secret` and `users.is_2fa_enabled` columns. + +## Superseded scripts + +`APP_PROFILER/add_columns.py`, `APP_PROFILER/scripts/add_public_ip_column.py` and `APP_PROFILER/scripts/add_mtu_mss_columns.py` are superseded by migration 1 and must not be needed any more; they stay in place unchanged for reference. `ensure_columns()` in `APP_PROFILER/database.py` was removed. + +## Tests + +One pytest file per component builds an old database from an embedded SQL schema (the oldest reconstructable one and the baseline of commit `3836049`), runs the migration and checks data, new columns, the backup, the stamp, the no-op second run and the downgrade protection. + +```sh +cd APP_PROFILER && python -m pytest test_migrations.py +cd APP_CORE && python -m pytest test_migrations.py # pip install -r requirements-dev.txt first +``` diff --git a/DOCS/General/Index.md b/DOCS/General/Index.md index eb168e2..2b0c499 100644 --- a/DOCS/General/Index.md +++ b/DOCS/General/Index.md @@ -23,6 +23,7 @@ Welcome to the documentation for the OpenVPN Monitor suite. - [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md) - [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md) - [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md) +- [Database migrations (2026-10-05)](../Changes/2026-10-05_DB_Migrations.md) · [reference](Database_Migrations.md) ## 🔍 Core Monitoring (`APP_CORE`) The core module responsible for log parsing, real-time statistics, and the primary API. diff --git a/README.md b/README.md index 3a06694..e8db8b8 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US | 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](DOCS/Changes/2026-10-04_Async_PKI_Init.md) | | 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](DOCS/Changes/2026-10-04_Toast_Notifications.md) | | 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md) | +| 2026-10-05 | Database migrations with backup, integrity checks and downgrade protection; standalone `migrate.py` (phase 1 of install/update scenarios) | [Database migrations](DOCS/Changes/2026-10-05_DB_Migrations.md) | ## Notes