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:
1 parent
56dae90ff5
commit
e556d6d4b9
15 files changed
+1729
-127
No files matched your search
@@ -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).
|
||||
@@ -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 <action> 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 (`<db>.bak-<timestamp>`), 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.
|
||||
@@ -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
|
||||
```
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user