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 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 08:37:38 +03:00
1 parent 56dae90ff5
commit e556d6d4b9
15 files changed
+1729 -127

No files matched your search

+7 -110
View File
@@ -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)
+64
View File
@@ -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())
+467
View File
@@ -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
('<db>.bak-<UTC timestamp>'), 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 '<db>.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
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pytest
+246
View File
@@ -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,)]