From 1c49d0b9c248597d88ee8bd3993b230a8f2e369c Mon Sep 17 00:00:00 2001 From: ayurishchev Date: Mon, 5 Oct 2026 09:24:55 +0300 Subject: [PATCH] Scenario 1: container install and update (all-in-one and per-component) - Variant B: docker-compose.yml gets configurable host ports and health checks. Variant A: deploy/allinone image (nginx, supervisord, gunicorn, uvicorn, gatherer, OpenVPN) with an explicit database migration step before any service; docker-compose.allinone.yml. Same five volumes and paths in both variants. - deploy/docker: install.sh, update.sh (backup, build, stop, separate DB migration phase, start, automatic rollback), backup.sh, restore.sh, lib.sh. - Verified on Docker: install A/B, update with pre-versioned databases, rollback after an injected failure, backup/restore. - Docs: Scenario1_Containers guide, change summary, README, Index; .dockerignore, .gitignore additions. Co-Authored-By: Claude Sonnet 5.5 --- .dockerignore | 36 + .gitignore | 4 + .../2026-10-05_Scenario1_Containers.md | 42 ++ DOCS/Deployment/Scenario1_Containers.md | 261 ++++++++ DOCS/General/Deployment_Docker.md | 51 +- DOCS/General/Index.md | 1 + README.md | 3 +- deploy/allinone/Dockerfile | 70 ++ deploy/allinone/entrypoint.sh | 92 +++ deploy/allinone/supervisord.conf | 86 +++ deploy/docker/backup.sh | 89 +++ deploy/docker/install.sh | 190 ++++++ deploy/docker/lib.sh | 616 ++++++++++++++++++ deploy/docker/restore.sh | 80 +++ deploy/docker/update.sh | 261 ++++++++ docker-compose.allinone.yml | 64 ++ docker-compose.yml | 34 +- 17 files changed, 1930 insertions(+), 50 deletions(-) create mode 100644 .dockerignore create mode 100644 DOCS/Changes/2026-10-05_Scenario1_Containers.md create mode 100644 DOCS/Deployment/Scenario1_Containers.md create mode 100644 deploy/allinone/Dockerfile create mode 100755 deploy/allinone/entrypoint.sh create mode 100644 deploy/allinone/supervisord.conf create mode 100755 deploy/docker/backup.sh create mode 100755 deploy/docker/install.sh create mode 100644 deploy/docker/lib.sh create mode 100755 deploy/docker/restore.sh create mode 100755 deploy/docker/update.sh create mode 100644 docker-compose.allinone.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b684cae --- /dev/null +++ b/.dockerignore @@ -0,0 +1,36 @@ +# Build context of the all-in-one image (deploy/allinone/Dockerfile) is the repository root. +# The per-component images (docker-compose.yml) use ./APP_UI, ./APP_CORE, ./APP_PROFILER as +# their own contexts, so this file does not affect them. + +# VCS, local environments, secrets +.git +.gitignore +.claude +.env +**/.env +venv +**/venv +**/.venv + +# Runtime data and local state: never part of an image +*.db +**/*.db +**/*.db.bak-* +**/easy-rsa +**/client-config +**/staging +backups +.ovpmon-* +**/*.log + +# Build artefacts and caches +**/node_modules +**/dist +**/__pycache__ +**/*.pyc +**/.pytest_cache + +# Documentation and the compose files are not needed inside the image +DOCS +README.md +docker-compose*.yml diff --git a/.gitignore b/.gitignore index e43b0f9..3f3c949 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ .DS_Store +.env +backups/ +.ovpmon-deploy +.ovpmon-lock/ diff --git a/DOCS/Changes/2026-10-05_Scenario1_Containers.md b/DOCS/Changes/2026-10-05_Scenario1_Containers.md new file mode 100644 index 0000000..dd161fd --- /dev/null +++ b/DOCS/Changes/2026-10-05_Scenario1_Containers.md @@ -0,0 +1,42 @@ +# Scenario 1: containers, variants A and B (2026-10-05) + +Phase 2 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 1: containers](../Deployment/Scenario1_Containers.md). + +## What was added + +| Area | Content | +|---|---| +| Variant B (one container per component) | The existing `docker-compose.yml`, extended: host ports `OVPMON_HTTP_PORT` / `OVPMON_VPN_PORT` (defaults 80 and 1194), health checks for all four services. Nothing else changed | +| Variant A (all in one container) | `deploy/allinone/` (`Dockerfile`: UI built in a Node 20 stage; Alpine, nginx, supervisord, gunicorn, uvicorn, gatherer, OpenVPN), `entrypoint.sh` (TUN, easy-rsa workspace, NAT without duplicates, nginx config, **explicit database migration before any service**), `supervisord.conf`, `docker-compose.allinone.yml` | +| Same data layout | Both variants use the same five named volumes with the same in-container paths: backups are identical and a volume set can be used by either variant (one variant per host: same ports and container names) | +| `deploy/docker/install.sh` | `--variant a|b`, preflight, `.env` with a random secret (mode 600), generated administrator password shown once, build, start, health wait, removal of the admin seed from `.env` once a user exists | +| `deploy/docker/update.sh` | Phases: preflight, **backup of all volumes** (verified), source update, build (old stack keeps running, current images tagged `:previous`), stop, **database migration as its own step** (`migrate.py --check` / apply / check, abort before start on failure), start with health wait, **automatic rollback** (volumes restored from this run's backup, `:previous` images started); `--rollback` for a manual rollback; last 5 backups kept | +| `backup.sh`, `restore.sh`, `lib.sh` | Stand-alone backup (cron friendly) and restore with confirmation; shared functions | +| Housekeeping | root `.dockerignore`; `.gitignore` gets `.env`, `backups/`, deploy state files | +| Docs | `DOCS/Deployment/Scenario1_Containers.md`; `DOCS/General/Deployment_Docker.md` is now a pointer | + +## Verification (real Docker on this host) + +| Check | Result | +|---|---| +| `install.sh --variant b` on a clean host state | built, healthy, administrator seed removed, password shown once | +| Variant B: PKI init, server config, client, note | all `200`; stack healthy | +| `update.sh` variant B on databases without a version (version table and `note` column removed from real data) | backup, migration phase applied the baseline to both databases with their own backups, start healthy, profile and PKI intact | +| `update.sh` variant B with a broken new Profiler image (injected syntax error) | build ok, migration ok, start unhealthy, **automatic rollback**: volumes restored, previous images started, healthy, data intact | +| `install.sh --variant a` | built and healthy; UI and both APIs through nginx; PKI init, server config, client, note; **OpenVPN started inside the container** (process running) | +| `update.sh` variant A on databases without a version | explicit migration phase, healthy, data intact | +| `backup.sh`, then a change, then `restore.sh` | archives verified; after the restore the later change is gone and the data is as at backup time | +| Cleanup | test projects, volumes, images and files removed; the 8089 stand was restarted on its own volumes, data intact | + +## Notes and limits + +- OpenVPN is not started automatically after a container is recreated (update, rollback): start it from the UI. This was already so; an automatic start when `server.conf` exists is a worthwhile follow-up. +- Variant A runs everything as root in one container (as the Profiler container in B); the blast radius is wider than in B. +- After a rollback the stack runs from the `:previous` images through a generated override; the next `update.sh` run rebuilds and returns to the normal compose file. +- Not tested: `docker-compose` v1, switching a volume set between A and B, adoption of a hand-started B stack by `update.sh`. +- Two backups started in the same UTC second collide (the second refuses). +- A container is not a production host: run the procedure once on the target host before relying on it. + +## Existing installations + +A stack started by hand (`docker-compose up`) can be adopted: `update.sh --variant b` records its state on the first run. Data stays in the named volumes. diff --git a/DOCS/Deployment/Scenario1_Containers.md b/DOCS/Deployment/Scenario1_Containers.md new file mode 100644 index 0000000..4bb892e --- /dev/null +++ b/DOCS/Deployment/Scenario1_Containers.md @@ -0,0 +1,261 @@ +# Scenario 1: installation in containers + +Two variants, both installed and updated by the scripts in `deploy/docker/`: + +| | Variant A: one container | Variant B: one container per component | +|---|---|---| +| Compose file | `docker-compose.allinone.yml` | `docker-compose.yml` | +| Containers | `ovp-allinone` (nginx, gunicorn, gatherer, uvicorn, OpenVPN under `supervisord`) | `ovp-ui`, `ovp-api`, `ovp-gatherer`, `ovp-profiler` | +| Image build | `deploy/allinone/Dockerfile` (build context: repository root) | one Dockerfile per component (`APP_UI`, `APP_CORE`, `APP_PROFILER`) | +| Choose it when | one host, simplest operation, one thing to start/stop/back up | you want to restart, scale or inspect components separately, or follow the usual one-process-per-container practice | +| Trade-off | a failing process is restarted by `supervisord`, the container stays up; one image to rebuild for any change | more moving parts, internal network `ovp-net` | + +Both variants use the **same five named volumes with the same in-container paths**, the same environment variables and the same published ports. Backups look identical. + +> **Only one variant can run per host.** Both publish the same host ports (`80/tcp`, `1194/udp` by default) and use fixed container names (`ovp-*`). The scripts refuse to start a variant while a container of the other one is running. + +## Requirements + +- Docker Engine with the compose plugin (`docker compose`, v2, preferred) or `docker-compose`. +- The Docker daemon running and usable by the user that runs the scripts (root, or a member of the `docker` group). +- Access to `/dev/net/tun` on the host and the `NET_ADMIN` capability (already set in the compose files). +- Free disk space: about 2 GB for images and builds, plus room for backups (the scripts check both). +- Internet access for the first build (base images, npm, pip) and for the backup helper image (`alpine:3`). For offline hosts see *Troubleshooting*. +- `openssl` is optional (random secret otherwise comes from `/dev/urandom`). + +## Install + +Clone the repository, change into it and run the script (as root or a docker user): + +```bash +# Variant B: one container per component +deploy/docker/install.sh --variant b + +# Variant A: everything in one container +deploy/docker/install.sh --variant a + +# Options +deploy/docker/install.sh --variant b --project ovpmon --http-port 8080 --vpn-port 1194 --admin-user admin +``` + +| Option | Meaning | +|---|---| +| `--variant a\|b` | required | +| `--project NAME` | compose project name = prefix of the volume names (default `ovpmon`: volumes `ovpmon_db_data`, ...) | +| `--http-port N` | host port of the UI (written to `.env` as `OVPMON_HTTP_PORT`, default 80) | +| `--vpn-port N` | host UDP port of OpenVPN (`OVPMON_VPN_PORT`, default 1194) | +| `--admin-user NAME` | login of the first administrator (default `admin`) | + +What `install.sh` does: + +1. **Preflight:** docker and compose, running daemon, the other variant is not running, no foreign container with the same names, ports free, free disk space. +2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it). +3. **Build, start** (`docker compose up -d`), write the state file `.ovpmon-deploy` (variant and project; used by `update.sh`, `backup.sh`, `restore.sh`), wait up to 3 minutes for the health checks. +4. **Initial administrator:** when the users table is not empty, `OVPMON_INITIAL_ADMIN_*` are removed from `.env` and the container that reads them is recreated (variant B: `app-api`, variant A: `ovpmon`). If the table cannot be read or is empty, the lines stay in `.env` and a warning says so. +5. **Result:** URL, ports, and the administrator login and password. **The password is shown once** and stored nowhere else. `JWT_SECRET` is never printed. + +Running it again is safe: it rebuilds and starts, keeps `.env`, and makes no new administrator. + +Then in the UI: sign in, **PKI Configuration → Initialize PKI**, generate the server configuration and start the VPN server. Put TLS in front of the UI (see *Security*). + +### Without the script + +```bash +cat > .env < +EOT +chmod 600 .env +docker compose up -d --build # variant B +docker compose -f docker-compose.allinone.yml up -d --build # variant A +``` + +After the first start remove the two `OVPMON_INITIAL_ADMIN_*` lines from `.env` and recreate `app-api` (B) or `ovpmon` (A). + +## `.env` reference + +| Variable | Required | Default | Meaning | +|---|---|---|---| +| `JWT_SECRET` | yes | none (compose refuses to start) | Signing key of both APIs (`OVPMON_API_SECRET_KEY`). Changing it logs every user out. Keep the same value across updates | +| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | first start only | empty | Seed for the first user, used only while the users table is empty. Removed by `install.sh` afterwards | +| `OVPMON_CORS_ORIGINS` | no | empty (off) | Comma-separated extra origins; the UI is same-origin behind nginx | +| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI | +| `OVPMON_VPN_PORT` | no | `1194` | Host UDP port of OpenVPN (the container side is always 1194) | + +Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_DIR` (backup root, default `./backups`), `OVPMON_BACKUP_IMAGE` (helper image, default `alpine:3`), `OVPMON_HEALTH_TIMEOUT` (seconds, default 180), `OVPMON_MIN_FREE_MB` (docker data, default 2048), `OVPMON_MIN_FREE_BACKUP_MB` (backups, default 1024). + +`OVPMON_VPN_PORT` changes only the host side of the mapping. If you change the OpenVPN port in the server settings of the UI, the client profiles carry that port; keep the two consistent. + +## Ports + +| Port | Published | Purpose | +|---|---|---| +| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP) | +| `${OVPMON_VPN_PORT:-1194}/udp` | yes | OpenVPN | +| `5001` (monitoring API), `8000` (profiler API) | no | variant B: `expose`d on `ovp-net` only; variant A: listen on `127.0.0.1` inside the container | + +## Volumes: what is stored where + +| Volume | Path in the container | Content | Mounted by (B) | +|---|---|---|---| +| `ovp_logs` | `/var/log/openvpn` | `openvpn-status.log` and OpenVPN logs | gatherer, profiler | +| `ovp_config` | `/etc/openvpn` | `server.conf` generated by the profiler | profiler | +| `ovp_pki` | `/app/easy-rsa` | easy-rsa scripts and `pki/` (CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem`) | profiler | +| `ovp_client_config` | `/app/client-config` | generated client `.ovpn` files | profiler | +| `db_data` | `/app/db` | `ovpn_profiler.db`, `openvpn_monitor.db`, migration backups `*.db.bak-*` | gatherer, api, profiler | + +Not stored in volumes (lost when the container is recreated): the container file system, `profiler.log` and `openvpn_gatherer.log` (written into the working directory), supervisor state. Application logs go to `docker logs`. + +Volume names are `_`; the scripts find them by the compose labels, so any project name works. + +### Layout of variant A + +The code is in `/app/APP_CORE` and `/app/APP_PROFILER`; the volumes are mounted at the same paths as in variant B (`/app/db`, `/app/easy-rsa`, `/app/client-config`, `/etc/openvpn`, `/var/log/openvpn`). + +The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`services/pki.py`, `routers/profiles.py`), and stores `client-config/.ovpn` as a relative path in its database. In variant B that directory is `/app`. Variant A keeps it that way: **`supervisord` starts the profiler with working directory `/app`** (`uvicorn --app-dir /app/APP_PROFILER main:app`), so `/app/easy-rsa` and `/app/client-config` are the volumes. No symlinks are used, and the database paths are identical in both variants (so a volume set can be used by either variant). The monitoring API and the gatherer run with working directory `/app/APP_CORE`, where `config.ini` lives; their database path comes from `OVPMON_OPENVPN_MONITOR_DB_PATH=/app/db/openvpn_monitor.db`. + +Processes in `ovp-allinone` (`deploy/allinone/supervisord.conf`, started in this order, all with `autorestart`, logs to stdout/stderr): `gatherer`, `api` (`gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app`), `profiler` (`uvicorn` on `127.0.0.1:8000`, no reload), `nginx`. OpenVPN is started by the profiler API on request (direct start inside containers), as in variant B. + +`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1`, then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema). + +## Update + +```bash +deploy/docker/update.sh # variant and project from .ovpmon-deploy +deploy/docker/update.sh --yes # no questions +deploy/docker/update.sh --no-pull # sources already in place / offline (no git pull, no base image refresh) +deploy/docker/update.sh --rollback # manual rollback to the newest backup +``` + +Each phase is logged separately: + +| Phase | What happens | If it fails | +|---|---|---| +| 0 Preflight | state file, `.env`, compose configuration, running stack, the other variant not running, `db_data` volume exists, free space | nothing was changed | +| 1 **Backup** | all five volumes → `backups//*.tar.gz` through a throwaway `alpine` container (volumes mounted read-only), copy of `.env` (mode 600), record of the current image IDs, `SHA256SUMS`; every archive is verified (`tar -tzf`) | the update is **refused**, nothing was changed | +| 2 Sources | `git pull --ff-only` when the directory is a git checkout and `--no-pull` was not given | nothing was changed | +| 3 Build | current images are tagged `:previous`, then the new images are built while the old stack keeps running | nothing was changed, the old version still runs | +| 4 Stop | the application containers are stopped (volumes are kept); a second, final backup of the volumes is taken now that nothing writes to the databases | automatic rollback | +| 5 **Database migration** | a separate step, see below | automatic rollback, nothing is started | +| 6 Start | `up -d` with the new images, wait for the health checks | automatic rollback | + +Old backups: the newest 5 are kept; older ones are pruned only after a successful update. Volumes are never deleted and `down -v` is never used. The new `deploy/docker/*.sh` take effect on the next run (the running script is not replaced). + +### Database migration as its own step + +After the containers are stopped and before any new component starts, `update.sh` runs, for each database, a one-off container **from the new image with the same volumes**: + +| Variant | Profiler database | Monitoring database | +|---|---|---| +| B | `app-profiler` image: `cd /app && python migrate.py` | `app-api` image: `cd /app && python migrate.py` | +| A | `ovpmon` image: `cd /app/APP_PROFILER && python migrate.py` | `ovpmon` image: `cd /app/APP_CORE && python migrate.py` | + +For each database it runs `python migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), applies the pending migrations with `python migrate.py` and checks again. The reports are printed. A failure or a "too new" database aborts **before anything is started** and triggers the rollback. + +What the migration does (details: [Database migrations](../General/Database_Migrations.md)): versioned, additive-only changes (`CREATE ... IF NOT EXISTS`, `ADD COLUMN` with defaults), never a drop or rewrite; before any change an integrity check and a consistent copy `.bak-` next to the database (newest 5 kept); after the change an integrity check and a comparison of row counts; on a mismatch everything is rolled back; a database newer than the application is not touched. + +The migration also runs by itself when a service starts (variant B: profiler and API; variant A: the entrypoint, before `supervisord`), so a plain `docker compose up -d --build` is safe too. `update.sh` only makes it a visible, separate, controlled step. + +### Automatic rollback + +On any failure in phases 4 to 6: the stack is stopped, all five volumes are restored from the backup of this run, the `:previous` images are started (through a generated `compose.previous.yml` in the backup directory) and the result is reported with the backup path. If the rollback itself fails, the message says where the backup is and how to retry (`update.sh --rollback`, or `restore.sh`). + +After a rollback the stack runs on the `:previous` images; the next `update.sh` run builds again and recreates the containers on the new images. + +## Backup, restore, rollback + +### Backup + +```bash +deploy/docker/backup.sh # live backup of the five volumes -> backups// +deploy/docker/backup.sh --stop # stops the containers during the copy (consistent SQLite files), starts them again +deploy/docker/backup.sh --keep 14 # afterwards keep the newest 14 +``` + +Cron example (nightly, consistent, 14 kept): `30 3 * * * /opt/ovpmon/deploy/docker/backup.sh --stop --keep 14 >> /var/log/ovpmon-backup.log 2>&1`. + +A live backup copies the PKI and configuration reliably; a database file that is written at that very moment may be caught half-way, which `--stop` avoids (and `update.sh` always backs up a stopped stack for its final snapshot). The backup holds private keys, password hashes and the secret: the directory is mode 700, the files mode 600. Store copies off the host and protect them. + +Manual equivalent for one volume (project `ovpmon`): + +```bash +mkdir -p backups/manual +docker run --rm -v ovpmon_db_data:/data:ro -v "$PWD/backups/manual":/backup alpine \ + tar -czf /backup/db_data.tar.gz -C /data . +``` + +### Restore + +```bash +deploy/docker/restore.sh backups/20261005T101500Z # asks, stops the stack, restores, prints the start command +deploy/docker/restore.sh backups/20261005T101500Z --yes --start +``` + +It verifies the archives first, saves the current content to `backups/-pre-restore`, empties each volume and fills it from the archive. Volumes are not removed. `.env` is not touched (a difference to the copy in the backup is reported). Manual equivalent: + +```bash +docker compose stop # or: -f docker-compose.allinone.yml +docker run --rm -v ovpmon_db_data:/data -v "$PWD/backups/20261005T101500Z":/backup:ro alpine \ + sh -c 'rm -rf /data/* /data/.[!.]* /data/..?* && tar -xzf /backup/db_data.tar.gz -C /data' +docker compose up -d +``` + +A single database can also be put back from its migration backup in `db_data`: stop the stack, copy `.bak-` over the database file, start the OLD release (see [Database migrations](../General/Database_Migrations.md)). + +### Rollback to the previous version + +```bash +deploy/docker/update.sh --rollback +``` + +After confirmation: stop, restore all volumes from the newest complete backup (current content saved first), start the images recorded in that backup. Use it when an update completed but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy). + +## Switching between variants + +Both variants use the same volumes, so with the same project name the data can be used by the other variant: stop the running one (`docker compose [-f docker-compose.allinone.yml] stop`), take a backup, run `install.sh --variant --project `. This path has not been tested in a real run; keep the backup. Starting both at once is refused. + +## Troubleshooting + +| Symptom | Cause and action | +|---|---| +| `port 80/tcp is already in use` | Another service uses the port. Install with `--http-port 8080` or set `OVPMON_HTTP_PORT` in `.env` (same for `OVPMON_VPN_PORT`) | +| `container 'ovp-...' of the OTHER variant is running` | Variants A and B cannot run together. Stop the other stack first | +| `container 'ovp-ui' ... belongs to compose project 'x'` | A stack of another project uses the fixed names. Use `--project x` or remove that stack | +| Health check does not turn healthy | `docker compose ps`, then `docker compose logs --tail 100 ` (A: `docker logs ovp-allinone`). The scripts print the last log lines of failing services. The profiler allows 40 s and the all-in-one container 60 s before failures count | +| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources, or restore a matching backup (`update.sh --rollback` or `restore.sh`) | +| Migration failed | Nothing was started and the volumes are restored by the automatic rollback. The report names the migration; the database copy `.bak-*` is in `db_data`. Send the report with the problem | +| `JWT_SECRET must be set in .env` | `.env` missing or empty value; run `install.sh` or add `JWT_SECRET=$(openssl rand -hex 32)` | +| `permission denied` on docker | Run as root or add the user to the `docker` group. Backups belong to the user that runs the scripts | +| Permission errors on bind mounts on SELinux hosts | Backup and restore bind-mount `backups/` into a container; label the directory for containers (`chcon -Rt container_file_t backups`) | +| Cannot pull `alpine:3` (offline) | Make an image with `sh`, `tar` and `sha256sum` available locally and set `OVPMON_BACKUP_IMAGE`; use `--no-pull` with `update.sh` | +| `/dev/net/tun` missing | Load the module on the host (`modprobe tun`); the compose files map the device | +| VPN does not start after an update | The containers were recreated and the profiler starts OpenVPN only on request: start the server in the UI. Check that the server configuration exists (`ovp_config` volume) | +| The UI answers 502 right after start | The APIs are still starting; wait for the health checks | + +## Security + +- Put **TLS in front** of the UI (reverse proxy or a certificate in nginx): the container serves plain HTTP. See [Nginx configuration](../General/Nginx_Configuration.md). +- `.env` holds the signing secret: mode 600, owned by the operator, never committed (`.gitignore` lists it). The scripts never print `JWT_SECRET`; the generated administrator password is shown once and removed from `.env` after the first start. +- Backups contain the PKI (CA and server private keys), the databases (password hashes, 2FA secrets) and a copy of `.env`: keep them mode 700/600 and store off-host copies encrypted. +- The profiler container is privileged for networking (`NET_ADMIN`, TUN). Variant A runs everything in that one container; its APIs listen on `127.0.0.1` only, so only nginx (80) and OpenVPN (1194/udp) are reachable. +- No secrets in logs: the scripts only log names and paths; the services log the source of the secret, not its value. + +## What is preserved on update + +| Item | On update | +|---|---| +| Databases (`db_data`) | Kept. Backed up twice (before and after the stop), migrated additively with their own `.bak-*` copy; restored automatically if the update fails after the stop | +| PKI (`ovp_pki`): CA, keys, certificates, CRL | Kept, backed up. The easy-rsa scripts are copied only when the volume does not have them yet | +| Client profiles (`ovp_client_config`) | Kept, backed up | +| Server configuration (`ovp_config`) | Kept, backed up (the new image does not overwrite it) | +| OpenVPN logs and status file (`ovp_logs`) | Kept | +| `.env` (secret, ports) | Kept, copied into every backup | +| User sessions | Stay valid while `JWT_SECRET` is unchanged | +| Images | Replaced; the previous ones stay tagged `:previous` | +| Containers | Recreated; running VPN sessions are interrupted and clients reconnect; the OpenVPN process has to be started again (see troubleshooting) | +| Container file system, `profiler.log`, `openvpn_gatherer.log` | Not kept (use `docker logs`) | +| Backups in `backups/` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically | +| Volumes | Never deleted by any script; `down -v` is never used | + +Related: [Database migrations](../General/Database_Migrations.md), [Deployment plan](../Changes/2026-10-05_Deployment_Scenarios_PLAN.md). diff --git a/DOCS/General/Deployment_Docker.md b/DOCS/General/Deployment_Docker.md index ad32006..6899c41 100644 --- a/DOCS/General/Deployment_Docker.md +++ b/DOCS/General/Deployment_Docker.md @@ -1,53 +1,10 @@ # Deployment: Docker -Uses `docker-compose.yml` from the repository root. +The container deployment (all components in one container, or one container per component), its install and update scripts, backup and rollback are described in **[Scenario 1: installation in containers](../Deployment/Scenario1_Containers.md)**. -## Services - -| Service | Container | Ports | Notes | -|---|---|---|---| -| `app-ui` | `ovp-ui` | 80 | Nginx + built UI; proxies `/api/` and `/profiles-api/` | -| `app-api` | `ovp-api` | 5001 | Flask monitoring API | -| `app-gatherer` | `ovp-gatherer` | - | Parses `openvpn-status.log` | -| `app-profiler` | `ovp-profiler` | 8000, 1194/udp | FastAPI + OpenVPN; needs `NET_ADMIN` and `/dev/net/tun` | - -Volumes: `ovp_logs`, `ovp_config`, `ovp_pki`, `ovp_client_config`, `db_data`. - -## Steps - -1. Create `.env` next to `docker-compose.yml` (`JWT_SECRET` is mandatory: compose refuses to start without it): - ```bash - cat > .env < - OVPMON_INITIAL_ADMIN_PASSWORD= - EOT - chmod 600 .env - ``` -2. `docker-compose up -d --build` -3. Open `http://`, sign in, **PKI Configuration → Initialize PKI**. -4. Remove `OVPMON_INITIAL_ADMIN_*` from `.env` and run `docker-compose up -d app-api` (the seed is used only while the users table is empty). - -## Compose settings - -| Item | Value | -|---|---| -| Published ports | `80/tcp` (UI) and `1194/udp` (VPN) only; `5001` and `8000` are `expose`d on `ovp-net` and reached through Nginx in `app-ui` | -| Secrets | `JWT_SECRET` (required) → `OVPMON_API_SECRET_KEY` for both APIs | -| Initial admin | `OVPMON_INITIAL_ADMIN_USER` / `OVPMON_INITIAL_ADMIN_PASSWORD` (optional, first start) | -| CORS | `OVPMON_CORS_ORIGINS` (optional, comma-separated; off by default because the UI is same-origin) | -| Restart policy | `unless-stopped` | - -## Hardening - -- Terminate TLS in front of `app-ui` (reverse proxy or a certificate mounted into the UI container); see [Nginx configuration](Nginx_Configuration.md). The container serves plain HTTP on 80. -- `ovp-profiler` is privileged (`NET_ADMIN`, TUN): keep its API off the host network. -- Back up the `db_data` and `ovp_pki` volumes; never commit `.env`. - -## Operations +Quick start (variant B, one container per component, `docker-compose.yml`): ```bash -docker-compose ps -docker-compose logs -f app-api app-profiler -docker-compose up -d --build app-ui # after UI changes +deploy/docker/install.sh --variant b # variant A (one container): --variant a +deploy/docker/update.sh # later updates: backup, build, separate database migration, start ``` diff --git a/DOCS/General/Index.md b/DOCS/General/Index.md index 2b0c499..ff39f48 100644 --- a/DOCS/General/Index.md +++ b/DOCS/General/Index.md @@ -24,6 +24,7 @@ Welcome to the documentation for the OpenVPN Monitor suite. - [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) +- [Scenario 1: containers (2026-10-05)](../Changes/2026-10-05_Scenario1_Containers.md) · [guide](../Deployment/Scenario1_Containers.md) ## 🔍 Core Monitoring (`APP_CORE`) The core module responsible for log parsing, real-time statistics, and the primary API. diff --git a/README.md b/README.md index e8db8b8..c4bb0f8 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Nginx is the only public entry point: `/` UI, `/api/` Monitoring API, `/profiles ## Quick start -- **Containers:** `docker-compose up -d --build`, open `http://`. Details: [Deployment: Docker](DOCS/General/Deployment_Docker.md). +- **Containers:** `deploy/docker/install.sh --variant a|b`, open `http://`. Details: [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) (update, backup, rollback included). - **System services** (systemd / OpenRC, no containers): [Deployment: native](DOCS/General/Deployment_Native.md). After the first start: sign in, open **PKI Configuration** → **Initialize PKI**, generate the server config, start OpenVPN, create profiles. @@ -66,6 +66,7 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US | 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](DOCS/Changes/2026-10-04_Toast_Notifications.md) | | 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md) | | 2026-10-05 | Database migrations with backup, integrity checks and downgrade protection; standalone `migrate.py` (phase 1 of install/update scenarios) | [Database migrations](DOCS/Changes/2026-10-05_DB_Migrations.md) | +| 2026-10-05 | Scenario 1: container install and update, variant A (one container) and B (per component); backup, restore, automatic rollback | [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) · [change](DOCS/Changes/2026-10-05_Scenario1_Containers.md) | ## Notes diff --git a/deploy/allinone/Dockerfile b/deploy/allinone/Dockerfile new file mode 100644 index 0000000..83b696b --- /dev/null +++ b/deploy/allinone/Dockerfile @@ -0,0 +1,70 @@ +# OpenVPN Monitor & Profiler: ALL components in ONE container (scenario 1, variant A) +# +# Build context: the repository root (see docker-compose.allinone.yml): +# docker build -f deploy/allinone/Dockerfile . +# +# Processes (supervisord): nginx (UI + reverse proxy), gunicorn (monitoring API, APP_CORE), +# gatherer (APP_CORE), uvicorn (profiler API, APP_PROFILER). OpenVPN is started by the profiler +# API itself (direct start inside containers, see APP_PROFILER/services/process.py). +# +# Layout: code in /app/APP_CORE and /app/APP_PROFILER; data in the same volume paths as the +# per-component compose file: /app/db, /app/easy-rsa, /app/client-config, /etc/openvpn, +# /var/log/openvpn. The profiler runs with working directory /app, so its relative paths +# (easy-rsa, client-config) resolve to the volumes exactly as in variant B. +# +# Supported ENV: JWT_SECRET or OVPMON_API_SECRET_KEY (required), OVPMON_INITIAL_ADMIN_USER, +# OVPMON_INITIAL_ADMIN_PASSWORD, OVPMON_CORS_ORIGINS, OVPMON_* overrides of the components. + +# Stage 1: build the UI +FROM node:20-alpine AS ui-build +WORKDIR /app +COPY APP_UI/package*.json ./ +RUN npm install +COPY APP_UI/ ./ +RUN npm run build + +# Stage 2: runtime +FROM python:3.12-alpine + +# openvpn/easy-rsa/iptables/iproute2: like APP_PROFILER/Dockerfile (OpenRC is not needed: direct start) +# nginx, supervisor: the process tree; gettext: envsubst for the nginx template +RUN apk add --no-cache openvpn easy-rsa iproute2 iptables bash nginx supervisor gettext \ + && (command -v envsubst >/dev/null || apk add --no-cache gettext-envsubst) \ + && command -v envsubst >/dev/null + +WORKDIR /app + +# Python dependencies of both components (+ gunicorn for the Flask API). Layers are cached +# until a requirements file changes. +COPY APP_CORE/requirements.txt /tmp/requirements-core.txt +COPY APP_PROFILER/requirements.txt /tmp/requirements-profiler.txt +RUN pip install --no-cache-dir -r /tmp/requirements-core.txt -r /tmp/requirements-profiler.txt gunicorn \ + && rm -f /tmp/requirements-*.txt + +COPY APP_CORE /app/APP_CORE +COPY APP_PROFILER /app/APP_PROFILER + +# UI and nginx: the template is rendered at container start (entrypoint.sh) +COPY --from=ui-build /app/dist /usr/share/nginx/html +COPY APP_UI/default.conf.template /etc/ovpmon/default.conf.template +RUN rm -f /etc/nginx/http.d/default.conf \ + && mkdir -p /run/nginx /var/log/nginx \ + && ln -sf /dev/stdout /var/log/nginx/access.log \ + && ln -sf /dev/stderr /var/log/nginx/error.log + +COPY deploy/allinone/supervisord.conf /etc/supervisord.conf +COPY deploy/allinone/entrypoint.sh /usr/local/bin/ovpmon-entrypoint.sh + +# Mount points of the five named volumes +RUN chmod +x /usr/local/bin/ovpmon-entrypoint.sh \ + && mkdir -p /app/db /app/easy-rsa /app/client-config /etc/openvpn /var/log/openvpn + +# Default database locations (the compose file sets the same values) +ENV OVPMON_PROFILER_DB_PATH=/app/db/ovpn_profiler.db \ + OVPMON_OPENVPN_MONITOR_DB_PATH=/app/db/openvpn_monitor.db \ + OVPMON_OPENVPN_MONITOR_LOG_PATH=/var/log/openvpn/openvpn-status.log + +EXPOSE 80 +EXPOSE 1194/udp + +ENTRYPOINT ["/usr/local/bin/ovpmon-entrypoint.sh"] diff --git a/deploy/allinone/entrypoint.sh b/deploy/allinone/entrypoint.sh new file mode 100755 index 0000000..0348988 --- /dev/null +++ b/deploy/allinone/entrypoint.sh @@ -0,0 +1,92 @@ +#!/bin/sh +# Entrypoint of the all-in-one container (variant A). +# +# Order: environment -> TUN device -> workspace (easy-rsa) -> NAT -> nginx config -> +# DATABASE MIGRATION (explicit step, container does not start on failure) -> supervisord. +# +# Re-running (container restart) is safe: every step is idempotent. +set -eu + +log() { echo "[ovpmon] $*"; } +warn() { echo "[ovpmon] WARNING: $*" >&2; } +die() { echo "[ovpmon] FATAL: $*" >&2; exit 1; } + +# --- 1. Secret ---------------------------------------------------------------------------- +# Both APIs read OVPMON_API_SECRET_KEY; JWT_SECRET is accepted as an alias (same name as in .env). +if [ -z "${OVPMON_API_SECRET_KEY:-}" ] && [ -n "${JWT_SECRET:-}" ]; then + OVPMON_API_SECRET_KEY="$JWT_SECRET" +fi +[ -n "${OVPMON_API_SECRET_KEY:-}" ] || die "JWT_SECRET (or OVPMON_API_SECRET_KEY) is not set. Generate one: openssl rand -hex 32" +export OVPMON_API_SECRET_KEY + +# Database locations (same defaults as in the image and in docker-compose.allinone.yml) +export OVPMON_PROFILER_DB_PATH="${OVPMON_PROFILER_DB_PATH:-/app/db/ovpn_profiler.db}" +export OVPMON_OPENVPN_MONITOR_DB_PATH="${OVPMON_OPENVPN_MONITOR_DB_PATH:-/app/db/openvpn_monitor.db}" + +# --- 2. TUN device ------------------------------------------------------------------------ +if [ ! -c /dev/net/tun ]; then + log "Creating /dev/net/tun" + mkdir -p /dev/net + mknod /dev/net/tun c 10 200 || warn "cannot create /dev/net/tun (add devices: /dev/net/tun to the container)" + chmod 600 /dev/net/tun 2>/dev/null || true +fi + +# IP forwarding is set by the container runtime (sysctls: net.ipv4.ip_forward=1 in compose) + +mkdir -p /run /run/nginx /app/db /app/client-config /etc/openvpn /var/log/openvpn + +# --- 3. Easy-RSA workspace ---------------------------------------------------------------- +# /app/easy-rsa is the PKI volume; the profiler (working directory /app) uses /app/easy-rsa/pki. +# Copy the easy-rsa scripts only if the volume does not have them yet (never touches pki/). +if [ ! -f /app/easy-rsa/easyrsa ]; then + log "Initializing Easy-RSA workspace in /app/easy-rsa" + mkdir -p /app/easy-rsa + cp -r /usr/share/easy-rsa/* /app/easy-rsa/ +fi + +# --- 4. NAT and MSS clamping (as in APP_PROFILER/entrypoint.sh, without duplicates) -------- +# The rules live in the container's network namespace and survive a plain container restart, +# so each rule is added only if it is not there yet (-C checks for it). +NAT_IFACE="${OVPMON_NAT_IFACE:-eth0}" +ensure_rule() { + table="$1"; shift + if iptables -t "$table" -C "$@" 2>/dev/null; then + return 0 + fi + iptables -t "$table" -A "$@" || warn "iptables rule not added: -t $table $* (NET_ADMIN missing? VPN traffic will not be routed)" +} +ensure_rule nat POSTROUTING -o "$NAT_IFACE" -j MASQUERADE +ensure_rule mangle FORWARD -o "$NAT_IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu +ensure_rule mangle FORWARD -i "$NAT_IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu + +# --- 5. Nginx configuration --------------------------------------------------------------- +# The same template as the UI image of variant B; all upstreams are local. Only the four +# OVP_* variables are substituted, nginx's own $variables stay intact. +export OVP_API_HOST=127.0.0.1 OVP_API_PORT=5001 +export OVP_PROFILER_HOST=127.0.0.1 OVP_PROFILER_PORT=8000 +envsubst '${OVP_API_HOST} ${OVP_API_PORT} ${OVP_PROFILER_HOST} ${OVP_PROFILER_PORT}' \ + < /etc/ovpmon/default.conf.template > /etc/nginx/http.d/ovpmon.conf +nginx -t || die "generated nginx configuration is invalid (see above)" + +# --- 6. Database migration (explicit step, before any service starts) ---------------------- +# Same command as the update scripts run. Pending migrations are applied after a consistent +# backup (.bak- next to the database). A database that is newer than this +# image, or a failed migration, stops the container here: nothing is started on a bad database. +# See DOCS/General/Database_Migrations.md +run_migration() { + name="$1"; dir="$2" + log "Database migration: $name" + if ! ( cd "$dir" && python migrate.py ); then + die "database migration of $name failed (see the report above). Nothing was started. Restore the volumes from the last backup or use the previous image; see DOCS/Deployment/Scenario1_Containers.md" + fi +} +run_migration "profiler" /app/APP_PROFILER +run_migration "monitoring" /app/APP_CORE + +# The migration has been done: the services only verify the schema and never migrate on their own +# (two gunicorn workers and the gatherer must not race for it). +export OVPMON_AUTO_MIGRATE=0 + +# --- 7. Services -------------------------------------------------------------------------- +log "Starting services (supervisord)" +exec supervisord -n -c /etc/supervisord.conf diff --git a/deploy/allinone/supervisord.conf b/deploy/allinone/supervisord.conf new file mode 100644 index 0000000..7a1746d --- /dev/null +++ b/deploy/allinone/supervisord.conf @@ -0,0 +1,86 @@ +; Process tree of the all-in-one container (variant A). PID 1 is supervisord (started by +; entrypoint.sh after the explicit database migration step). All logs go to the container's +; stdout/stderr (docker logs). Environment variables of the container are inherited by the programs. + +[supervisord] +nodaemon=true +user=root +logfile=/dev/null +logfile_maxbytes=0 +pidfile=/run/supervisord.pid +loglevel=info + +[unix_http_server] +file=/run/supervisor.sock + +[rpcinterface:supervisor] +supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface + +[supervisorctl] +serverurl=unix:///run/supervisor.sock + +; Start order (priority, lower first): gatherer, then the two APIs, nginx last. +; The explicit migration already ran in entrypoint.sh; the programs only check the schema +; (OVPMON_AUTO_MIGRATE=0 is exported there). + +[program:gatherer] +command=python openvpn_gatherer_v3.py +directory=/app/APP_CORE +priority=10 +autostart=true +autorestart=true +startsecs=5 +startretries=5 +stopsignal=TERM +stopwaitsecs=10 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 + +[program:api] +; Flask monitoring API; "app" is the module-level Flask object of openvpn_api_v3.py +command=gunicorn -w 2 -b 127.0.0.1:5001 --access-logfile - --error-logfile - openvpn_api_v3:app +directory=/app/APP_CORE +priority=20 +autostart=true +autorestart=true +startsecs=5 +startretries=5 +stopsignal=TERM +stopwaitsecs=15 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 + +[program:profiler] +; Working directory /app on purpose: the profiler resolves easy-rsa/ and client-config/ relative +; to it, and in this layout /app/easy-rsa and /app/client-config are the volumes (as in variant B). +command=uvicorn --app-dir /app/APP_PROFILER main:app --host 127.0.0.1 --port 8000 +directory=/app +priority=20 +autostart=true +autorestart=true +startsecs=5 +startretries=5 +stopsignal=TERM +stopwaitsecs=15 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 + +[program:nginx] +command=nginx -g "daemon off;" +priority=30 +autostart=true +autorestart=true +startsecs=3 +startretries=5 +stopsignal=QUIT +stopwaitsecs=10 +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 diff --git a/deploy/docker/backup.sh b/deploy/docker/backup.sh new file mode 100755 index 0000000..0e1e935 --- /dev/null +++ b/deploy/docker/backup.sh @@ -0,0 +1,89 @@ +#!/bin/sh +# Back up the five data volumes of the running stack (usable from cron). +# +# deploy/docker/backup.sh [--variant a|b] [--project NAME] [--stop] [--keep N] +# +# --stop stop the application containers during the backup and start them again afterwards: +# a perfectly consistent copy of the SQLite databases (without it the copy is taken +# while the services run: fine for the PKI and configuration, a database write that +# happens to run at that moment may be caught half-way; update.sh always backs up a +# stopped stack) +# --keep N afterwards keep only the newest N backups (default: keep all) +# +# Result: backups// with .tar.gz, SHA256SUMS, .env (mode 600), MANIFEST and the +# recorded image IDs. The directory can be set with OVPMON_BACKUP_DIR. Exit code 0 only if the +# backup was written and verified. Restore: deploy/docker/restore.sh +# See DOCS/Deployment/Scenario1_Containers.md +set -eu + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +. "$SCRIPT_DIR/lib.sh" + +usage() { + sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//' +} + +ARG_VARIANT="" +ARG_PROJECT="" +STOP=0 +KEEP="" +STOPPED=0 + +cleanup() { + _rc=$? + set +e + if [ "$STOPPED" = 1 ]; then + log "starting the stack again" + dc start >/dev/null 2>&1 || warn "could not start the stack again: run '$DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") start'" + STOPPED=0 + fi + release_lock + exit "$_rc" +} + +while [ $# -gt 0 ]; do + case "$1" in + --variant) [ $# -ge 2 ] || die "--variant needs a value"; ARG_VARIANT="$2"; shift 2 ;; + --project) [ $# -ge 2 ] || die "--project needs a value"; ARG_PROJECT="$2"; shift 2 ;; + --stop) STOP=1; shift ;; + --keep) [ $# -ge 2 ] || die "--keep needs a value"; KEEP="$2"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "unknown option: $1" ;; + esac +done +case "$KEEP" in + ""|[1-9]|[1-9][0-9]*) ;; + *) die "--keep must be a positive number" ;; +esac + +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +need_docker +resolve_stack +acquire_lock + +log "backup of variant $VARIANT, project $PROJECT" +[ -n "$(volume_name db_data)" ] || die "volume db_data of project '$PROJECT' not found: wrong --project?" +mkdir -p "$BACKUP_ROOT" +chmod 700 "$BACKUP_ROOT" 2>/dev/null || true +check_free "$BACKUP_ROOT" "$MIN_FREE_BACKUP_MB" "the backup" + +BACKUP_DIR="$BACKUP_ROOT/$(backup_stamp)" +[ ! -e "$BACKUP_DIR" ] || die "backup directory already exists: $BACKUP_DIR (retry in a second)" +mkdir -p "$BACKUP_DIR" +chmod 700 "$BACKUP_DIR" + +if [ "$STOP" = 1 ] && stack_running; then + log "stopping the application containers for a consistent copy" + dc stop + STOPPED=1 +fi + +record_images "$BACKUP_DIR" +make_backup "$BACKUP_DIR" backup || die "the BACKUP FAILED (incomplete files in $BACKUP_DIR are never used by restore or rollback)" + +if [ -n "$KEEP" ]; then + prune_backups "$KEEP" +fi +log "backup complete and verified: $BACKUP_DIR" diff --git a/deploy/docker/install.sh b/deploy/docker/install.sh new file mode 100755 index 0000000..74af190 --- /dev/null +++ b/deploy/docker/install.sh @@ -0,0 +1,190 @@ +#!/bin/sh +# Install OpenVPN Monitor & Profiler in containers. +# +# deploy/docker/install.sh --variant a|b [--project NAME] [--http-port N] [--vpn-port N] [--admin-user NAME] +# +# --variant a all components in ONE container (docker-compose.allinone.yml) +# --variant b one container per component (docker-compose.yml) +# --project compose project name = prefix of the volumes (default: ovpmon) +# --http-port host port of the web UI (default 80), stored in .env as OVPMON_HTTP_PORT +# --vpn-port host UDP port of OpenVPN (default 1194), stored in .env as OVPMON_VPN_PORT +# --admin-user login of the initial administrator (default: admin) +# +# Safe to run again: .env is created only if it does not exist, an existing stack is only rebuilt +# and started. Variants A and B cannot run on the same host together (same ports and names). +# See DOCS/Deployment/Scenario1_Containers.md +set -eu + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +. "$SCRIPT_DIR/lib.sh" + +usage() { + sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//' +} + +ARG_VARIANT="" +ARG_PROJECT="" +ARG_HTTP_PORT="" +ARG_VPN_PORT="" +ADMIN_USER="admin" + +while [ $# -gt 0 ]; do + case "$1" in + --variant) [ $# -ge 2 ] || die "--variant needs a value"; ARG_VARIANT="$2"; shift 2 ;; + --project) [ $# -ge 2 ] || die "--project needs a value"; ARG_PROJECT="$2"; shift 2 ;; + --http-port) [ $# -ge 2 ] || die "--http-port needs a value"; ARG_HTTP_PORT="$2"; shift 2 ;; + --vpn-port) [ $# -ge 2 ] || die "--vpn-port needs a value"; ARG_VPN_PORT="$2"; shift 2 ;; + --admin-user) [ $# -ge 2 ] || die "--admin-user needs a value"; ADMIN_USER="$2"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "unknown option: $1" ;; + esac +done + +[ -n "$ARG_VARIANT" ] || { usage >&2; die "--variant a|b is required"; } +set_variant "$ARG_VARIANT" +PROJECT="${ARG_PROJECT:-$(state_get OVPMON_PROJECT)}" +PROJECT="${PROJECT:-$DEFAULT_PROJECT}" +valid_project "$PROJECT" || die "invalid project name '$PROJECT' (lowercase letters, digits, - and _)" +[ -z "$ARG_HTTP_PORT" ] || valid_port "$ARG_HTTP_PORT" || die "invalid --http-port '$ARG_HTTP_PORT'" +[ -z "$ARG_VPN_PORT" ] || valid_port "$ARG_VPN_PORT" || die "invalid --vpn-port '$ARG_VPN_PORT'" +case "$ADMIN_USER" in + ""|*[!A-Za-z0-9._-]*) die "invalid --admin-user (letters, digits, . _ - only)" ;; +esac + +acquire_lock +trap release_lock EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +# --------------------------------------------------------------------------------------------- +phase 0 "preflight" +need_docker +log "docker compose command: $DC_BIN; variant $VARIANT; project $PROJECT" +check_other_variant_stopped +check_name_clash + +HTTP_PORT="${ARG_HTTP_PORT:-$(env_get OVPMON_HTTP_PORT)}"; HTTP_PORT="${HTTP_PORT:-80}" +VPN_PORT="${ARG_VPN_PORT:-$(env_get OVPMON_VPN_PORT)}"; VPN_PORT="${VPN_PORT:-1194}" +valid_port "$HTTP_PORT" || die "invalid OVPMON_HTTP_PORT '$HTTP_PORT' in .env" +valid_port "$VPN_PORT" || die "invalid OVPMON_VPN_PORT '$VPN_PORT' in .env" + +if stack_running; then + log "the stack of this variant is already running: ports are held by it, port check skipped" +else + check_port "$HTTP_PORT" tcp "UI (HTTP)" + check_port "$VPN_PORT" udp "OpenVPN" +fi +check_free "$(docker_root_dir)" "$MIN_FREE_DOCKER_MB" "images (docker data root)" +check_free "$ROOT_DIR" 256 "the installation directory" + +# --------------------------------------------------------------------------------------------- +phase 1 "configuration (.env)" +if [ -f "$ENV_FILE" ]; then + log ".env exists and is kept as it is: $ENV_FILE" + if [ -n "$ARG_HTTP_PORT" ]; then env_set OVPMON_HTTP_PORT "$ARG_HTTP_PORT"; log "OVPMON_HTTP_PORT=$ARG_HTTP_PORT written to .env"; fi + if [ -n "$ARG_VPN_PORT" ]; then env_set OVPMON_VPN_PORT "$ARG_VPN_PORT"; log "OVPMON_VPN_PORT=$ARG_VPN_PORT written to .env"; fi +else + command -v openssl >/dev/null 2>&1 || log "openssl not found: the secret is generated from /dev/urandom" + JWT=$(openssl rand -hex 32 2>/dev/null || true) + if [ "${#JWT}" -ne 64 ]; then + JWT=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n') + fi + [ "${#JWT}" -eq 64 ] || die "cannot generate a random secret" + ADMIN_PASSWORD=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24) + [ "${#ADMIN_PASSWORD}" -eq 24 ] || die "cannot generate a random password" + ( + umask 077 + { + echo "# Created by deploy/docker/install.sh on $(date -u '+%Y-%m-%d %H:%M:%S') UTC. Keep it private, never commit it." + echo "JWT_SECRET=$JWT" + echo "# Initial administrator: used only while the users table is empty; install.sh removes these two lines after the first start" + echo "OVPMON_INITIAL_ADMIN_USER=$ADMIN_USER" + echo "OVPMON_INITIAL_ADMIN_PASSWORD=$ADMIN_PASSWORD" + echo "# Optional settings" + if [ -n "$ARG_HTTP_PORT" ]; then echo "OVPMON_HTTP_PORT=$ARG_HTTP_PORT"; else echo "# OVPMON_HTTP_PORT=80"; fi + if [ -n "$ARG_VPN_PORT" ]; then echo "OVPMON_VPN_PORT=$ARG_VPN_PORT"; else echo "# OVPMON_VPN_PORT=1194"; fi + echo "# OVPMON_CORS_ORIGINS=" + } > "$ENV_FILE" + ) + chmod 600 "$ENV_FILE" + unset JWT ADMIN_PASSWORD + log ".env created (mode 600): $ENV_FILE" +fi +check_env_file +dc config -q || die "compose configuration is invalid (see the message above)" + +# --------------------------------------------------------------------------------------------- +phase 2 "build" +dc build + +# --------------------------------------------------------------------------------------------- +phase 3 "start" +dc up -d +[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || INSTALLED_AT=$(date -u '+%Y-%m-%dT%H:%M:%SZ') +state_write "$VARIANT" "$PROJECT" "${INSTALLED_AT:-}" +log "state recorded in $STATE_FILE" +if ! wait_healthy; then + die "the stack did not become healthy. Check: $DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") logs" +fi + +# --------------------------------------------------------------------------------------------- +phase 4 "initial administrator" +SHOW_USER="" +SHOW_PASSWORD="" +print_admin() { + [ -n "$SHOW_PASSWORD" ] || return 0 + printf '\n Administrator (shown ONCE, it is not stored anywhere any more):\n' + printf ' login: %s\n' "$SHOW_USER" + printf ' password: %s\n' "$SHOW_PASSWORD" +} +if [ -n "$(env_get OVPMON_INITIAL_ADMIN_USER)$(env_get OVPMON_INITIAL_ADMIN_PASSWORD)" ]; then + COUNT=$(users_count || true) + case "$COUNT" in + ""|*[!0-9]*) + warn "cannot read the users table (got '$COUNT'): OVPMON_INITIAL_ADMIN_* are LEFT in .env. Remove them by hand after you have logged in, then: $DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") up -d $SEED_SERVICE" + ;; + 0) + warn "the users table is empty: the administrator was not created. OVPMON_INITIAL_ADMIN_* stay in .env. Check the logs of $SEED_SERVICE" + ;; + *) + SHOW_USER=$(env_get OVPMON_INITIAL_ADMIN_USER) + SHOW_PASSWORD=$(env_get OVPMON_INITIAL_ADMIN_PASSWORD) + env_remove_admin + log "$COUNT user(s) exist: OVPMON_INITIAL_ADMIN_* removed from .env, recreating $SEED_SERVICE without them" + dc up -d --no-deps --force-recreate "$SEED_SERVICE" + if ! wait_healthy; then + # the seed is already gone from .env: the one-time credentials must not be lost + print_admin + die "the stack did not become healthy after removing the seed. Check: $DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") logs" + fi + ;; + esac +else + COUNT=$(users_count || true) + case "$COUNT" in + 0) warn "no users exist and .env has no OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD: add them and run '$DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") up -d $SEED_SERVICE'" ;; + *) log "users already exist: nothing to seed" ;; + esac +fi + +# --------------------------------------------------------------------------------------------- +HOST_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || true) +HOST_IP="${HOST_IP:-}" +URL_PORT="" +[ "$HTTP_PORT" = 80 ] || URL_PORT=":$HTTP_PORT" + +printf '\n' +log "=== INSTALLED: variant $VARIANT, project $PROJECT ===" +printf ' Web UI: http://%s%s/\n' "$HOST_IP" "$URL_PORT" +printf ' OpenVPN: %s/udp on this host (open it in the firewall)\n' "$VPN_PORT" +printf ' Config: %s (mode 600; contains the secret, never commit it)\n' "$ENV_FILE" +print_admin +cat < Initialize PKI (wait until it finishes). + 3. Generate the server configuration and start the VPN server in the UI. + 4. Put TLS in front of the UI (reverse proxy); the container serves plain HTTP. + Update later with: deploy/docker/update.sh Backup: deploy/docker/backup.sh +EOF diff --git a/deploy/docker/lib.sh b/deploy/docker/lib.sh new file mode 100644 index 0000000..3ee13c7 --- /dev/null +++ b/deploy/docker/lib.sh @@ -0,0 +1,616 @@ +#!/bin/sh +# lib.sh: shared helpers of install.sh, update.sh, backup.sh and restore.sh (scenario 1, containers). +# Sourced, not executed. The caller sets SCRIPT_DIR (directory of the calling script) first: +# +# SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +# . "$SCRIPT_DIR/lib.sh" +# +# POSIX sh (dash, busybox ash, bash); `local` is used in functions (supported by all of them). +# Nothing here ever runs `down -v`, `volume rm` or `docker system prune`. + +ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd) +ENV_FILE="$ROOT_DIR/.env" +STATE_FILE="$ROOT_DIR/.ovpmon-deploy" +LOCK_DIR="$ROOT_DIR/.ovpmon-lock" +BACKUP_ROOT="${OVPMON_BACKUP_DIR:-$ROOT_DIR/backups}" +case "$BACKUP_ROOT" in /*) ;; *) BACKUP_ROOT="$PWD/$BACKUP_ROOT" ;; esac # docker -v needs an absolute path + +# Logical names of the five named volumes (identical in variants A and B) +VOLUMES="ovp_logs ovp_config ovp_pki ovp_client_config db_data" +# Throwaway image for backup/restore containers (override for offline hosts: any image with sh and tar) +BACKUP_IMAGE="${OVPMON_BACKUP_IMAGE:-alpine:3}" +# Seconds to wait for the stack to become healthy +HEALTH_TIMEOUT="${OVPMON_HEALTH_TIMEOUT:-180}" +# Minimum free space in MB: docker data root (images) and the backup directory +MIN_FREE_DOCKER_MB="${OVPMON_MIN_FREE_MB:-2048}" +MIN_FREE_BACKUP_MB="${OVPMON_MIN_FREE_BACKUP_MB:-1024}" +# How many backups update.sh keeps +KEEP_BACKUPS=5 + +DEFAULT_PROJECT=ovpmon + +# --------------------------------------------------------------------------------------------- +# Output +# --------------------------------------------------------------------------------------------- +log() { printf '%s %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*"; } +warn() { log "WARNING: $*" >&2; } +die() { log "ERROR: $*" >&2; exit 1; } +phase() { printf '\n'; log "=== PHASE $1: $2 ==="; } + +# confirm "question": 0 = yes. ASSUME_YES=1 (--yes) skips the question. +confirm() { + local ans + [ "${ASSUME_YES:-0}" = 1 ] && return 0 + [ -t 0 ] || die "confirmation required but stdin is not a terminal: use --yes" + printf '%s [y/N] ' "$1" + read -r ans || return 1 + case "$ans" in y|Y|yes|YES) return 0 ;; esac + return 1 +} + +# --------------------------------------------------------------------------------------------- +# Docker and compose +# --------------------------------------------------------------------------------------------- +need_docker() { + command -v docker >/dev/null 2>&1 || die "docker not found in PATH" + docker info >/dev/null 2>&1 || die "the Docker daemon is not running or not accessible for this user (start it, use sudo or join the docker group)" + if docker compose version >/dev/null 2>&1; then + DC_BIN="docker compose" + elif command -v docker-compose >/dev/null 2>&1; then + DC_BIN="docker-compose" + else + die "neither 'docker compose' (v2) nor 'docker-compose' found" + fi +} + +# set_variant a|b: compose file, service and container names of the variant +set_variant() { + case "$1" in + a|A) + VARIANT=a + COMPOSE_FILE="$ROOT_DIR/docker-compose.allinone.yml" + SERVICES="ovpmon" + CONTAINERS="ovp-allinone" + OTHER_CONTAINERS="ovp-ui ovp-api ovp-gatherer ovp-profiler" + SEED_SERVICE="ovpmon" + # name:service:directory of migrate.py inside the container + MIG_TARGETS="profiler:ovpmon:/app/APP_PROFILER monitoring:ovpmon:/app/APP_CORE" + ;; + b|B) + VARIANT=b + COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" + SERVICES="app-ui app-api app-gatherer app-profiler" + CONTAINERS="ovp-ui ovp-api ovp-gatherer ovp-profiler" + OTHER_CONTAINERS="ovp-allinone" + SEED_SERVICE="app-api" + MIG_TARGETS="profiler:app-profiler:/app monitoring:app-api:/app" + ;; + *) die "variant must be 'a' (one container) or 'b' (one container per component), got '$1'" ;; + esac + [ -f "$COMPOSE_FILE" ] || die "compose file not found: $COMPOSE_FILE" +} + +valid_project() { + case "$1" in + ""|[!a-z0-9]*|*[!a-z0-9_-]*) return 1 ;; + esac + return 0 +} + +# dc ARGS...: docker compose for the selected variant and project. DC_OVERRIDE adds a second file. +dc() { + if [ -n "${DC_OVERRIDE:-}" ]; then + ( cd "$ROOT_DIR" && $DC_BIN -p "$PROJECT" -f "$COMPOSE_FILE" -f "$DC_OVERRIDE" "$@" ) + else + ( cd "$ROOT_DIR" && $DC_BIN -p "$PROJECT" -f "$COMPOSE_FILE" "$@" ) + fi +} + +container_exists() { docker container inspect "$1" >/dev/null 2>&1; } +container_running() { [ "$(docker container inspect -f '{{.State.Running}}' "$1" 2>/dev/null)" = "true" ]; } +container_project() { docker container inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$1" 2>/dev/null || true; } + +# Variant A and B use the same host ports and fixed container names: only one may run +check_other_variant_stopped() { + local c + for c in $OTHER_CONTAINERS; do + if container_running "$c"; then + die "container '$c' of the OTHER variant is running. Variants A and B cannot run together (same ports and container names). Stop it first, for example: docker stop $OTHER_CONTAINERS" + fi + done +} + +# A container with our fixed name that belongs to another compose project would make 'up' fail +check_name_clash() { + local c p + for c in $CONTAINERS; do + if container_exists "$c"; then + p=$(container_project "$c") + if [ -n "$p" ] && [ "$p" != "$PROJECT" ]; then + die "container '$c' exists and belongs to compose project '$p', not '$PROJECT'. Use --project $p or remove that container" + fi + fi + done +} + +stack_running() { + local c + for c in $CONTAINERS; do container_running "$c" && return 0; done + return 1 +} + +stack_exists() { + local c + for c in $CONTAINERS; do container_exists "$c" && return 0; done + return 1 +} + +# detect_project_from_containers: compose project of an existing container of this variant +detect_project_from_containers() { + local c p + for c in $CONTAINERS; do + if container_exists "$c"; then + p=$(container_project "$c") + [ -n "$p" ] && { echo "$p"; return 0; } + fi + done + return 1 +} + +# volume_name LOGICAL: real name of the project's volume (empty if it does not exist) +volume_name() { + local v + v=$(docker volume ls -q \ + --filter "label=com.docker.compose.project=$PROJECT" \ + --filter "label=com.docker.compose.volume=$1" 2>/dev/null | head -n 1) + if [ -z "$v" ] && docker volume inspect "${PROJECT}_$1" >/dev/null 2>&1; then + v="${PROJECT}_$1" + fi + echo "$v" +} + +# --------------------------------------------------------------------------------------------- +# State file (.ovpmon-deploy): variant and project chosen by install.sh, read by the other scripts +# --------------------------------------------------------------------------------------------- +state_get() { + [ -f "$STATE_FILE" ] || return 0 + sed -n "s/^$1=//p" "$STATE_FILE" | tail -n 1 +} + +# state_write VARIANT PROJECT [INSTALLED_AT] [LAST_UPDATE]: missing times are kept from the old file +state_write() { + local tmp inst upd + tmp="$STATE_FILE.tmp.$$" + inst="${3:-$(state_get OVPMON_INSTALLED_AT)}" + upd="${4:-$(state_get OVPMON_LAST_UPDATE)}" + { + echo "# written by deploy/docker scripts; read by update.sh, backup.sh, restore.sh" + echo "OVPMON_VARIANT=$1" + echo "OVPMON_PROJECT=$2" + echo "OVPMON_INSTALLED_AT=$inst" + echo "OVPMON_LAST_UPDATE=$upd" + } > "$tmp" + mv "$tmp" "$STATE_FILE" +} + +# resolve_stack: sets VARIANT/PROJECT from the state file, checked against --variant/--project +# (ARG_VARIANT, ARG_PROJECT). Without a state file (stack started by hand) --variant is required; +# the project is taken from the existing containers. +resolve_stack() { + local sv sp + sv=$(state_get OVPMON_VARIANT) + sp=$(state_get OVPMON_PROJECT) + if [ -n "$sv" ]; then + [ -z "${ARG_VARIANT:-}" ] || [ "$ARG_VARIANT" = "$sv" ] || die "--variant $ARG_VARIANT does not match the installed variant '$sv' (state file $STATE_FILE). Switching variants is described in DOCS/Deployment/Scenario1_Containers.md" + [ -z "${ARG_PROJECT:-}" ] || [ "$ARG_PROJECT" = "$sp" ] || die "--project $ARG_PROJECT does not match the installed project '$sp' (state file $STATE_FILE)" + PROJECT="$sp" + set_variant "$sv" + STATE_ADOPTED=0 + else + [ -n "${ARG_VARIANT:-}" ] || die "no state file ($STATE_FILE): pass --variant a|b (and --project NAME if the stack was not started by install.sh)" + set_variant "$ARG_VARIANT" + PROJECT="${ARG_PROJECT:-}" + if [ -z "$PROJECT" ]; then + PROJECT=$(detect_project_from_containers || true) + [ -n "$PROJECT" ] || PROJECT="$DEFAULT_PROJECT" + fi + STATE_ADOPTED=1 + warn "no state file: adopting an existing stack (variant $VARIANT, project $PROJECT); it is recorded after success" + fi + valid_project "$PROJECT" || die "invalid compose project name '$PROJECT'" +} + +# --------------------------------------------------------------------------------------------- +# .env helpers (read and edit without sourcing: the file is data, not code) +# --------------------------------------------------------------------------------------------- +env_get() { + [ -f "$ENV_FILE" ] || return 0 + sed -n "s/^[[:space:]]*$1=//p" "$ENV_FILE" | tail -n 1 | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/" +} + +# env_set KEY VALUE (VALUE must not contain | & \ or newlines: used for ports and names) +env_set() { + local tmp + tmp="$ENV_FILE.tmp.$$" + ( umask 077 + if [ -f "$ENV_FILE" ] && grep -q "^$1=" "$ENV_FILE"; then + sed "s|^$1=.*|$1=$2|" "$ENV_FILE" > "$tmp" + else + { [ -f "$ENV_FILE" ] && cat "$ENV_FILE"; printf '%s=%s\n' "$1" "$2"; } > "$tmp" + fi ) + chmod 600 "$tmp" + mv "$tmp" "$ENV_FILE" +} + +# env_remove_admin: delete the initial-admin seed lines from .env (mode stays 600) +env_remove_admin() { + local tmp + tmp="$ENV_FILE.tmp.$$" + ( umask 077; grep -v -E '^[[:space:]]*(OVPMON_INITIAL_ADMIN_(USER|PASSWORD)=|# Initial administrator)' "$ENV_FILE" > "$tmp" || true ) + chmod 600 "$tmp" + mv "$tmp" "$ENV_FILE" +} + +check_env_file() { + [ -f "$ENV_FILE" ] || die ".env not found at $ENV_FILE (install.sh creates it)" + [ -n "$(env_get JWT_SECRET)" ] || die "JWT_SECRET is empty in $ENV_FILE" + if [ -n "$(find "$ENV_FILE" \( -perm -040 -o -perm -004 \) 2>/dev/null)" ]; then + warn ".env is readable by other users; fix with: chmod 600 $ENV_FILE" + fi +} + +valid_port() { + case "$1" in + ""|*[!0-9]*) return 1 ;; + esac + [ "$1" -ge 1 ] && [ "$1" -le 65535 ] +} + +# --------------------------------------------------------------------------------------------- +# Host checks +# --------------------------------------------------------------------------------------------- +# port_in_use PORT tcp|udp: 0 = in use, 1 = free, 2 = cannot tell +port_in_use() { + local fl + case "$2" in tcp) fl=-ltn ;; *) fl=-lun ;; esac + if command -v ss >/dev/null 2>&1; then + ss $fl 2>/dev/null | awk -v p=":$1\$" '$4 ~ p { f = 1 } END { exit !f }' && return 0 || return 1 + elif command -v netstat >/dev/null 2>&1; then + netstat $fl 2>/dev/null | awk -v p=":$1\$" '$4 ~ p { f = 1 } END { exit !f }' && return 0 || return 1 + fi + return 2 +} + +# check_port PORT PROTO LABEL: dies if the port is busy +check_port() { + local rc + port_in_use "$1" "$2" && rc=0 || rc=$? + case "$rc" in + 0) die "$3 port $1/$2 is already in use on this host. Choose another one (--http-port / --vpn-port, or OVPMON_HTTP_PORT / OVPMON_VPN_PORT in .env)" ;; + 2) warn "cannot check whether port $1/$2 is free (no ss or netstat)" ;; + esac + return 0 +} + +# free_mb DIR: free space in MB (empty if unknown) +free_mb() { + df -Pk "$1" 2>/dev/null | awk 'NR == 2 { print int($4 / 1024) }' +} + +# check_free DIR MIN_MB LABEL +check_free() { + local f + f=$(free_mb "$1") + if [ -z "$f" ]; then + warn "cannot determine free space for $3 ($1)" + elif [ "$f" -lt "$2" ]; then + die "not enough free space for $3: ${f} MB free in $1, at least $2 MB required (override: OVPMON_MIN_FREE_MB / OVPMON_MIN_FREE_BACKUP_MB)" + else + log "free space for $3: ${f} MB ($1)" + fi +} + +docker_root_dir() { + local d + d=$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true) + [ -n "$d" ] && [ -d "$d" ] && [ -r "$d" ] && { echo "$d"; return 0; } + echo /var/lib +} + +acquire_lock() { + local pid + if mkdir "$LOCK_DIR" 2>/dev/null; then + echo $$ > "$LOCK_DIR/pid" + LOCK_HELD=1 + return 0 + fi + pid=$(cat "$LOCK_DIR/pid" 2>/dev/null || true) + if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then + die "another deploy script is running (pid $pid)" + fi + warn "removing stale lock $LOCK_DIR" + rm -rf "$LOCK_DIR" + mkdir "$LOCK_DIR" || die "cannot create lock $LOCK_DIR" + echo $$ > "$LOCK_DIR/pid" + LOCK_HELD=1 +} + +release_lock() { + if [ "${LOCK_HELD:-0}" = 1 ]; then + rm -rf "$LOCK_DIR" + LOCK_HELD=0 + fi +} + +# --------------------------------------------------------------------------------------------- +# Health +# --------------------------------------------------------------------------------------------- +service_state() { # SERVICE -> healthy|starting|unhealthy|running|exited|missing ... + local cid + cid=$(dc ps -a -q "$1" 2>/dev/null | head -n 1) + [ -n "$cid" ] || { echo missing; return 0; } + docker container inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$cid" 2>/dev/null || echo unknown +} + +show_failed_logs() { + local s st + for s in $SERVICES; do + st=$(service_state "$s") + case "$st" in + healthy|running) ;; + *) + log "--- last log lines of $s (state: $st) ---" >&2 + dc logs --tail 30 "$s" 2>&1 | sed 's/^/ /' >&2 || true + ;; + esac + done +} + +# wait_healthy [SECONDS]: 0 when every service is healthy (or running without a health check) +wait_healthy() { + local t w all fail s st + t="${1:-$HEALTH_TIMEOUT}" + w=0 + log "waiting for the stack to become healthy (up to ${t}s): $SERVICES" + while :; do + all=1 + fail=0 + for s in $SERVICES; do + st=$(service_state "$s") + case "$st" in + healthy|running) ;; + starting|created) all=0 ;; + *) all=0; fail=1; log "service $s is $st" >&2 ;; + esac + done + if [ "$all" = 1 ]; then + log "stack is healthy" + return 0 + fi + if [ "$fail" = 1 ]; then + show_failed_logs + return 1 + fi + if [ "$w" -ge "$t" ]; then + log "timeout: the stack is not healthy after ${t}s" >&2 + show_failed_logs + return 1 + fi + sleep 3 + w=$((w + 3)) + done +} + +# --------------------------------------------------------------------------------------------- +# Images (:previous tags for rollback) +# --------------------------------------------------------------------------------------------- +image_repo() { # strip a tag, keep a registry port: repo:tag -> repo + case "${1##*/}" in + *:*) echo "${1%:*}" ;; + *) echo "$1" ;; + esac +} + +# record_images DIR: images.tsv with "serviceimage nameimage id" of the existing containers +record_images() { + local s cid name id + : > "$1/images.tsv" + for s in $SERVICES; do + cid=$(dc ps -a -q "$s" 2>/dev/null | head -n 1) + if [ -z "$cid" ]; then + warn "no container for service $s: no previous image recorded for it" + continue + fi + name=$(docker container inspect -f '{{.Config.Image}}' "$cid") + id=$(docker container inspect -f '{{.Image}}' "$cid") + printf '%s\t%s\t%s\n' "$s" "$name" "$id" >> "$1/images.tsv" + done + chmod 600 "$1/images.tsv" +} + +# tag_previous DIR: tag the recorded images ":previous" (so a rebuild does not orphan them) +tag_previous() { + local s name id + [ -s "$1/images.tsv" ] || { warn "no recorded images: rollback to previous images will not be possible"; return 0; } + while IFS="$(printf '\t')" read -r s name id; do + case "$name" in sha256:*) warn "image of $s has no name: cannot tag it"; continue ;; esac + docker tag "$id" "$(image_repo "$name"):previous" || die "cannot tag previous image of $s" + log " $s: $(image_repo "$name"):previous = $id" + done < "$1/images.tsv" +} + +# --------------------------------------------------------------------------------------------- +# Backup and restore of the five volumes (throwaway container, volumes mounted read-only for backup) +# --------------------------------------------------------------------------------------------- +backup_stamp() { date -u '+%Y%m%dT%H%M%SZ'; } + +# Files created by the container are root-owned; give them to the calling user (not in rootless mode) +_backup_owner() { + case "$(docker info --format '{{.SecurityOptions}}' 2>/dev/null)" in + *rootless*) echo "" ;; + *) echo "$(id -u):$(id -g)" ;; + esac +} + +# backup_volumes DIR: .tar.gz for each existing volume, volumes.tsv, SHA256SUMS. Archives are +# written under a temporary name and renamed when complete, so an old archive is never half replaced. +backup_volumes() { + local dir n v real own + dir="$1" + mkdir -p "$dir" + chmod 700 "$dir" + : > "$dir/volumes.tsv.new" # replaces volumes.tsv only when every archive is done + n=0 + for v in $VOLUMES; do + real=$(volume_name "$v") + if [ -z "$real" ]; then + warn "volume $v of project $PROJECT does not exist: skipped" + continue + fi + log " archiving $v ($real)" + docker run --rm -v "$real":/data:ro -v "$dir":/backup "$BACKUP_IMAGE" \ + sh -c "tar -czf /backup/$v.tar.gz.tmp -C /data . && mv /backup/$v.tar.gz.tmp /backup/$v.tar.gz" \ + || { log "backup of volume $v failed" >&2; return 1; } + printf '%s\t%s\n' "$v" "$real" >> "$dir/volumes.tsv.new" + n=$((n + 1)) + done + [ "$n" -gt 0 ] || { log "no volumes found for project $PROJECT: nothing to back up" >&2; return 1; } + mv "$dir/volumes.tsv.new" "$dir/volumes.tsv" + own=$(_backup_owner) + docker run --rm -v "$dir":/backup "$BACKUP_IMAGE" \ + sh -c "cd /backup && sha256sum *.tar.gz > SHA256SUMS && chmod 600 *.tar.gz SHA256SUMS volumes.tsv && { [ -z '$own' ] || chown '$own' *.tar.gz SHA256SUMS volumes.tsv; }" \ + || { log "cannot finish backup (checksums)" >&2; return 1; } +} + +# verify_backup DIR: archive of every volume in volumes.tsv exists and is a readable gzip tar +verify_backup() { + local dir v real + dir="$1" + [ -s "$dir/volumes.tsv" ] || { log "backup $dir has no volumes.tsv" >&2; return 1; } + while IFS="$(printf '\t')" read -r v real; do + [ -s "$dir/$v.tar.gz" ] || { log "archive $v.tar.gz is missing or empty in $dir" >&2; return 1; } + done < "$dir/volumes.tsv" + docker run --rm -v "$dir":/backup:ro "$BACKUP_IMAGE" \ + sh -c 'for f in /backup/*.tar.gz; do tar -tzf "$f" >/dev/null || { echo "corrupt archive: $f" >&2; exit 1; }; done' \ + || return 1 +} + +git_head() { + git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || echo "n/a" +} + +write_manifest() { # DIR KIND + { + echo "created_utc=$(date -u '+%Y-%m-%dT%H:%M:%SZ')" + echo "kind=$2" + echo "variant=$VARIANT" + echo "project=$PROJECT" + echo "compose_file=$(basename "$COMPOSE_FILE")" + echo "git_commit=$(git_head)" + } > "$1/MANIFEST" + chmod 600 "$1/MANIFEST" +} + +# make_backup DIR KIND: full backup into DIR, verified, marked COMPLETE (only complete backups are used) +make_backup() { + local dir + dir="$1" + rm -f "$dir/COMPLETE" + backup_volumes "$dir" || return 1 + if [ -f "$ENV_FILE" ]; then + ( umask 077; cp "$ENV_FILE" "$dir/.env" ) + fi + write_manifest "$dir" "$2" + log "verifying the backup" + verify_backup "$dir" || return 1 + date -u '+%Y-%m-%dT%H:%M:%SZ' > "$dir/COMPLETE" + chmod 600 "$dir/COMPLETE" +} + +# list_backups: timestamp directories, oldest first +list_backups() { + [ -d "$BACKUP_ROOT" ] || return 0 + ls -1 "$BACKUP_ROOT" 2>/dev/null | grep -E '^[0-9]{8}T[0-9]{6}Z$' | sort || true +} + +# latest_backup: path of the newest COMPLETE backup (empty if none) +latest_backup() { + local b + for b in $(list_backups | sort -r); do + if [ -f "$BACKUP_ROOT/$b/COMPLETE" ]; then + echo "$BACKUP_ROOT/$b" + return 0 + fi + done + return 0 +} + +# prune_backups [KEEP]: keep the newest KEEP timestamp directories (default 5) +prune_backups() { + local keep + keep="${1:-$KEEP_BACKUPS}" + list_backups | sort -r | awk -v k="$keep" 'NR > k' | while read -r b; do + log "removing old backup $BACKUP_ROOT/$b" + rm -rf "${BACKUP_ROOT:?}/$b" + done +} + +# restore_volumes DIR SAFETY: replace the content of the volumes with the archives of DIR. +# The stack must be stopped. SAFETY=1 first saves the current content to /-pre-restore. +# Volumes are emptied and refilled, never removed. +restore_volumes() { + local dir safe v real + dir="$1" + verify_backup "$dir" || { log "backup $dir failed verification: nothing was changed" >&2; return 1; } + # Refuse if anything still uses the volumes + while IFS="$(printf '\t')" read -r v real; do + if [ -n "$(docker ps -q --filter "volume=$real")" ]; then + log "volume $real is in use by a running container: stop the stack first" >&2 + return 1 + fi + done < "$dir/volumes.tsv" + if [ "${2:-0}" = 1 ] && [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then + safe="$BACKUP_ROOT/$(backup_stamp)-pre-restore" + log "saving the current content first: $safe" + make_backup "$safe" "pre-restore" || { log "safety backup failed: nothing was changed" >&2; return 1; } + fi + while IFS="$(printf '\t')" read -r v real; do + if ! docker volume inspect "$real" >/dev/null 2>&1; then + log " creating missing volume $real" + docker volume create \ + --label "com.docker.compose.project=$PROJECT" \ + --label "com.docker.compose.volume=$v" "$real" >/dev/null || return 1 + fi + log " restoring $v ($real)" + docker run --rm -v "$real":/data -v "$dir":/backup:ro "$BACKUP_IMAGE" \ + sh -c "rm -rf /data/* /data/.[!.]* /data/..?* && tar -xzf /backup/$v.tar.gz -C /data" \ + || { log "restore of volume $v failed: restore again from $dir before starting anything" >&2; return 1; } + done < "$dir/volumes.tsv" +} + +# start_previous DIR: start the images recorded in DIR/images.tsv (tagged :previous) with the same +# compose file, through a generated override file; no build. DC_OVERRIDE stays set afterwards, so +# the following dc calls (health wait, status) see the same configuration. +start_previous() { + local dir ov s name id + dir="$1" + [ -s "$dir/images.tsv" ] || { log "no images.tsv in $dir: cannot start previous images" >&2; return 1; } + ov="$dir/compose.previous.yml" + { + echo "# generated: runs the images recorded before the update" + echo "services:" + } > "$ov" + while IFS="$(printf '\t')" read -r s name id; do + case "$name" in sha256:*) log "image of $s has no name" >&2; return 1 ;; esac + docker image inspect "$id" >/dev/null 2>&1 || { log "previous image $id of $s is no longer present" >&2; return 1; } + docker tag "$id" "$(image_repo "$name"):previous" || return 1 + printf ' %s:\n image: %s:previous\n' "$s" "$(image_repo "$name")" >> "$ov" + done < "$dir/images.tsv" + DC_OVERRIDE="$ov" + dc up -d --no-build --force-recreate +} + +# users_count: rows in the users table of the monitoring database (empty if it cannot be read) +users_count() { + dc exec -T "$SEED_SERVICE" python -c 'import os, sqlite3; c = sqlite3.connect("file:" + os.environ["OVPMON_OPENVPN_MONITOR_DB_PATH"] + "?mode=ro", uri=True); print(c.execute("SELECT COUNT(*) FROM users").fetchone()[0])' 2>/dev/null | tail -n 1 | tr -d '\r ' +} diff --git a/deploy/docker/restore.sh b/deploy/docker/restore.sh new file mode 100755 index 0000000..9e245e6 --- /dev/null +++ b/deploy/docker/restore.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# Restore the five data volumes from a backup directory (made by backup.sh or update.sh). +# +# deploy/docker/restore.sh BACKUP_DIR [--variant a|b] [--project NAME] [--yes] [--start] +# +# BACKUP_DIR e.g. backups/20261005T101500Z +# --start start the stack after the restore (default: only print the command) +# +# The application containers are stopped (after confirmation); the CURRENT content of the volumes is +# first saved to backups/-pre-restore (OVPMON_NO_SAFETY_BACKUP=1 skips it), then each volume +# is emptied and refilled from its archive. Volumes are never removed. .env is not touched: the copy +# in the backup is only reported. To also go back to the previous images use: update.sh --rollback +# See DOCS/Deployment/Scenario1_Containers.md +set -eu + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +. "$SCRIPT_DIR/lib.sh" + +usage() { + sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' +} + +ARG_VARIANT="" +ARG_PROJECT="" +ASSUME_YES=0 +START=0 +SRC="" + +while [ $# -gt 0 ]; do + case "$1" in + --variant) [ $# -ge 2 ] || die "--variant needs a value"; ARG_VARIANT="$2"; shift 2 ;; + --project) [ $# -ge 2 ] || die "--project needs a value"; ARG_PROJECT="$2"; shift 2 ;; + --yes|-y) ASSUME_YES=1; shift ;; + --start) START=1; shift ;; + -h|--help) usage; exit 0 ;; + -*) usage >&2; die "unknown option: $1" ;; + *) [ -z "$SRC" ] || die "only one backup directory can be given"; SRC="$1"; shift ;; + esac +done +[ -n "$SRC" ] || { usage >&2; die "BACKUP_DIR is required"; } +[ -d "$SRC" ] || die "not a directory: $SRC" +SRC=$(cd "$SRC" && pwd) + +trap release_lock EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +need_docker +resolve_stack +acquire_lock + +# The archives belong to the volumes of one project +BK_PROJECT=$(sed -n 's/^project=//p' "$SRC/MANIFEST" 2>/dev/null | tail -n 1 || true) +if [ -n "$BK_PROJECT" ] && [ "$BK_PROJECT" != "$PROJECT" ]; then + die "the backup belongs to project '$BK_PROJECT', this stack uses '$PROJECT' (use --project $BK_PROJECT)" +fi +log "backup: $SRC" +[ -f "$SRC/MANIFEST" ] && sed 's/^/ /' "$SRC/MANIFEST" +[ -f "$SRC/COMPLETE" ] || warn "the backup is not marked COMPLETE (an interrupted backup?)" +log "verifying the backup" +verify_backup "$SRC" || die "the backup is damaged or incomplete: nothing was changed" +if [ -f "$SRC/.env" ] && [ -f "$ENV_FILE" ] && ! cmp -s "$SRC/.env" "$ENV_FILE"; then + warn ".env differs from the copy in the backup ($SRC/.env); it is NOT restored. A different JWT_SECRET logs everybody out." +fi + +log "the content of the volumes of project $PROJECT will be REPLACED by this backup (the current content is saved first)" +confirm "Stop the stack and restore?" || die "aborted by the user" + +if stack_running; then + log "stopping the application containers" + dc stop +fi +restore_volumes "$SRC" 1 || die "the restore failed (see above). The backup is intact: $SRC" +log "restore complete" + +if [ "$START" = 1 ]; then + dc up -d + wait_healthy || die "the stack did not become healthy after the restore" +else + log "start the stack when ready: $DC_BIN -p $PROJECT -f $(basename "$COMPOSE_FILE") up -d" +fi diff --git a/deploy/docker/update.sh b/deploy/docker/update.sh new file mode 100755 index 0000000..97b3d42 --- /dev/null +++ b/deploy/docker/update.sh @@ -0,0 +1,261 @@ +#!/bin/sh +# Update OpenVPN Monitor & Profiler in containers without touching the data. +# +# deploy/docker/update.sh [--variant a|b] [--project NAME] [--yes] [--no-pull] [--rollback] +# +# --variant, --project normally read from .ovpmon-deploy (written by install.sh); needed only for +# a stack that was started by hand +# --yes no confirmation questions +# --no-pull no "git pull --ff-only" and no refresh of the base images (offline hosts) +# --rollback restore the volumes from the newest backup and start the previous images +# +# Phases: 0 preflight, 1 BACKUP of the five volumes, 2 git pull, 3 BUILD (old stack still running), +# 4 STOP, 5 DATABASE MIGRATION (own step, nothing is started yet), 6 START and health check. +# A failure in phases 4-6 triggers an automatic rollback: the volumes are restored from the backup of +# this run and the previous images are started. Volumes are never removed. +# See DOCS/Deployment/Scenario1_Containers.md and DOCS/General/Database_Migrations.md +set -eu + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +. "$SCRIPT_DIR/lib.sh" + +usage() { + sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//' +} + +ARG_VARIANT="" +ARG_PROJECT="" +ASSUME_YES=0 +NO_PULL=0 +DO_ROLLBACK=0 + +BACKUP_DIR="" +CURRENT_PHASE="start" +ROLLBACK_ARMED=0 +STACK_WAS_RUNNING=0 + +# --------------------------------------------------------------------------------------------- +# Rollback +# --------------------------------------------------------------------------------------------- +rollback_failed() { + log "!!! ROLLBACK FAILED: $1" >&2 + log "!!! Your data is safe in the backup: $BACKUP_DIR" >&2 + log "!!! Retry the rollback: $SCRIPT_DIR/update.sh --rollback (or only the data: $SCRIPT_DIR/restore.sh $BACKUP_DIR)" >&2 +} + +# Automatic rollback after a failure in phases 4-6 (called from the EXIT trap) +auto_rollback() { + printf '\n' >&2 + log "!!! UPDATE FAILED in phase: $CURRENT_PHASE" >&2 + log "!!! Automatic rollback: restore the volumes from $BACKUP_DIR and start the previous images" >&2 + dc stop >/dev/null 2>&1 || true + if ! restore_volumes "$BACKUP_DIR" 0; then + rollback_failed "the volumes could not be restored" + return 0 + fi + if ! start_previous "$BACKUP_DIR"; then + rollback_failed "the previous images could not be started" + return 0 + fi + if ! wait_healthy; then + rollback_failed "the previous version did not become healthy" + return 0 + fi + log "!!! ROLLED BACK: the previous version is running again on the data as it was before the update." >&2 + log "!!! The update failed in phase '$CURRENT_PHASE'; see the messages above. Backup kept in: $BACKUP_DIR" >&2 +} + +on_exit() { + _rc=$? + set +e + trap '' INT TERM + if [ "$_rc" -ne 0 ]; then + if [ "$ROLLBACK_ARMED" = 1 ]; then + ROLLBACK_ARMED=0 + auto_rollback + elif [ -n "$BACKUP_DIR" ]; then + log "update stopped in phase '$CURRENT_PHASE' before the running stack was changed. Backup: $BACKUP_DIR" >&2 + fi + fi + release_lock + exit "$_rc" +} + +manual_rollback() { + BACKUP_DIR=$(latest_backup) + [ -n "$BACKUP_DIR" ] || die "no complete backup found in $BACKUP_ROOT" + log "newest backup: $BACKUP_DIR" + [ -f "$BACKUP_DIR/MANIFEST" ] && sed 's/^/ /' "$BACKUP_DIR/MANIFEST" + [ -s "$BACKUP_DIR/images.tsv" ] || die "the backup has no recorded images (images.tsv): use restore.sh to restore the data only" + log "the volumes of project $PROJECT will be REPLACED by this backup; the current content is saved first to $BACKUP_ROOT/-pre-restore" + confirm "Restore all volumes from this backup and start the previous images?" || die "aborted by the user" + phase R1 "stop the stack" + dc stop + phase R2 "restore the volumes" + restore_volumes "$BACKUP_DIR" 1 || die "restore failed (see above). The backup is intact: $BACKUP_DIR" + phase R3 "start the previous images" + start_previous "$BACKUP_DIR" || die "the previous images could not be started (data is restored; see above)" + wait_healthy || die "the stack did not become healthy" + printf '\n' + log "=== ROLLBACK DONE: the data and images of $BACKUP_DIR are in use ===" +} + +# --------------------------------------------------------------------------------------------- +# Phase 5 helper: one component's database, one-off container from the NEW image, same volumes +# --------------------------------------------------------------------------------------------- +indent() { printf '%s\n' "$1" | sed 's/^/ | /'; } + +migrate_component() { # NAME SERVICE DIR + local name svc dir rc out + name="$1"; svc="$2"; dir="$3" + log "--- $name database: check ---" + rc=0 + out=$(dc run --rm --no-deps -T --entrypoint sh "$svc" -c "cd $dir && python migrate.py --check" 2>&1) || rc=$? + indent "$out" + case "$rc" in + 0) log "$name: up to date, nothing to migrate"; return 0 ;; + 2) log "$name: migrations pending: applying (a consistent backup of the database is made first)" ;; + *) die "$name: the check failed with exit code $rc (database newer than this version, damaged, or the check could not run)" ;; + esac + rc=0 + out=$(dc run --rm --no-deps -T --entrypoint sh "$svc" -c "cd $dir && python migrate.py" 2>&1) || rc=$? + indent "$out" + [ "$rc" -eq 0 ] || die "$name: the migration failed with exit code $rc" + rc=0 + out=$(dc run --rm --no-deps -T --entrypoint sh "$svc" -c "cd $dir && python migrate.py --check" 2>&1) || rc=$? + [ "$rc" -eq 0 ] || { indent "$out"; die "$name: the database is not up to date after the migration (exit code $rc)"; } + log "$name: migrated, database is up to date" +} + +# --------------------------------------------------------------------------------------------- +main() { + while [ $# -gt 0 ]; do + case "$1" in + --variant) [ $# -ge 2 ] || die "--variant needs a value"; ARG_VARIANT="$2"; shift 2 ;; + --project) [ $# -ge 2 ] || die "--project needs a value"; ARG_PROJECT="$2"; shift 2 ;; + --yes|-y) ASSUME_YES=1; shift ;; + --no-pull) NO_PULL=1; shift ;; + --rollback) DO_ROLLBACK=1; shift ;; + -h|--help) usage; exit 0 ;; + *) usage >&2; die "unknown option: $1" ;; + esac + done + + trap on_exit EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + need_docker + resolve_stack + acquire_lock + + if [ "$DO_ROLLBACK" = 1 ]; then + manual_rollback + return 0 + fi + + # ----- Phase 0 ------------------------------------------------------------------------- + CURRENT_PHASE="0 preflight" + phase 0 "preflight" + log "variant $VARIANT, project $PROJECT, compose file $(basename "$COMPOSE_FILE"), docker compose command: $DC_BIN" + check_env_file + dc config -q || die "the compose configuration is invalid (see the message above)" + check_other_variant_stopped + check_name_clash + stack_exists || die "no containers of variant $VARIANT found in project $PROJECT: nothing to update (install first, or check --variant / --project)" + if stack_running; then + STACK_WAS_RUNNING=1 + else + warn "the stack is not running" + confirm "Continue anyway? (the stack will be started at the end)" || die "aborted by the user" + fi + [ -n "$(volume_name db_data)" ] || die "volume db_data of project '$PROJECT' not found: wrong --project? Nothing was changed" + mkdir -p "$BACKUP_ROOT" + chmod 700 "$BACKUP_ROOT" 2>/dev/null || true + check_free "$BACKUP_ROOT" "$MIN_FREE_BACKUP_MB" "backups" + check_free "$(docker_root_dir)" "$MIN_FREE_DOCKER_MB" "new images (docker data root)" + OLD_COMMIT=$(git_head) + log "current source version: $OLD_COMMIT" + log "plan: backup -> git pull -> build -> stop -> DATABASE MIGRATION -> start (automatic rollback after the stop)" + confirm "Update now?" || die "aborted by the user" + + # ----- Phase 1: backup ----------------------------------------------------------------- + CURRENT_PHASE="1 backup" + phase 1 "BACKUP of all volumes" + BACKUP_DIR="$BACKUP_ROOT/$(backup_stamp)" + [ ! -e "$BACKUP_DIR" ] || die "backup directory already exists: $BACKUP_DIR (retry in a second)" + mkdir -p "$BACKUP_DIR" + chmod 700 "$BACKUP_DIR" + log "backup directory: $BACKUP_DIR" + record_images "$BACKUP_DIR" + if ! make_backup "$BACKUP_DIR" update; then + die "the BACKUP FAILED. Nothing was changed, the update is refused. (The incomplete backup in $BACKUP_DIR is never used.)" + fi + log "backup complete and verified: $BACKUP_DIR" + + # ----- Phase 2: sources ---------------------------------------------------------------- + CURRENT_PHASE="2 git pull" + phase 2 "source update" + if [ "$NO_PULL" = 1 ]; then + log "skipped (--no-pull)" + elif ! git -C "$ROOT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + log "not a git checkout: skipped (put the new sources in place yourself before running this script)" + else + git -C "$ROOT_DIR" pull --ff-only || die "git pull --ff-only failed. The stack was not touched. Fix the checkout, or use --no-pull" + log "source version: $OLD_COMMIT -> $(git_head)" + log "note: if deploy/docker/*.sh changed, the new versions are used from the next run" + fi + + # ----- Phase 3: build ------------------------------------------------------------------ + CURRENT_PHASE="3 build" + phase 3 "BUILD the new images (the old stack keeps running)" + dc config -q || die "the compose configuration is invalid after the source update" + log "tagging the current images as :previous" + tag_previous "$BACKUP_DIR" + if [ "$NO_PULL" = 1 ]; then + dc build || die "the build failed. The stack was not touched (still running the old version)" + else + dc build --pull || die "the build failed. The stack was not touched (still running the old version)" + fi + + # ----- Phase 4: stop ------------------------------------------------------------------- + CURRENT_PHASE="4 stop" + phase 4 "STOP the application containers (volumes are kept)" + ROLLBACK_ARMED=1 # from here on a failure restores the backup and the previous images + dc stop + if [ "$STACK_WAS_RUNNING" = 1 ]; then + log "final consistent snapshot of the volumes (everything is stopped, the databases are quiet)" + make_backup "$BACKUP_DIR" update || die "the final snapshot failed" + fi + + # ----- Phase 5: database migration ----------------------------------------------------- + CURRENT_PHASE="5 database migration" + phase 5 "DATABASE MIGRATION (own step; no service is started on an unmigrated database)" + log "one-off containers from the NEW images with the same volumes; reports below" + for t in $MIG_TARGETS; do # name:service:directory + _mname=${t%%:*}; _mrest=${t#*:} + migrate_component "$_mname" "${_mrest%%:*}" "${_mrest#*:}" + done + log "all databases are up to date" + + # ----- Phase 6: start ------------------------------------------------------------------ + CURRENT_PHASE="6 start" + phase 6 "START the new stack" + dc up -d --no-build + wait_healthy || die "the new stack did not become healthy" + + # ----- Done ---------------------------------------------------------------------------- + ROLLBACK_ARMED=0 + CURRENT_PHASE="finish" + state_write "$VARIANT" "$PROJECT" "" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" + phase 7 "finish" + prune_backups + printf '\n' + log "=== UPDATE SUCCESSFUL: variant $VARIANT, project $PROJECT ===" + printf ' Source version: %s -> %s\n' "$OLD_COMMIT" "$(git_head)" + printf ' Backup: %s (the newest %s backups are kept)\n' "$BACKUP_DIR" "$KEEP_BACKUPS" + printf ' Previous images: tagged :previous (rollback: %s --rollback)\n' "$0" + printf ' Check in the UI that the OpenVPN server is running: the containers were recreated and the\n' + printf ' profiler starts OpenVPN only on request.\n' +} + +main "$@"; exit $? diff --git a/docker-compose.allinone.yml b/docker-compose.allinone.yml new file mode 100644 index 0000000..8a9e653 --- /dev/null +++ b/docker-compose.allinone.yml @@ -0,0 +1,64 @@ +# OpenVPN Monitor & Profiler: ALL components in ONE container (scenario 1, variant A) +# Required: JWT_SECRET in .env (openssl rand -hex 32) +# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env +# Optional: OVPMON_CORS_ORIGINS, OVPMON_HTTP_PORT (host port of the UI, default 80), +# OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194) +# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Scenario1_Containers.md) +# +# Variants A (this file) and B (docker-compose.yml) publish the same host ports and use fixed +# container names (ovp-*): run only ONE variant per host. Both use the same five volumes with the +# same in-container paths, so backups are identical and data of one variant can be used by the other. + +services: + ovpmon: + build: + context: . + dockerfile: deploy/allinone/Dockerfile + container_name: ovp-allinone + restart: unless-stopped + stop_grace_period: 20s + cap_add: + - NET_ADMIN + sysctls: + - net.ipv4.ip_forward=1 + devices: + - "/dev/net/tun:/dev/net/tun" + ports: + # UI (Nginx) and VPN port only; both APIs listen on 127.0.0.1 inside the container + - "${OVPMON_HTTP_PORT:-80}:80" + - "${OVPMON_VPN_PORT:-1194}:1194/udp" + volumes: + - ovp_logs:/var/log/openvpn + - ovp_config:/etc/openvpn + - ovp_pki:/app/easy-rsa + - ovp_client_config:/app/client-config + - db_data:/app/db + environment: + OVPMON_API_SECRET_KEY: ${JWT_SECRET:?JWT_SECRET must be set in .env (openssl rand -hex 32)} + OVPMON_API_PORT: 5001 + OVPMON_PROFILER_DB_PATH: /app/db/ovpn_profiler.db + OVPMON_OPENVPN_MONITOR_DB_PATH: /app/db/openvpn_monitor.db + OVPMON_OPENVPN_MONITOR_LOG_PATH: /var/log/openvpn/openvpn-status.log + OVPMON_LOGGING_LEVEL: INFO + # Initial admin: used only while the users table is empty (remove after first start) + OVPMON_INITIAL_ADMIN_USER: ${OVPMON_INITIAL_ADMIN_USER:-} + OVPMON_INITIAL_ADMIN_PASSWORD: ${OVPMON_INITIAL_ADMIN_PASSWORD:-} + OVPMON_CORS_ORIGINS: ${OVPMON_CORS_ORIGINS:-} + healthcheck: + # UI through Nginx, profiler root (FastAPI) and TCP connect to the Flask API + test: + - "CMD" + - "python" + - "-c" + - "import socket, urllib.request as u; u.urlopen('http://127.0.0.1/', timeout=3); u.urlopen('http://127.0.0.1:8000/', timeout=3); socket.create_connection(('127.0.0.1', 5001), 3).close()" + interval: 30s + timeout: 8s + retries: 3 + start_period: 60s + +volumes: + ovp_logs: + ovp_config: + ovp_pki: + ovp_client_config: + db_data: diff --git a/docker-compose.yml b/docker-compose.yml index a375bab..ff3d37e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,6 +2,8 @@ # Required: JWT_SECRET in .env (openssl rand -hex 32) # First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env # Optional: OVPMON_CORS_ORIGINS (comma-separated origins; off by default, UI is same-origin via Nginx) +# Optional: OVPMON_HTTP_PORT (host port of the UI, default 80), OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194) +# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Scenario1_Containers.md) x-secret: &jwt-secret OVPMON_API_SECRET_KEY: ${JWT_SECRET:?JWT_SECRET must be set in .env (openssl rand -hex 32)} @@ -12,7 +14,7 @@ services: container_name: ovp-ui restart: unless-stopped ports: - - "80:80" + - "${OVPMON_HTTP_PORT:-80}:80" depends_on: - app-api - app-profiler @@ -23,6 +25,13 @@ services: OVP_API_PORT: 5001 OVP_PROFILER_HOST: ovp-profiler OVP_PROFILER_PORT: 8000 + healthcheck: + # busybox wget exists in nginx:alpine + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 10s app-gatherer: build: @@ -41,6 +50,13 @@ services: OVPMON_OPENVPN_MONITOR_DB_PATH: /app/db/openvpn_monitor.db OVPMON_OPENVPN_MONITOR_LOG_PATH: /var/log/openvpn/openvpn-status.log OVPMON_LOGGING_LEVEL: INFO + healthcheck: + # Process check: the gatherer is PID 1 of its container (CMD python openvpn_gatherer_v3.py) + test: ["CMD", "python", "-c", "import sys; sys.exit(0 if b'openvpn_gatherer_v3.py' in open('/proc/1/cmdline', 'rb').read() else 1)"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 30s app-api: build: @@ -66,6 +82,13 @@ services: OVPMON_INITIAL_ADMIN_USER: ${OVPMON_INITIAL_ADMIN_USER:-} OVPMON_INITIAL_ADMIN_PASSWORD: ${OVPMON_INITIAL_ADMIN_PASSWORD:-} OVPMON_CORS_ORIGINS: ${OVPMON_CORS_ORIGINS:-} + healthcheck: + # TCP connect to the Flask port + test: ["CMD", "python", "-c", "import socket; socket.create_connection(('127.0.0.1', 5001), 3).close()"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 30s app-profiler: build: ./APP_PROFILER @@ -79,7 +102,7 @@ services: - "/dev/net/tun:/dev/net/tun" ports: # VPN port only; the profiler API (8000) is reached through app-ui - - "1194:1194/udp" + - "${OVPMON_VPN_PORT:-1194}:1194/udp" expose: - "8000" volumes: @@ -94,6 +117,13 @@ services: <<: *jwt-secret OVPMON_PROFILER_DB_PATH: /app/db/ovpn_profiler.db OVPMON_CORS_ORIGINS: ${OVPMON_CORS_ORIGINS:-} + healthcheck: + # GET / of the FastAPI app must answer 200 + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/', timeout=3)"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 40s networks: ovp-net: