- 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>
8.0 KiB
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:
- Reads the state without a lock. Nothing pending: done, no write, no backup.
- 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. - Refuses if the database is newer than the code (see Downgrade protection).
PRAGMA integrity_check. If it fails, nothing is changed.- If the database already holds tables: a consistent backup with the SQLite backup API to
<db>.bak-<UTC YYYYmmddTHHMMSS>(same file permissions as the database), before anything is touched. A brand-new database gets no backup. - 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.
- Before the commit:
PRAGMA integrity_checkand 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. - After a successful run that made a backup, only the newest 5
<db>.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.
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 <db>.bak-<YYYYmmddTHHMMSS> (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:
# 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:
- Write a function
_m002_<what>(conn). It gets thesqlite3connection inside a transaction: do not commit, do not open another connection. Only additive statements, idempotent (IF NOT EXISTS, checkPRAGMA table_infobeforeADD COLUMN). - Append
Migration(2, "<what>", _m002_<what>)toMIGRATIONS. Versions are consecutive and are never changed or removed after release. APP_PROFILER: a brand-new database is created from the models (FRESH_SCHEMA, thecreate_allequivalent) and all migrations are recorded without running them, so the models must already contain the change. Migrations 2+ only serve existing databases.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.- 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_PROFILERmigration 1 is generated from the SQLAlchemy models: tables that are missing are created, every missing model column is added withALTER TABLE ... ADD COLUMN. The type comes from the column type; a scalar default becomesDEFAULT <literal>(so existing rows get it: Boolean0/1, numbers, strings), a JSON/list default becomes'[]'; other columns stayNULL. It covers all columns that the old scripts added (is_revoked,is_expired,expiration_dateinuser_profiles;public_ip,tun_mtu,mssfixinsystem_settings) andnote. Existing indexes and constraints of existing tables are not touched.APP_COREmigration 1 is the formerinit_database():CREATE TABLE IF NOT EXISTSfor all tables and indexes, and the missingusers.totp_secretandusers.is_2fa_enabledcolumns.
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.
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