"""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