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

+103
View File
@@ -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 `<db>.bak-<UTC YYYYmmddTHHMMSS>` (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 `<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.
```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 `<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:
```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_<what>(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, "<what>", _m002_<what>)` 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 <literal>` (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
```