Compare commits

...
3 Commits
Author SHA1 Message Date
ayurishchevandClaude Sonnet 5.5 4abd2044f0 Scenario 2: install and update as system services (Alpine, Debian, Ubuntu)
- deploy/native: install.sh, update.sh (backup, new code prepared aside,
  stop services, separate DB migration phase, start, automatic rollback;
  OpenVPN keeps running), backup.sh, restore.sh, build-ui.sh (Node 20
  container), lib.sh OS adapter (OpenRC and systemd).
- Root helper reads /etc/ovpmon/helper.conf (service manager, unit, config
  path), validated strictly; process.py/server.py honour OVPMON_RUNTIME,
  OVPMON_OPENVPN_SERVICE, OVPMON_OPENVPN_CONFIG. Debian/Ubuntu use
  openvpn-server@server and /etc/openvpn/server/server.conf.
- Service definitions rewritten (systemd, OpenRC). Fixes found by real runs:
  no seccomp-based options in the profiler unit (they imply NoNewPrivileges
  and break setuid doas); OpenRC start_pre extends PATH instead of
  replacing it; helper syntax check works on a read-only tree.
- Verified in containers with real init systems (Debian 12, Ubuntu 24.04,
  Alpine 3.23): install, PKI/server config/OpenVPN start, update on
  pre-versioned databases, rollback, backup/restore.
- Test: test_helper_config.py. Docs: Scenario 2 guide, change summary,
  README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-05 10:45:24 +03:00
ayurishchevandClaude Sonnet 5.5 1c49d0b9c2 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 <noreply@anthropic.com>
2026-10-05 09:24:55 +03:00
ayurishchevandClaude Sonnet 5.5 e556d6d4b9 Database migrations with backup, integrity checks and downgrade protection
- Profiler and monitoring: schema_migrations table, additive ordered
  migrations, single write lock, integrity check, consistent backup via
  the SQLite backup API (newest 5 kept), row-count verification before
  commit, refusal to start on a database newer than the code.
- Profiler baseline migration is generated from the models and adds every
  missing column (replaces ensure_columns and the manual add_*.py scripts).
- migrate.py in each component (--check exit 0/2/1, --db); services migrate
  at start, OVPMON_AUTO_MIGRATE=0 only checks.
- Tests: test_migrations.py per component; verified on databases created by
  the code of commit 3836049 and on the live stand.
- Docs: Database_Migrations reference, change summary, deployment
  scenarios plan, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-05 08:37:38 +03:00
53 changed files with 6985 additions and 432 deletions

No files matched your search

+36
View File
@@ -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
+5
View File
@@ -1 +1,6 @@
.DS_Store
.env
backups/
.ovpmon-deploy
.ovpmon-lock/
deploy/native/ui-dist.tar.gz
+7 -110
View File
@@ -3,6 +3,8 @@ import configparser
import os
import logging
import migrations
class DatabaseManager:
def __init__(self, config_file='config.ini'):
self.config_file = config_file
@@ -26,7 +28,7 @@ class DatabaseManager:
return sqlite3.connect(self.db_path)
def init_database(self):
"""Initialize the database schema"""
"""Initialize the database schema (applies pending migrations)"""
# Create directory if needed
db_dir = os.path.dirname(self.db_path)
if db_dir and not os.path.exists(db_dir):
@@ -37,112 +39,7 @@ class DatabaseManager:
self.logger.info(f"Using database: {self.db_path}")
conn = self.get_connection()
cursor = conn.cursor()
def _column_exists(table, column):
cursor.execute(f"PRAGMA table_info({table})")
return any(row[1] == column for row in cursor.fetchall())
def _ensure_column(table, column, type_def):
if not _column_exists(table, column):
self.logger.info(f"Adding missing column {column} to table {table}")
cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}")
try:
# 1. Clients Table
cursor.execute('''
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
common_name TEXT UNIQUE NOT NULL,
real_address TEXT,
status TEXT DEFAULT 'Active',
total_bytes_received INTEGER DEFAULT 0,
total_bytes_sent INTEGER DEFAULT 0,
last_bytes_received INTEGER DEFAULT 0,
last_bytes_sent INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 2. Raw Usage History
cursor.execute('''
CREATE TABLE IF NOT EXISTS usage_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_id INTEGER,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
bytes_received INTEGER,
bytes_sent INTEGER,
bytes_received_rate_mbps REAL,
bytes_sent_rate_mbps REAL,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)')
# 2.1 Active Sessions (Temporary state table)
cursor.execute('''
CREATE TABLE IF NOT EXISTS active_sessions (
client_id INTEGER,
common_name TEXT,
real_address TEXT,
bytes_received INTEGER,
bytes_sent INTEGER,
connected_since TIMESTAMP,
last_seen TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
# 2.2 Users and Auth
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
totp_secret TEXT,
is_2fa_enabled INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 2.3 Login Attempts (Brute-force protection)
cursor.execute('''
CREATE TABLE IF NOT EXISTS login_attempts (
ip_address TEXT PRIMARY KEY,
attempts INTEGER DEFAULT 0,
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 3. Aggregated Stats Tables
tables = ['stats_5min', 'stats_15min', 'stats_hourly', 'stats_6h', 'stats_daily']
for table in tables:
cursor.execute(f'''
CREATE TABLE IF NOT EXISTS {table} (
timestamp TEXT NOT NULL,
client_id INTEGER NOT NULL,
bytes_received INTEGER DEFAULT 0,
bytes_sent INTEGER DEFAULT 0,
PRIMARY KEY (timestamp, client_id),
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
cursor.execute(f'CREATE INDEX IF NOT EXISTS idx_{table}_ts ON {table}(timestamp)')
# 4. Migrations (Ensure columns in existing tables)
# If users table existed but was old, ensure it has 2FA columns
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if cursor.fetchone():
_ensure_column('users', 'totp_secret', 'TEXT')
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
conn.commit()
self.logger.info("Database initialized with full schema and migrations")
except Exception as e:
self.logger.error(f"Database initialization error: {e}")
finally:
conn.close()
# Schema creation and upgrades live in migrations.py (versioned, with a backup before
# any change). Exits with a clear message if the database is newer than this code or
# migrations are pending while OVPMON_AUTO_MIGRATE=0.
migrations.startup_or_exit(self.db_path)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Apply pending database migrations (or only check for them).
python migrate.py apply pending migrations (backup first)
python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new
python migrate.py --db PATH use this database file instead of the configured one
Run it from the component directory with the component's virtualenv, like the service.
The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0).
"""
import argparse
import logging
import sys
import migrations
from db import DatabaseManager
EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2
def default_db_path():
return DatabaseManager().db_path
def main(argv=None):
parser = argparse.ArgumentParser(description="Database schema migrations")
parser.add_argument("--check", action="store_true",
help="only report: exit 0 = up to date, 2 = pending, 1 = error")
parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
db_path = args.db or default_db_path()
try:
st = migrations.status(db_path)
if st.too_new:
raise migrations._too_new_error(st)
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
if args.check:
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
if not st.pending:
print("Pending: none, up to date")
return EXIT_OK
print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending))
return EXIT_PENDING
before = st.current
report = migrations.run(db_path)
except migrations.MigrationError as e:
print(f"ERROR: {e}", file=sys.stderr)
return EXIT_ERROR
print(f"Schema version: {before} -> {report.version}")
if report.applied:
print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied))
else:
print("Applied: nothing, already up to date")
print(f"Backup: {report.backup or 'none'}"
+ (" (new database)" if report.created else ""))
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())
+467
View File
@@ -0,0 +1,467 @@
"""Versioned, additive-only schema migrations for the component's SQLite database.
The generic part (everything above "Migrations of this component") is the same in
APP_CORE/migrations.py and APP_PROFILER/migrations.py: the components have separate
build contexts and virtualenvs, so each carries its own copy. Keep them in sync.
Safety rules:
- a migration only adds (tables, columns, indexes); it never drops or rewrites data;
- before the first change a consistent backup is made with the SQLite backup API
('<db>.bak-<UTC timestamp>'), unless the database is brand new;
- every migration runs in its own savepoint inside one write-locked transaction, so
two processes starting at the same time cannot race (the second one waits, then
finds nothing pending);
- afterwards PRAGMA integrity_check and the row counts of all pre-existing tables are
compared with the backup; on a mismatch everything is rolled back;
- a database with a higher schema version than the code knows is never touched.
"""
import logging
import os
import re
import sqlite3
import stat
import sys
import urllib.parse
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Optional
logger = logging.getLogger(__name__)
BACKUPS_KEEP = 5 # number of '<db>.bak-*' files kept per database
LOCK_TIMEOUT = 60 # seconds a second process waits for the migration lock
class MigrationError(Exception):
"""A migration could not be applied or verified."""
class SchemaTooNew(MigrationError):
"""The database was migrated by a newer release than this code."""
class MigrationPending(MigrationError):
"""Migrations are pending but automatic migration is disabled."""
@dataclass
class Migration:
version: int
name: str
apply: Callable[[sqlite3.Connection], None] # runs inside a transaction, no commit
@dataclass
class Status:
db_path: str
exists: bool
fresh: bool # no tables and no recorded migrations
applied: dict = field(default_factory=dict) # version -> name
pending: list = field(default_factory=list) # [Migration]
too_new: Optional[int] = None # highest version if above the code's
@property
def current(self):
return max(self.applied) if self.applied else 0
@dataclass
class Report:
db_path: str
version: int # schema version after the run
applied: list = field(default_factory=list) # [(version, name)] applied by this run
backup: Optional[str] = None
created: bool = False # the database was new and got the current schema
def latest_version():
return max((m.version for m in MIGRATIONS), default=0)
def _resolve_path(target):
"""Accept a path or a SQLAlchemy engine."""
if isinstance(target, (str, os.PathLike)):
return os.fspath(target)
url = getattr(target, "url", None)
if url is not None and url.database:
return url.database
raise TypeError(f"Cannot get a database path from {target!r}")
def _quote(name):
return '"' + name.replace('"', '""') + '"'
def _tables(conn):
rows = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' "
"AND substr(name, 1, 7) != 'sqlite_' ORDER BY name")
return [r[0] for r in rows]
def _read_status(conn, db_path):
tables = _tables(conn)
applied = {}
if "schema_migrations" in tables:
applied = {v: n for v, n in conn.execute("SELECT version, name FROM schema_migrations")}
known = latest_version()
too_new = max(applied) if applied and max(applied) > known else None
pending = sorted((m for m in MIGRATIONS if m.version not in applied), key=lambda m: m.version)
fresh = not [t for t in tables if t != "schema_migrations"] and not applied
return Status(db_path, True, fresh, applied, pending, too_new)
def _too_new_error(st):
return SchemaTooNew(
f"Database {st.db_path} has schema version {st.too_new}, but this release only knows "
f"versions up to {latest_version()}. It was migrated by a newer release. The database "
f"has not been touched and the service will not start. Install the newer release, or "
f"restore a matching backup ('{st.db_path}.bak-*') with the services stopped.")
def _quick_status(db_path):
"""Read-only look at the database, no lock and no changes. None if it cannot be read."""
if not os.path.exists(db_path):
return Status(db_path, False, True, {}, sorted(MIGRATIONS, key=lambda m: m.version))
uri = "file:%s?mode=ro" % urllib.parse.quote(os.path.abspath(db_path))
try:
conn = sqlite3.connect(uri, uri=True, timeout=LOCK_TIMEOUT)
try:
return _read_status(conn, db_path)
finally:
conn.close()
except sqlite3.Error:
return None
def status(target):
"""Report applied and pending migrations without changing anything."""
db_path = _resolve_path(target)
st = _quick_status(db_path)
if st is None:
raise MigrationError(f"Cannot read database {db_path} (not a SQLite database, or locked)")
return st
def _integrity_problems(conn):
rows = [r[0] for r in conn.execute("PRAGMA integrity_check")]
return [] if rows == ["ok"] else rows[:5]
def _row_counts(conn):
return {t: conn.execute(f"SELECT COUNT(*) FROM {_quote(t)}").fetchone()[0]
for t in _tables(conn)}
def _backup(conn, db_path):
"""Consistent copy through the SQLite backup API. Returns (path, row counts of the copy)."""
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
dest = f"{db_path}.bak-{stamp}"
n = 0
while os.path.exists(dest):
n += 1
dest = f"{db_path}.bak-{stamp}-{n}"
tmp = dest + ".part"
try:
dst = sqlite3.connect(tmp)
# A separate read-only connection: the backup API stalls when the source connection
# itself holds the write lock. Nothing has been modified yet, so the copy is consistent.
src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=LOCK_TIMEOUT)
try:
src.backup(dst)
problems = _integrity_problems(dst)
if problems:
raise MigrationError("backup copy failed the integrity check: " + "; ".join(problems))
counts = _row_counts(dst)
finally:
src.close()
dst.close()
# The copy holds the same secrets as the database: same permissions
os.chmod(tmp, stat.S_IMODE(os.stat(db_path).st_mode))
os.replace(tmp, dest)
except Exception as e:
try:
os.remove(tmp)
except OSError:
pass
raise MigrationError(f"Cannot back up {db_path} ({e}). Nothing was changed.") from e
logger.info(f"Database backup created: {dest}")
return dest, counts
def _prune_backups(db_path, keep=BACKUPS_KEEP):
"""Keep the newest `keep` backups of this database only."""
directory = os.path.dirname(os.path.abspath(db_path))
pattern = re.compile(re.escape(os.path.basename(db_path)) + r"\.bak-(\d{8}T\d{6})(?:-(\d+))?$")
found = []
for name in os.listdir(directory):
m = pattern.match(name)
if m:
found.append((m.group(1), int(m.group(2) or 0), name))
found.sort()
for _, _, name in (found[:-keep] if keep > 0 else found):
try:
os.remove(os.path.join(directory, name))
logger.info(f"Old database backup removed: {name}")
except OSError as e:
logger.warning(f"Cannot remove old backup {name}: {e}")
def _stamp(conn, migration):
conn.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(migration.version, migration.name,
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")))
def run(target, fresh_schema=None):
"""Apply pending migrations to the database (path or SQLAlchemy engine).
fresh_schema(conn), if given, creates the complete current schema of a brand-new
database; all migrations are then recorded as applied without running them.
Raises SchemaTooNew / MigrationError; returns a Report."""
db_path = _resolve_path(target)
if fresh_schema is None:
fresh_schema = FRESH_SCHEMA
# Fast path: nothing to do, no lock, no write
st = _quick_status(db_path)
if st is not None:
if st.too_new:
raise _too_new_error(st)
if not st.pending:
return Report(db_path, st.current)
db_dir = os.path.dirname(db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
try:
conn = sqlite3.connect(db_path, timeout=LOCK_TIMEOUT, isolation_level=None)
try:
report = _run_locked(conn, db_path, fresh_schema)
finally:
conn.close()
except sqlite3.Error as e:
raise MigrationError(f"Database error while migrating {db_path}: {e}") from e
if report.backup:
_prune_backups(db_path)
return report
def _run_locked(conn, db_path, fresh_schema):
# The write lock is taken before anything is read or changed: a second process
# waits here, and then finds nothing pending (and makes no second backup)
conn.execute("BEGIN IMMEDIATE")
try:
st = _read_status(conn, db_path)
if st.too_new:
raise _too_new_error(st)
if not st.pending:
conn.execute("ROLLBACK")
return Report(db_path, st.current)
problems = _integrity_problems(conn)
if problems:
raise MigrationError(
f"Integrity check failed for {db_path}: {'; '.join(problems)}. Nothing was changed.")
backup, before = None, {}
if not st.fresh:
backup, before = _backup(conn, db_path)
where = f"backup: {backup}" if backup else "new database, no backup needed"
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations ("
"version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)")
applied = []
if st.fresh and fresh_schema is not None:
fresh_schema(conn)
for m in st.pending:
_stamp(conn, m)
applied.append((m.version, m.name))
else:
for m in st.pending:
logger.info(f"Applying migration {m.version} ({m.name}) to {db_path}")
conn.execute("SAVEPOINT migration")
try:
m.apply(conn)
_stamp(conn, m)
except Exception as e:
conn.execute("ROLLBACK TO migration")
conn.execute("RELEASE migration")
# Migrations completed before this one stay (each is complete in itself)
conn.execute("COMMIT" if applied else "ROLLBACK")
raise MigrationError(
f"Migration {m.version} ({m.name}) failed and was rolled back: {e} "
f"[{where}]. The service will not start; fix the cause and run migrate.py "
f"again.") from e
conn.execute("RELEASE migration")
applied.append((m.version, m.name))
# Verify before the commit: on any mismatch nothing is kept
problems = _integrity_problems(conn)
if problems:
raise MigrationError(
f"Integrity check failed after migration of {db_path}: {'; '.join(problems)}. "
f"The changes were rolled back. Backup: {backup or 'none (new database)'}")
after = _row_counts(conn)
for table, count in before.items():
if table == "schema_migrations":
continue # the bookkeeping table is expected to grow
if after.get(table) != count:
raise MigrationError(
f"Row count of table '{table}' changed during migration ({count} -> "
f"{after.get(table)}) in {db_path}. The changes were rolled back. "
f"Backup: {backup}")
conn.execute("COMMIT")
for version, name in applied:
logger.info(f"Migration {version} ({name}) applied to {db_path} [{where}]")
return Report(db_path, applied[-1][0], applied, backup, st.fresh)
except BaseException:
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
def startup(target, fresh_schema=None):
"""Called when a service starts. Applies pending migrations, or, with
OVPMON_AUTO_MIGRATE=0, only checks and refuses while any are pending."""
db_path = _resolve_path(target)
if os.getenv("OVPMON_AUTO_MIGRATE", "1").strip() == "0":
st = status(db_path)
if st.too_new:
raise _too_new_error(st)
if st.pending:
names = ", ".join(f"{m.version} ({m.name})" for m in st.pending)
raise MigrationPending(
f"Database {db_path} is at schema version {st.current}, pending migrations: "
f"{names}. Automatic migration is disabled (OVPMON_AUTO_MIGRATE=0): run "
f"'python migrate.py' first.")
return Report(db_path, st.current)
report = run(target, fresh_schema)
logger.info(f"Database {db_path}: schema version {report.version}")
return report
def startup_or_exit(target, fresh_schema=None):
"""startup() for service entry points: a clear message and a non-zero exit
instead of a traceback when the database must not be used."""
try:
return startup(target, fresh_schema)
except MigrationError as e:
logger.critical(str(e))
print(f"FATAL: {e}", file=sys.stderr)
sys.exit(1)
# --- Migrations of this component -------------------------------------------
def _m001_baseline(conn):
"""Schema of the releases before versioning (formerly DatabaseManager.init_database):
CREATE TABLE IF NOT EXISTS plus the 'add column if missing' steps. Idempotent."""
def _column_exists(table, column):
return any(row[1] == column for row in conn.execute(f"PRAGMA table_info({table})"))
def _ensure_column(table, column, type_def):
if not _column_exists(table, column):
logger.info(f"Adding missing column {column} to table {table}")
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {type_def}")
# 1. Clients Table
conn.execute('''
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
common_name TEXT UNIQUE NOT NULL,
real_address TEXT,
status TEXT DEFAULT 'Active',
total_bytes_received INTEGER DEFAULT 0,
total_bytes_sent INTEGER DEFAULT 0,
last_bytes_received INTEGER DEFAULT 0,
last_bytes_sent INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 2. Raw Usage History
conn.execute('''
CREATE TABLE IF NOT EXISTS usage_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_id INTEGER,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
bytes_received INTEGER,
bytes_sent INTEGER,
bytes_received_rate_mbps REAL,
bytes_sent_rate_mbps REAL,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
conn.execute('CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_history(timestamp)')
# 2.1 Active Sessions (Temporary state table)
conn.execute('''
CREATE TABLE IF NOT EXISTS active_sessions (
client_id INTEGER,
common_name TEXT,
real_address TEXT,
bytes_received INTEGER,
bytes_sent INTEGER,
connected_since TIMESTAMP,
last_seen TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
# 2.2 Users and Auth
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
totp_secret TEXT,
is_2fa_enabled INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 2.3 Login Attempts (Brute-force protection)
conn.execute('''
CREATE TABLE IF NOT EXISTS login_attempts (
ip_address TEXT PRIMARY KEY,
attempts INTEGER DEFAULT 0,
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# 3. Aggregated Stats Tables
tables = ['stats_5min', 'stats_15min', 'stats_hourly', 'stats_6h', 'stats_daily']
for table in tables:
conn.execute(f'''
CREATE TABLE IF NOT EXISTS {table} (
timestamp TEXT NOT NULL,
client_id INTEGER NOT NULL,
bytes_received INTEGER DEFAULT 0,
bytes_sent INTEGER DEFAULT 0,
PRIMARY KEY (timestamp, client_id),
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
conn.execute(f'CREATE INDEX IF NOT EXISTS idx_{table}_ts ON {table}(timestamp)')
# 4. Migrations (Ensure columns in existing tables)
# If users table existed but was old, ensure it has 2FA columns
if conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'").fetchone():
_ensure_column('users', 'totp_secret', 'TEXT')
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
MIGRATIONS = [
Migration(1, "baseline", _m001_baseline),
]
# No separate "fresh" schema: the baseline migration creates everything on a new database
FRESH_SCHEMA = None
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pytest
+246
View File
@@ -0,0 +1,246 @@
import glob
import hashlib
import sqlite3
import threading
import pytest
import migrations
from db import DatabaseManager
CLIENTS_SQL = """
CREATE TABLE clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
common_name TEXT UNIQUE NOT NULL,
real_address TEXT,
status TEXT DEFAULT 'Active',
total_bytes_received INTEGER DEFAULT 0,
total_bytes_sent INTEGER DEFAULT 0,
last_bytes_received INTEGER DEFAULT 0,
last_bytes_sent INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE usage_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_id INTEGER,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
bytes_received INTEGER,
bytes_sent INTEGER,
bytes_received_rate_mbps REAL,
bytes_sent_rate_mbps REAL,
FOREIGN KEY (client_id) REFERENCES clients (id)
);
CREATE INDEX idx_usage_ts ON usage_history(timestamp);
"""
STATS_SQL = "".join(f"""
CREATE TABLE {t} (
timestamp TEXT NOT NULL,
client_id INTEGER NOT NULL,
bytes_received INTEGER DEFAULT 0,
bytes_sent INTEGER DEFAULT 0,
PRIMARY KEY (timestamp, client_id),
FOREIGN KEY (client_id) REFERENCES clients (id)
);
CREATE INDEX idx_{t}_ts ON {t}(timestamp);
""" for t in ["stats_5min", "stats_15min", "stats_hourly", "stats_6h", "stats_daily"])
# Oldest schema: APP/db.py at commit c9af0a5 (no active_sessions, users, login_attempts),
# plus a legacy users table without the 2FA columns (the case _ensure_column was written for;
# no commit holds that table definition, it is reconstructed from the migration step)
OLDEST_SQL = CLIENTS_SQL + STATS_SQL + """
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
# Baseline: APP_CORE/db.py at commit 3836049 (identical to the schema today)
BASELINE_SQL = CLIENTS_SQL + STATS_SQL + """
CREATE TABLE active_sessions (
client_id INTEGER,
common_name TEXT,
real_address TEXT,
bytes_received INTEGER,
bytes_sent INTEGER,
connected_since TIMESTAMP,
last_seen TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
);
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
totp_secret TEXT,
is_2fa_enabled INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE login_attempts (
ip_address TEXT PRIMARY KEY,
attempts INTEGER DEFAULT 0,
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
ROWS_SQL = """
INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent)
VALUES (1, 'alice', '10.0.0.1:1000', 1000, 2000);
INSERT INTO clients (id, common_name, real_address, total_bytes_received, total_bytes_sent)
VALUES (2, 'bob', '10.0.0.2:2000', 3000, 4000);
INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent)
VALUES (1, '2026-01-01 10:00:00', 10, 20);
INSERT INTO usage_history (client_id, timestamp, bytes_received, bytes_sent)
VALUES (2, '2026-01-01 10:00:10', 30, 40);
INSERT INTO stats_5min (timestamp, client_id, bytes_received, bytes_sent)
VALUES ('2026-01-01 10:00:00', 1, 10, 20);
INSERT INTO users (id, username, password_hash) VALUES (1, 'admin', 'hash');
"""
SCHEMAS = {"oldest_c9af0a5": OLDEST_SQL, "baseline_3836049": BASELINE_SQL}
DATA_QUERIES = [
"SELECT * FROM clients ORDER BY id",
"SELECT * FROM usage_history ORDER BY id",
"SELECT * FROM stats_5min",
"SELECT id, username, password_hash FROM users",
]
@pytest.fixture(autouse=True)
def _auto_migrate(monkeypatch):
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
def make_db(path, schema_sql, extra_sql=ROWS_SQL):
conn = sqlite3.connect(path)
conn.executescript(schema_sql + extra_sql)
conn.commit()
conn.close()
def query(path, sql):
conn = sqlite3.connect(path)
try:
return conn.execute(sql).fetchall()
finally:
conn.close()
def table_names(path):
return {r[0] for r in query(path, "SELECT name FROM sqlite_master WHERE type='table'")}
def sha(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
@pytest.mark.parametrize("schema", SCHEMAS)
def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
db = str(tmp_path / "old.db")
make_db(db, SCHEMAS[schema])
before = [query(db, q) for q in DATA_QUERIES]
report = migrations.run(db)
# Original rows intact
assert [query(db, q) for q in DATA_QUERIES] == before
# Missing tables and columns are there, existing rows get the defaults
assert {"active_sessions", "users", "login_attempts"} <= table_names(db)
assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)]
# Stamped, and the backup is the untouched pre-migration copy
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")]
backups = glob.glob(db + ".bak-*")
assert backups == [report.backup]
assert [query(backups[0], q) for q in DATA_QUERIES] == before
assert "schema_migrations" not in table_names(backups[0])
assert query(backups[0], "PRAGMA integrity_check") == [("ok",)]
def test_second_run_is_a_noop(tmp_path):
db = str(tmp_path / "old.db")
make_db(db, OLDEST_SQL)
migrations.run(db)
first = sha(db)
report = migrations.run(db)
assert report.applied == [] and report.backup is None
assert len(glob.glob(db + ".bak-*")) == 1
assert sha(db) == first
def test_too_new_database_is_not_touched(tmp_path, monkeypatch):
db = str(tmp_path / "new.db")
make_db(db, BASELINE_SQL, ROWS_SQL + """
CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);
INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z');
""")
before = sha(db)
with pytest.raises(migrations.SchemaTooNew):
migrations.run(db)
# The service itself refuses to start: exit code 1, no traceback
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", db)
with pytest.raises(SystemExit) as exc:
DatabaseManager(str(tmp_path / "none.ini")).init_database()
assert exc.value.code == 1
assert sha(db) == before
assert glob.glob(db + ".bak-*") == []
assert len(query(db, "SELECT * FROM clients")) == 2
def test_fresh_database_gets_full_schema_without_backup(tmp_path):
db = str(tmp_path / "fresh.db")
report = migrations.run(db)
assert report.created and report.backup is None
assert glob.glob(db + ".bak-*") == []
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
"stats_5min", "stats_daily", "schema_migrations"} <= table_names(db)
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
db = str(tmp_path / "old.db")
make_db(db, OLDEST_SQL)
before = sha(db)
monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0")
with pytest.raises(migrations.MigrationPending, match="migrate.py"):
migrations.startup(db)
assert sha(db) == before
migrations.run(db)
migrations.startup(db) # up to date: allowed
def test_simultaneous_start_makes_one_backup(tmp_path):
db = str(tmp_path / "old.db")
make_db(db, OLDEST_SQL)
barrier = threading.Barrier(2)
reports, errors = [], []
def start():
try:
barrier.wait()
reports.append(migrations.run(db))
except Exception as e: # pragma: no cover
errors.append(e)
threads = [threading.Thread(target=start) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
assert errors == []
assert len(glob.glob(db + ".bak-*")) == 1
assert sorted(len(r.applied) for r in reports) == [0, 1]
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
+1 -12
View File
@@ -1,4 +1,4 @@
from sqlalchemy import create_engine, inspect, text
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
@@ -22,14 +22,3 @@ def get_db():
yield db
finally:
db.close()
def ensure_columns():
"""Idempotent 'add column if missing' migration for existing databases.
create_all() creates new tables but never alters existing ones."""
insp = inspect(engine)
if "user_profiles" not in insp.get_table_names():
return
existing = {c["name"] for c in insp.get_columns("user_profiles")}
if "note" not in existing:
with engine.begin() as conn:
conn.execute(text("ALTER TABLE user_profiles ADD COLUMN note TEXT"))
+7 -5
View File
@@ -7,17 +7,19 @@ import os
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database import engine, Base, ensure_columns
from database import db_path
import migrations
from routers import system, server, profiles, server_process
from utils.logging import setup_logging
from fastapi.middleware.cors import CORSMiddleware
# Create Database Tables
Base.metadata.create_all(bind=engine)
ensure_columns()
setup_logging()
# Create or upgrade the database schema (versioned migrations, backup before any change).
# Exits with a clear message if the database is newer than this code or migrations are
# pending while OVPMON_AUTO_MIGRATE=0.
migrations.startup_or_exit(db_path)
app = FastAPI(
title="OpenVPN Profiler API",
description="REST API for managing OpenVPN profiles and configuration",
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Apply pending database migrations (or only check for them).
python migrate.py apply pending migrations (backup first)
python migrate.py --check only report; exit 0 = up to date, 2 = pending, 1 = error / too new
python migrate.py --db PATH use this database file instead of the configured one
Run it from the component directory with the component's virtualenv, like the service.
The services apply pending migrations themselves at start (unless OVPMON_AUTO_MIGRATE=0).
"""
import argparse
import logging
import sys
import migrations
from database import db_path as configured_db_path
EXIT_OK, EXIT_ERROR, EXIT_PENDING = 0, 1, 2
def default_db_path():
return configured_db_path
def main(argv=None):
parser = argparse.ArgumentParser(description="Database schema migrations")
parser.add_argument("--check", action="store_true",
help="only report: exit 0 = up to date, 2 = pending, 1 = error")
parser.add_argument("--db", metavar="PATH", help="database file (default: from configuration)")
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
db_path = args.db or default_db_path()
try:
st = migrations.status(db_path)
if st.too_new:
raise migrations._too_new_error(st)
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
if args.check:
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
if not st.pending:
print("Pending: none, up to date")
return EXIT_OK
print("Pending: " + ", ".join(f"{m.version} ({m.name})" for m in st.pending))
return EXIT_PENDING
before = st.current
report = migrations.run(db_path)
except migrations.MigrationError as e:
print(f"ERROR: {e}", file=sys.stderr)
return EXIT_ERROR
print(f"Schema version: {before} -> {report.version}")
if report.applied:
print("Applied: " + ", ".join(f"{v} ({n})" for v, n in report.applied))
else:
print("Applied: nothing, already up to date")
print(f"Backup: {report.backup or 'none'}"
+ (" (new database)" if report.created else ""))
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())
+447
View File
@@ -0,0 +1,447 @@
"""Versioned, additive-only schema migrations for the component's SQLite database.
The generic part (everything above "Migrations of this component") is the same in
APP_CORE/migrations.py and APP_PROFILER/migrations.py: the components have separate
build contexts and virtualenvs, so each carries its own copy. Keep them in sync.
Safety rules:
- a migration only adds (tables, columns, indexes); it never drops or rewrites data;
- before the first change a consistent backup is made with the SQLite backup API
('<db>.bak-<UTC timestamp>'), unless the database is brand new;
- every migration runs in its own savepoint inside one write-locked transaction, so
two processes starting at the same time cannot race (the second one waits, then
finds nothing pending);
- afterwards PRAGMA integrity_check and the row counts of all pre-existing tables are
compared with the backup; on a mismatch everything is rolled back;
- a database with a higher schema version than the code knows is never touched.
"""
import logging
import os
import re
import sqlite3
import stat
import sys
import urllib.parse
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Optional
logger = logging.getLogger(__name__)
BACKUPS_KEEP = 5 # number of '<db>.bak-*' files kept per database
LOCK_TIMEOUT = 60 # seconds a second process waits for the migration lock
class MigrationError(Exception):
"""A migration could not be applied or verified."""
class SchemaTooNew(MigrationError):
"""The database was migrated by a newer release than this code."""
class MigrationPending(MigrationError):
"""Migrations are pending but automatic migration is disabled."""
@dataclass
class Migration:
version: int
name: str
apply: Callable[[sqlite3.Connection], None] # runs inside a transaction, no commit
@dataclass
class Status:
db_path: str
exists: bool
fresh: bool # no tables and no recorded migrations
applied: dict = field(default_factory=dict) # version -> name
pending: list = field(default_factory=list) # [Migration]
too_new: Optional[int] = None # highest version if above the code's
@property
def current(self):
return max(self.applied) if self.applied else 0
@dataclass
class Report:
db_path: str
version: int # schema version after the run
applied: list = field(default_factory=list) # [(version, name)] applied by this run
backup: Optional[str] = None
created: bool = False # the database was new and got the current schema
def latest_version():
return max((m.version for m in MIGRATIONS), default=0)
def _resolve_path(target):
"""Accept a path or a SQLAlchemy engine."""
if isinstance(target, (str, os.PathLike)):
return os.fspath(target)
url = getattr(target, "url", None)
if url is not None and url.database:
return url.database
raise TypeError(f"Cannot get a database path from {target!r}")
def _quote(name):
return '"' + name.replace('"', '""') + '"'
def _tables(conn):
rows = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' "
"AND substr(name, 1, 7) != 'sqlite_' ORDER BY name")
return [r[0] for r in rows]
def _read_status(conn, db_path):
tables = _tables(conn)
applied = {}
if "schema_migrations" in tables:
applied = {v: n for v, n in conn.execute("SELECT version, name FROM schema_migrations")}
known = latest_version()
too_new = max(applied) if applied and max(applied) > known else None
pending = sorted((m for m in MIGRATIONS if m.version not in applied), key=lambda m: m.version)
fresh = not [t for t in tables if t != "schema_migrations"] and not applied
return Status(db_path, True, fresh, applied, pending, too_new)
def _too_new_error(st):
return SchemaTooNew(
f"Database {st.db_path} has schema version {st.too_new}, but this release only knows "
f"versions up to {latest_version()}. It was migrated by a newer release. The database "
f"has not been touched and the service will not start. Install the newer release, or "
f"restore a matching backup ('{st.db_path}.bak-*') with the services stopped.")
def _quick_status(db_path):
"""Read-only look at the database, no lock and no changes. None if it cannot be read."""
if not os.path.exists(db_path):
return Status(db_path, False, True, {}, sorted(MIGRATIONS, key=lambda m: m.version))
uri = "file:%s?mode=ro" % urllib.parse.quote(os.path.abspath(db_path))
try:
conn = sqlite3.connect(uri, uri=True, timeout=LOCK_TIMEOUT)
try:
return _read_status(conn, db_path)
finally:
conn.close()
except sqlite3.Error:
return None
def status(target):
"""Report applied and pending migrations without changing anything."""
db_path = _resolve_path(target)
st = _quick_status(db_path)
if st is None:
raise MigrationError(f"Cannot read database {db_path} (not a SQLite database, or locked)")
return st
def _integrity_problems(conn):
rows = [r[0] for r in conn.execute("PRAGMA integrity_check")]
return [] if rows == ["ok"] else rows[:5]
def _row_counts(conn):
return {t: conn.execute(f"SELECT COUNT(*) FROM {_quote(t)}").fetchone()[0]
for t in _tables(conn)}
def _backup(conn, db_path):
"""Consistent copy through the SQLite backup API. Returns (path, row counts of the copy)."""
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
dest = f"{db_path}.bak-{stamp}"
n = 0
while os.path.exists(dest):
n += 1
dest = f"{db_path}.bak-{stamp}-{n}"
tmp = dest + ".part"
try:
dst = sqlite3.connect(tmp)
# A separate read-only connection: the backup API stalls when the source connection
# itself holds the write lock. Nothing has been modified yet, so the copy is consistent.
src = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=LOCK_TIMEOUT)
try:
src.backup(dst)
problems = _integrity_problems(dst)
if problems:
raise MigrationError("backup copy failed the integrity check: " + "; ".join(problems))
counts = _row_counts(dst)
finally:
src.close()
dst.close()
# The copy holds the same secrets as the database: same permissions
os.chmod(tmp, stat.S_IMODE(os.stat(db_path).st_mode))
os.replace(tmp, dest)
except Exception as e:
try:
os.remove(tmp)
except OSError:
pass
raise MigrationError(f"Cannot back up {db_path} ({e}). Nothing was changed.") from e
logger.info(f"Database backup created: {dest}")
return dest, counts
def _prune_backups(db_path, keep=BACKUPS_KEEP):
"""Keep the newest `keep` backups of this database only."""
directory = os.path.dirname(os.path.abspath(db_path))
pattern = re.compile(re.escape(os.path.basename(db_path)) + r"\.bak-(\d{8}T\d{6})(?:-(\d+))?$")
found = []
for name in os.listdir(directory):
m = pattern.match(name)
if m:
found.append((m.group(1), int(m.group(2) or 0), name))
found.sort()
for _, _, name in (found[:-keep] if keep > 0 else found):
try:
os.remove(os.path.join(directory, name))
logger.info(f"Old database backup removed: {name}")
except OSError as e:
logger.warning(f"Cannot remove old backup {name}: {e}")
def _stamp(conn, migration):
conn.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(migration.version, migration.name,
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")))
def run(target, fresh_schema=None):
"""Apply pending migrations to the database (path or SQLAlchemy engine).
fresh_schema(conn), if given, creates the complete current schema of a brand-new
database; all migrations are then recorded as applied without running them.
Raises SchemaTooNew / MigrationError; returns a Report."""
db_path = _resolve_path(target)
if fresh_schema is None:
fresh_schema = FRESH_SCHEMA
# Fast path: nothing to do, no lock, no write
st = _quick_status(db_path)
if st is not None:
if st.too_new:
raise _too_new_error(st)
if not st.pending:
return Report(db_path, st.current)
db_dir = os.path.dirname(db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
try:
conn = sqlite3.connect(db_path, timeout=LOCK_TIMEOUT, isolation_level=None)
try:
report = _run_locked(conn, db_path, fresh_schema)
finally:
conn.close()
except sqlite3.Error as e:
raise MigrationError(f"Database error while migrating {db_path}: {e}") from e
if report.backup:
_prune_backups(db_path)
return report
def _run_locked(conn, db_path, fresh_schema):
# The write lock is taken before anything is read or changed: a second process
# waits here, and then finds nothing pending (and makes no second backup)
conn.execute("BEGIN IMMEDIATE")
try:
st = _read_status(conn, db_path)
if st.too_new:
raise _too_new_error(st)
if not st.pending:
conn.execute("ROLLBACK")
return Report(db_path, st.current)
problems = _integrity_problems(conn)
if problems:
raise MigrationError(
f"Integrity check failed for {db_path}: {'; '.join(problems)}. Nothing was changed.")
backup, before = None, {}
if not st.fresh:
backup, before = _backup(conn, db_path)
where = f"backup: {backup}" if backup else "new database, no backup needed"
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations ("
"version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)")
applied = []
if st.fresh and fresh_schema is not None:
fresh_schema(conn)
for m in st.pending:
_stamp(conn, m)
applied.append((m.version, m.name))
else:
for m in st.pending:
logger.info(f"Applying migration {m.version} ({m.name}) to {db_path}")
conn.execute("SAVEPOINT migration")
try:
m.apply(conn)
_stamp(conn, m)
except Exception as e:
conn.execute("ROLLBACK TO migration")
conn.execute("RELEASE migration")
# Migrations completed before this one stay (each is complete in itself)
conn.execute("COMMIT" if applied else "ROLLBACK")
raise MigrationError(
f"Migration {m.version} ({m.name}) failed and was rolled back: {e} "
f"[{where}]. The service will not start; fix the cause and run migrate.py "
f"again.") from e
conn.execute("RELEASE migration")
applied.append((m.version, m.name))
# Verify before the commit: on any mismatch nothing is kept
problems = _integrity_problems(conn)
if problems:
raise MigrationError(
f"Integrity check failed after migration of {db_path}: {'; '.join(problems)}. "
f"The changes were rolled back. Backup: {backup or 'none (new database)'}")
after = _row_counts(conn)
for table, count in before.items():
if table == "schema_migrations":
continue # the bookkeeping table is expected to grow
if after.get(table) != count:
raise MigrationError(
f"Row count of table '{table}' changed during migration ({count} -> "
f"{after.get(table)}) in {db_path}. The changes were rolled back. "
f"Backup: {backup}")
conn.execute("COMMIT")
for version, name in applied:
logger.info(f"Migration {version} ({name}) applied to {db_path} [{where}]")
return Report(db_path, applied[-1][0], applied, backup, st.fresh)
except BaseException:
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
def startup(target, fresh_schema=None):
"""Called when a service starts. Applies pending migrations, or, with
OVPMON_AUTO_MIGRATE=0, only checks and refuses while any are pending."""
db_path = _resolve_path(target)
if os.getenv("OVPMON_AUTO_MIGRATE", "1").strip() == "0":
st = status(db_path)
if st.too_new:
raise _too_new_error(st)
if st.pending:
names = ", ".join(f"{m.version} ({m.name})" for m in st.pending)
raise MigrationPending(
f"Database {db_path} is at schema version {st.current}, pending migrations: "
f"{names}. Automatic migration is disabled (OVPMON_AUTO_MIGRATE=0): run "
f"'python migrate.py' first.")
return Report(db_path, st.current)
report = run(target, fresh_schema)
logger.info(f"Database {db_path}: schema version {report.version}")
return report
def startup_or_exit(target, fresh_schema=None):
"""startup() for service entry points: a clear message and a non-zero exit
instead of a traceback when the database must not be used."""
try:
return startup(target, fresh_schema)
except MigrationError as e:
logger.critical(str(e))
print(f"FATAL: {e}", file=sys.stderr)
sys.exit(1)
# --- Migrations of this component -------------------------------------------
import json # noqa: E402
def _dialect():
from sqlalchemy.dialects import sqlite
return sqlite.dialect()
def _metadata():
"""Model metadata (imported lazily: models import database, which stays free of this module)."""
import models # noqa: F401 registers the tables
from database import Base
return Base.metadata
def _default_clause(column):
"""'DEFAULT <literal>' for a scalar Python default, so existing rows get the value.
JSON/list defaults become '[]'. Anything not constant (timestamps) stays NULL."""
default = column.default
if default is None:
return ""
if getattr(default, "is_scalar", False):
value = default.arg
elif getattr(default, "is_callable", False):
try:
value = default.arg(None)
except Exception:
return ""
else:
return ""
if isinstance(value, bool):
return f" DEFAULT {int(value)}"
if isinstance(value, (int, float)):
return f" DEFAULT {value}"
if isinstance(value, str):
return " DEFAULT '%s'" % value.replace("'", "''")
if isinstance(value, (list, dict)):
return " DEFAULT '%s'" % json.dumps(value)
return ""
def _create_table(conn, table):
from sqlalchemy.schema import CreateIndex, CreateTable
dialect = _dialect()
conn.execute(str(CreateTable(table).compile(dialect=dialect)))
for index in table.indexes:
conn.execute(str(CreateIndex(index).compile(dialect=dialect)))
def _create_all(conn):
"""Same effect as Base.metadata.create_all(), on the migration's own connection."""
existing = set(_tables(conn))
for table in _metadata().sorted_tables:
if table.name not in existing:
_create_table(conn, table)
def _m001_baseline(conn):
"""Bring any database created by an earlier release up to the current models:
create missing tables, add missing columns (type and default from the metadata).
Replaces the standalone scripts add_columns.py and scripts/add_*.py and the old
ensure_columns(). Idempotent."""
dialect = _dialect()
existing = set(_tables(conn))
for table in _metadata().sorted_tables:
if table.name not in existing:
logger.info(f"Creating missing table {table.name}")
_create_table(conn, table)
continue
have = {r[1] for r in conn.execute(f"PRAGMA table_info({_quote(table.name)})")}
for column in table.columns:
if column.name in have:
continue
if column.primary_key:
raise MigrationError(f"Cannot add primary key column {table.name}.{column.name}")
ddl = (f"ALTER TABLE {_quote(table.name)} ADD COLUMN {_quote(column.name)} "
f"{column.type.compile(dialect=dialect)}{_default_clause(column)}")
logger.info(f"Adding missing column {column.name} to table {table.name}")
conn.execute(ddl)
MIGRATIONS = [
Migration(1, "baseline", _m001_baseline),
]
# A brand-new database gets the complete current schema at once (create_all equivalent)
FRESH_SCHEMA = _create_all
+1 -1
View File
@@ -16,7 +16,7 @@ def configure_server(db: Session = Depends(get_db)):
pki.require_server_ready(db)
# Generate to a temporary location or standard location
# As per plan, we behave like srvconf
output_path = "/etc/openvpn/server.conf"
output_path = process.openvpn_config_path()
# Unprivileged service: render to the staging dir, the root helper validates and installs it
if not process.is_container() and os.geteuid() != 0:
+22 -3
View File
@@ -9,7 +9,14 @@ logger = logging.getLogger(__name__)
def is_container():
"""
Checks if the application is running inside a Docker container.
OVPMON_RUNTIME=host|container overrides the detection (a service that runs on a host inside a
test container with /.dockerenv sets host).
"""
forced = os.environ.get("OVPMON_RUNTIME", "").strip().lower()
if forced == "host":
return False
if forced == "container":
return True
if os.path.exists('/.dockerenv'):
return True
try:
@@ -23,6 +30,18 @@ def is_container():
HELPER_PATH = "/usr/local/sbin/ovpmon-helper"
def openvpn_config_path():
"""OpenVPN config path for root/container mode (OVPMON_OPENVPN_CONFIG, default /etc/openvpn/server.conf).
Unprivileged mode only stages the file; the helper's own configuration decides where it is installed."""
return os.environ.get("OVPMON_OPENVPN_CONFIG", "").strip() or "/etc/openvpn/server.conf"
def openvpn_service_name():
"""Service name for the native root path (OVPMON_OPENVPN_SERVICE, default 'openvpn';
systemd hosts use 'openvpn-server@server')."""
return os.environ.get("OVPMON_OPENVPN_SERVICE", "").strip() or "openvpn"
def _run_helper(args):
"""Call the root-side helper through doas (used when this process is unprivileged).
Returns (returncode, parsed_json_or_None, raw_output)."""
@@ -68,7 +87,7 @@ def control_service(action: str):
if action not in ["start", "stop", "restart"]:
raise ValueError("Invalid action")
CONFIG_PATH = "/etc/openvpn/server.conf"
CONFIG_PATH = openvpn_config_path()
PID_FILE = "/run/openvpn.pid"
# In Container: Use direct execution to avoid OpenRC/cgroups issues
@@ -149,9 +168,9 @@ def control_service(action: str):
cmd = []
if os_type == "alpine":
cmd = ["rc-service", "openvpn", action]
cmd = ["rc-service", openvpn_service_name(), action]
else:
cmd = ["systemctl", action, "openvpn"]
cmd = ["systemctl", action, openvpn_service_name()]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
+83
View File
@@ -0,0 +1,83 @@
"""One test for the root helper's optional configuration (/etc/ovpmon/helper.conf).
The helper has no .py extension, so it is loaded by path. Nothing here touches a real service:
subprocess.run is replaced, the config files live in a temporary directory.
"""
import importlib.machinery
import importlib.util
import os
import subprocess
import types
import pytest
HELPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "DOCS", "General",
"privilege-separation", "ovpmon-helper")
def load_helper():
loader = importlib.machinery.SourceFileLoader("ovpmon_helper_under_test", HELPER)
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
def write_conf(tmp_path, text, mode=0o644):
p = tmp_path / "helper.conf"
p.write_text(text)
p.chmod(mode)
return str(p)
def test_helper_config(tmp_path, monkeypatch):
if not os.path.isfile(HELPER):
pytest.skip("the helper source (DOCS/General/privilege-separation/ovpmon-helper) is not part of this tree")
h = load_helper()
# 1. Without helper.conf the old hard-coded values apply
assert h.load_config(str(tmp_path / "missing.conf")) == {}
assert h.STAGED == "/var/lib/ovpmon/staging/server.conf"
assert h.TARGET == "/etc/openvpn/server.conf"
assert h.PKI_DIR == "/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa/pki"
assert h.CRL_SRC == h.PKI_DIR + "/crl.pem"
assert h.service_command("restart") == ["/sbin/rc-service", "openvpn", "restart"]
# 2. A valid file (here owned by the test user instead of root) is applied; PKI follows install_dir
own = os.getuid()
conf = write_conf(tmp_path, "[helper]\ninstall_dir = /srv/ovpmon\nservice_manager = systemd\n"
"config_path = /etc/openvpn/server/server.conf\n")
h.load_config(conf, owner_uid=own)
assert h.TARGET == "/etc/openvpn/server/server.conf"
assert h.PKI_DIR == "/srv/ovpmon/APP_PROFILER/easy-rsa/pki"
assert h.SERVICE_UNIT == "openvpn-server@server" # systemd default unit
# 3. Command lines: systemd -> systemctl <action> <unit>; openrc -> rc-service <unit> <action>
calls = []
def fake_run(cmd, **kwargs):
calls.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="")
monkeypatch.setattr(h, "subprocess", types.SimpleNamespace(run=fake_run))
assert h.service("stop") == (0, "ok")
assert calls[-1][1:] == ["stop", "openvpn-server@server"] and calls[-1][0].endswith("systemctl")
h.load_config(write_conf(tmp_path, "[helper]\nservice_unit = openvpn\n"), owner_uid=own)
h.service("status")
assert calls[-1] == ["/sbin/rc-service", "openvpn", "status"]
# 4. Unsafe or malformed files are rejected; so is a file that is not owned by root
for bad in ("[helper]\ninstall_dir = /opt/../etc\n",
"[helper]\nservice_unit = x; reboot\n",
"[helper]\nservice_unit = -rf\n",
"[helper]\nservice_manager = runit\n",
"[helper]\nconfig_path = /tmp/server.conf\n",
"[helper]\nstaged_path = /etc/passwd\n",
"[helper]\nunknown = 1\n",
"install_dir = /opt/x\n"):
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, bad), owner_uid=own)
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, "[helper]\n", mode=0o666), owner_uid=own) # group/world writable
with pytest.raises(h.Reject):
h.load_config(write_conf(tmp_path, "[helper]\n"), owner_uid=own + 1) # wrong owner
+199
View File
@@ -0,0 +1,199 @@
import glob
import hashlib
import os
import sqlite3
import tempfile
import pytest
# The DB path must be set before database.py is imported (the migration reads the models)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
import migrations
PKI_SQL = """
CREATE TABLE pki_settings (
id INTEGER NOT NULL, fqdn_ca VARCHAR, fqdn_server VARCHAR, easyrsa_dn VARCHAR,
easyrsa_req_country VARCHAR, easyrsa_req_province VARCHAR, easyrsa_req_city VARCHAR,
easyrsa_req_org VARCHAR, easyrsa_req_email VARCHAR, easyrsa_req_ou VARCHAR,
easyrsa_key_size INTEGER, easyrsa_ca_expire INTEGER, easyrsa_cert_expire INTEGER,
easyrsa_cert_renew INTEGER, easyrsa_crl_days INTEGER, easyrsa_batch BOOLEAN,
PRIMARY KEY (id)
);
CREATE INDEX ix_pki_settings_id ON pki_settings (id);
"""
SYSTEM_COLUMNS = """
id INTEGER NOT NULL, protocol VARCHAR, port INTEGER, vpn_network VARCHAR,
vpn_netmask VARCHAR, tunnel_type VARCHAR, split_routes JSON, duplicate_cn BOOLEAN,
crl_verify BOOLEAN, client_to_client BOOLEAN, user_defined_dns BOOLEAN, dns_servers JSON,
user_defined_cdscripts BOOLEAN, connect_script VARCHAR, disconnect_script VARCHAR,
management_interface BOOLEAN, management_interface_address VARCHAR, management_port INTEGER
"""
# Oldest schema: reconstructed from what the standalone scripts (add_columns.py,
# scripts/add_*.py) had to add later. Git history has no older models.py than fcb8f6b.
ANCIENT_SQL = PKI_SQL + f"""
CREATE TABLE system_settings ({SYSTEM_COLUMNS}, PRIMARY KEY (id));
CREATE INDEX ix_system_settings_id ON system_settings (id);
CREATE TABLE user_profiles (
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
revoked_at DATETIME, file_path VARCHAR, PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
"""
# Baseline: models.py at commit 3836049 (everything except user_profiles.note)
BASELINE_SQL = PKI_SQL + f"""
CREATE TABLE system_settings (
{SYSTEM_COLUMNS}, public_ip VARCHAR, tun_mtu INTEGER, mssfix INTEGER, PRIMARY KEY (id)
);
CREATE INDEX ix_system_settings_id ON system_settings (id);
CREATE TABLE user_profiles (
id INTEGER NOT NULL, username VARCHAR, status VARCHAR, created_at DATETIME,
revoked_at DATETIME, expiration_date DATETIME, is_revoked BOOLEAN, is_expired BOOLEAN,
file_path VARCHAR, PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_user_profiles_username ON user_profiles (username);
CREATE INDEX ix_user_profiles_id ON user_profiles (id);
"""
ROWS_SQL = """
INSERT INTO pki_settings (id, fqdn_ca, easyrsa_key_size) VALUES (1, 'my-ca', 4096);
INSERT INTO system_settings (id, protocol, port, tunnel_type) VALUES (1, 'tcp', 443, 'SPLIT');
INSERT INTO user_profiles (id, username, status, created_at, file_path)
VALUES (1, 'alice', 'active', '2026-01-01 10:00:00', '/p/alice.ovpn');
INSERT INTO user_profiles (id, username, status, created_at, file_path)
VALUES (2, 'bob', 'revoked', '2026-01-02 10:00:00', '/p/bob.ovpn');
"""
SCHEMAS = {"ancient": ANCIENT_SQL, "baseline_3836049": BASELINE_SQL}
@pytest.fixture(autouse=True)
def _auto_migrate(monkeypatch):
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
def make_db(path, schema_sql, extra_sql=ROWS_SQL):
conn = sqlite3.connect(path)
conn.executescript(schema_sql + extra_sql)
conn.commit()
conn.close()
def query(path, sql):
conn = sqlite3.connect(path)
try:
return conn.execute(sql).fetchall()
finally:
conn.close()
def columns(path, table):
return [r[1] for r in query(path, f"PRAGMA table_info({table})")]
def sha(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
@pytest.mark.parametrize("schema", SCHEMAS)
def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
db = str(tmp_path / "old.db")
make_db(db, SCHEMAS[schema])
users_before = query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles")
report = migrations.run(db)
# Original rows intact
assert query(db, "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
assert query(db, "SELECT fqdn_ca, easyrsa_key_size FROM pki_settings") == [("my-ca", 4096)]
assert query(db, "SELECT protocol, port, tunnel_type FROM system_settings") == [("tcp", 443, "SPLIT")]
# New columns exist; existing rows get the defaults
assert {"note", "is_revoked", "is_expired", "expiration_date"} <= set(columns(db, "user_profiles"))
assert {"public_ip", "tun_mtu", "mssfix"} <= set(columns(db, "system_settings"))
# Columns added now get the default; columns that already existed keep their values
flags = (0, 0) if schema == "ancient" else (None, None)
assert query(db, "SELECT is_revoked, is_expired, expiration_date, note FROM user_profiles") == [
flags + (None, None), flags + (None, None)]
assert query(db, "SELECT public_ip, tun_mtu, mssfix FROM system_settings") == [(None, None, None)]
# Stamped, and the backup is the untouched pre-migration copy
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")]
backups = glob.glob(db + ".bak-*")
assert backups == [report.backup]
assert query(backups[0], "SELECT id, username, status, created_at, file_path FROM user_profiles") == users_before
assert "note" not in columns(backups[0], "user_profiles")
assert query(backups[0], "PRAGMA integrity_check") == [("ok",)]
def test_second_run_is_a_noop(tmp_path):
db = str(tmp_path / "old.db")
make_db(db, BASELINE_SQL)
migrations.run(db)
first = sha(db)
report = migrations.run(db)
assert report.applied == [] and report.backup is None
assert len(glob.glob(db + ".bak-*")) == 1
assert sha(db) == first
def test_too_new_database_is_not_touched(tmp_path):
db = str(tmp_path / "new.db")
make_db(db, BASELINE_SQL, ROWS_SQL + """
CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);
INSERT INTO schema_migrations VALUES (9999, 'from the future', '2030-01-01T00:00:00Z');
""")
before = sha(db)
with pytest.raises(migrations.SchemaTooNew):
migrations.run(db)
with pytest.raises(migrations.SchemaTooNew):
migrations.startup(db)
assert sha(db) == before
assert glob.glob(db + ".bak-*") == []
assert len(query(db, "SELECT * FROM user_profiles")) == 2
def test_fresh_database_gets_full_schema_without_backup(tmp_path):
db = str(tmp_path / "fresh.db")
report = migrations.run(db)
assert report.created and report.backup is None
assert glob.glob(db + ".bak-*") == []
assert {"note", "is_revoked"} <= set(columns(db, "user_profiles"))
assert {"public_ip", "mssfix"} <= set(columns(db, "system_settings"))
assert "ix_user_profiles_username" in [r[1] for r in query(db, "PRAGMA index_list(user_profiles)")]
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
db = str(tmp_path / "old.db")
make_db(db, BASELINE_SQL)
before = sha(db)
monkeypatch.setenv("OVPMON_AUTO_MIGRATE", "0")
with pytest.raises(migrations.MigrationPending, match="migrate.py"):
migrations.startup(db)
assert sha(db) == before
migrations.run(db)
migrations.startup(db) # up to date: allowed
def test_default_clause_from_model_defaults():
import models
t = models.SystemSettings.__table__.c
assert migrations._default_clause(t.split_routes) == " DEFAULT '[]'"
assert migrations._default_clause(t.duplicate_cn) == " DEFAULT 0"
assert migrations._default_clause(t.port) == " DEFAULT 1194"
assert migrations._default_clause(t.protocol) == " DEFAULT 'udp'"
assert migrations._default_clause(t.tun_mtu) == ""
assert migrations._default_clause(models.UserProfile.__table__.c.created_at) == ""
@@ -51,7 +51,7 @@ Only the directives the template produces, each with checked arguments: `dev tun
- The supervisors stay root by design (they only respawn the service user's process).
- Helper checks resolve PKI paths at install time; a service-user-owned PKI directory could later swap a file for a symlink before OpenVPN (root) starts. Impact is limited to OpenVPN failing to parse or reading a key/cert-shaped file; keep the PKI directory owned by `ovpmon` only.
- CRL checking (`crl_verify`) works with the unprivileged API, see the section below.
- systemd deployments: same idea with `User=ovpmon`, a polkit/sudoers rule for the helper's fixed commands, and the same helper (replace `rc-service` with `systemctl`).
- systemd deployments (Debian, Ubuntu): implemented, see the section *Helper configuration and systemd* at the end.
- Rollback: restore `/etc/init.d/ovpmon-*` from `/root/app-bak/p2/`, `chown -R root:root` the data directories, restart the services (the helper and doas rules can stay).
## CRL publishing (`crl_verify`)
@@ -75,3 +75,9 @@ Results (throw-away second OpenVPN instance on another port/subnet running as `n
| `crl_verify=true` via API + `server/configure` | 200; config contains `crl-verify /etc/openvpn/crl.pem`, accepted by the helper; setting restored afterwards, live `server.conf` byte-identical to the original |
| Valid client with active CRL check | connects (`Initialization Sequence Completed`) |
| Revoke through the API, then reconnect | server sends `certificate revoked`, client is refused; no CRL read errors |
## Helper configuration and systemd (2026-10-05)
The helper reads an optional **`/etc/ovpmon/helper.conf`** (INI, section `[helper]`) with keys `install_dir`, `service_manager` (`openrc` or `systemd`), `service_unit`, `config_path`, `staged_path`. Without the file the built-in values apply, which are exactly the previous hard-coded ones (OpenRC `rc-service openvpn`, `/etc/openvpn/server.conf`, PKI below `/opt/OpenVPN-Monitoring-Simple`): existing hosts behave as before. The helper runs through `doas` with a stripped environment, so it reads its own file: it must be a regular file owned by root and not group/world writable, every value is validated strictly (absolute paths without `..`, `config_path` below `/etc/openvpn/`, `staged_path` below `/var/lib/ovpmon/`, unit name `^[A-Za-z0-9@._-]{1,64}$`, fixed set of managers), unknown keys and invalid values make the helper refuse. With `systemd` it runs `systemctl <action> <unit>` (default unit `openvpn-server@server`, fixed argument list and `PATH`); the `/etc/openvpn/openvpn.conf` link is created only for OpenRC. The `doas` rules file is unchanged (on Debian/Ubuntu the package is `opendoas`, rules in `/etc/doas.conf`).
`APP_PROFILER/services/process.py` honours `OVPMON_RUNTIME=host|container` (explicit override of the container detection) and, for the root (non-helper) path, `OVPMON_OPENVPN_SERVICE` (default `openvpn`) and `OVPMON_OPENVPN_CONFIG` (default `/etc/openvpn/server.conf`). Installation: [Scenario 2](../Deployment/Scenario2_System_Services.md). Test: `APP_PROFILER/test_helper_config.py`.
+43
View File
@@ -0,0 +1,43 @@
# Database migrations, phase 1 (2026-10-05)
Goal: a database from an older version survives an update without data loss. Phase 1 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md); the container and system-service scenarios follow as separate phases. Reference: [Database migrations](../General/Database_Migrations.md).
## Problem found
The Profiler added only the `note` column automatically; `public_ip`, `tun_mtu`, `mssfix`, `is_revoked`, `is_expired`, `expiration_date` were added by manual scripts, so an older database broke after an update. The monitoring database had no schema version, no backup and no integrity check.
## Changes
| Area | Change |
|---|---|
| `APP_PROFILER/migrations.py`, `APP_CORE/migrations.py` | Same engine in both components: table `schema_migrations`, ordered additive migrations, one write lock for all processes, integrity check, consistent backup (SQLite backup API, newest 5 kept), per-migration savepoint, verification (integrity and row counts against the backup) before the commit, downgrade protection |
| Profiler baseline migration | Generated from the SQLAlchemy models: creates missing tables and adds every missing column (with defaults for existing rows); replaces `ensure_columns()` and the manual scripts |
| Monitoring baseline migration | The former `init_database()` SQL, behaviour unchanged |
| `migrate.py` (both components) | Standalone phase: `migrate.py` applies, `--check` reports (exit 0 up to date, 2 pending, 1 error or database too new), `--db PATH` |
| Service start | Pending migrations are applied automatically after the backup. `OVPMON_AUTO_MIGRATE=0`: the service only checks and refuses to start while migrations are pending. A database newer than the code: the service refuses to start and does not touch it |
| Tests | `test_migrations.py` in each component (oldest reconstructed schema and baseline schema `3836049`; data intact, backup, stamp, no-op rerun, too-new database, race of two processes in the monitoring component) |
| Fix during review | The backup was taken through the connection that holds the write lock and hung; it now reads through a separate read-only connection (the data is not modified at that point, so the copy is consistent) |
## Verification (containers)
| Check | Result |
|---|---|
| pytest: migrations (Profiler 7, monitoring 7) and the three earlier Profiler tests | all passed |
| Databases created and filled by the real old code (commit `3836049`), then `migrate.py --check` | exit 2, pending baseline (both) |
| `migrate.py` | version 0 → 1, backup created, backups open, rows intact (profiles, settings, clients, usage, users) |
| Second run | `up to date`, no new backup, `--check` exit 0 |
| New Profiler on the migrated database | `GET /api/profiles` returns the old profiles |
| Database marked version 9999 | `migrate.py` exit 1 and the service refuses to start, file untouched |
| Live stand: restart of Profiler, API and gatherer on databases without a version | one backup per database, schema version 1, race between API and gatherer handled, data intact (profile kept) |
## Notes
- Behaviour change: the monitoring component used to swallow schema errors and keep starting; now a migration or integrity problem stops the start.
- Migrations only add; nothing is dropped or rewritten. Existing columns keep their values (for example `NULL` flags in old rows).
- Oldest schemas in the tests are partly reconstructed (git has no `models.py` before `fcb8f6b`).
- The service user needs write access to the database directory for the backup files.
- The old standalone scripts (`add_columns.py`, `scripts/add_*.py`) are superseded and left in place.
## Existing installations
Nothing to do: the first start of the new version backs up and migrates each database. For a controlled update run `migrate.py --check` and `migrate.py` from the component directory with the service stopped (the update scripts of the next phases do this as a separate step).
@@ -0,0 +1,77 @@
# Deployment scenarios and safe upgrade: plan (2026-10-05)
Goal: two documented, scripted scenarios.
- **Scenario 1, containers:** A) all components in one container; B) one container per component.
- **Scenario 2, system services, install and update:** A) Alpine, B) Debian, C) Ubuntu.
Priority: **an update must not damage the databases; a database must survive the migration** that a new version needs.
(The request lists "variant A" three times for scenario 2; this plan reads them as A, B, C.)
## What exists today
- Containers: `docker-compose.yml` (four services, variant B) and `DOCS/General/Deployment_Docker.md`. No single-container variant.
- System services: manual guide `Deployment_Native.md` (tested on Alpine only), systemd units, OpenRC scripts, privilege-separation helper with `doas`. No install or update script.
- Database migration is incomplete:
- Profiler: `create_all` plus `ensure_columns()` for the single column `note`. The other columns that models have (`public_ip`, `tun_mtu`, `mssfix`, `is_revoked`, `is_expired`, `expiration_date`, ...) are added only by standalone manual scripts in `APP_PROFILER/scripts` and `add_columns.py`. **A database from an older version breaks after an update unless someone runs them.**
- Monitoring (`APP_CORE/db.py`): `CREATE TABLE IF NOT EXISTS` plus `_ensure_column`. No schema version, no backup, no integrity check.
- Found blockers for Debian/Ubuntu:
1. `ovpmon-helper` calls `/sbin/rc-service openvpn` only; `process.py` uses `systemctl <action> openvpn` for non-Alpine, but on Debian/Ubuntu the real unit is `openvpn-server@server` and the config is expected in `/etc/openvpn/server/`.
2. `doas` is not installed by default (`opendoas` package; Ubuntu and Debian have it, version differs).
3. The UI build needs Node 20.19+ (Vite 7); Debian 12 and Ubuntu 22.04 ship older Node.
4. Nginx paths and Python versions differ (`/etc/nginx/http.d` on Alpine, `conf.d` or `sites-available` on Debian/Ubuntu).
## Steps
### 1. Database migration (foundation, done first)
- One migration mechanism for both databases: table `schema_migrations(version, applied_at)`, ordered idempotent migrations in code (`APP_PROFILER/migrations.py`, `APP_CORE/migrations.py`), applied in a transaction at startup and by the CLI `migrate` used in the update script.
- Migration 1 for the Profiler adds every column that the current models need and a pre-versioned database lacks (generated from the models, not hand-written); `note` moves into it. Migration for `APP_CORE` stamps the baseline after checking the existing schema.
- Safety rules:
- Before any migration: `PRAGMA integrity_check`, then a consistent backup through the SQLite backup API (`<db>.bak-<timestamp>`), kept.
- The migration never drops or rewrites data; only `ADD COLUMN` and `CREATE ... IF NOT EXISTS`, with defaults.
- A database **newer** than the application is not touched: the service refuses to start with a clear message (downgrade protection).
- After the migration: integrity check and row counts compared with the backup; on failure the backup is restored automatically by the update script.
- One `VERSION` file is written on install and update and logged on start.
- Test: one pytest builds a database with the **old** schema (taken from the baseline commit `3836049`), puts data into it, migrates, checks that the data is intact, the columns exist and a second run changes nothing.
### 2. Scenario 1: containers
- **B (distributed):** existing `docker-compose.yml`, hardened: named volumes kept on update, `.env` template, health checks, documented `docker compose pull/build && up -d`; the migration runs at the start of the Profiler and the API; pre-update volume backup command (`docker run ... tar`).
- **A (one container):** new `deploy/allinone/Dockerfile` and `docker-compose.allinone.yml`: Alpine, `supervisord` (or OpenRC-free supervisor) running nginx, gunicorn, gatherer, uvicorn and OpenVPN; same environment variables, one data volume (databases, PKI, client config, `/etc/openvpn`), ports 80 and 1194/udp.
- Script `deploy/docker/install.sh` and `update.sh` (idempotent: generates the secret, asks for the admin once, creates the backup, rebuilds, waits for health, prints the result).
- Document: `DOCS/Deployment/Scenario1_Containers.md` (A and B, install, update, backup and restore, rollback).
### 3. Scenario 2: system services (Alpine, Debian, Ubuntu)
- `deploy/native/install.sh` and `update.sh` with an OS adapter (detects Alpine / Debian / Ubuntu; package names, service manager, nginx paths, doas package):
- install: packages, `ovpmon` user, directories, venvs, environment file (random secret), services (OpenRC or systemd), root helper and doas rules, Nginx with a self-signed certificate, firewall hints;
- update: preflight (free space, version, services state) → backup (databases through the backup API, `/etc/ovpmon`, PKI, client config, `server.conf`, code version) → stop → new code → dependencies → **database migration** → UI → start → health check → on failure automatic rollback (code and databases) with a log.
- Debian/Ubuntu support in the code: `ovpmon-helper` and `process.py` choose the service manager (OpenRC `openvpn`, systemd `openvpn-server@server`) and the config location; the helper rules are checked on both.
- UI build: the script builds `dist` in a Node 20 container (or uses a prebuilt archive) so that the host does not need a recent Node.
- Document: `DOCS/Deployment/Scenario2_System_Services.md` with one section per OS, the update procedure, backup, rollback and a "what is preserved" table.
### 4. Verification (containers, no real host is touched)
- Scenario 1: build and start A and B, log in, initialize PKI, create a client; then **update from the old version** (baseline `3836049` data volume) to the new one and check that data and PKI survive.
- Scenario 2: run `install.sh` and then `update.sh` inside Alpine 3.23, Debian 12 and Ubuntu 24.04 containers with an init system (OpenRC / systemd); seed an old database and PKI before the update; check migration, health check and rollback (forced failure).
- Limit to state in the report: a container is not a full host (no real firewall, `tun` and service-manager details can differ); a final run on a VM of each OS is recommended before production.
### 5. Documentation
- The two scenario documents, links from `README.md`, `DOCS/General/Index.md`; the old `Deployment_Docker.md` and `Deployment_Native.md` become short pointers to the new documents; summary `DOCS/Changes/2026-10-05_Deployment_Scenarios.md`.
## Decisions for the owner
1. **Form:** scripts (`install.sh`, `update.sh`) plus documents (recommended), or documents only.
2. **Order of work:** database migration first, then Scenario 1, then Scenario 2 (recommended), or all in one step.
3. **Debian/Ubuntu service manager:** use `openvpn-server@server` and `/etc/openvpn/server/server.conf` (the distribution convention, recommended) instead of the Alpine-style `openvpn.conf`.
4. **UI build:** in a Node 20 container (recommended) or require Node 20+ on the host.
## Out of scope
High availability, PostgreSQL instead of SQLite, automatic OS package upgrades, Windows hosts, a real-host run (needs a VM).
## Decisions of the owner (2026-10-05)
1. Scripts `install.sh` and `update.sh` plus documents.
2. **The database migration phase is separated from the component update.** Phase 1 (this stage): migration mechanism, standalone `migrate` command, backup, checks, tests; it also runs by itself at service start. Phase 2: scenario 1 (containers). Phase 3: scenario 2 (system services). The update scripts call the migration as its own, separate step before the components are replaced or restarted.
3. Debian and Ubuntu: `openvpn-server@server` and `/etc/openvpn/server/server.conf`.
4. The UI is built in a Node 20 container.
## Phase 1 details (migration)
- Each component has its own build context and virtualenv, so the small migration helper is a separate copy in `APP_PROFILER/` and `APP_CORE/` (same behaviour).
- Service start applies pending migrations automatically (after the backup); `OVPMON_AUTO_MIGRATE=0` makes the service only check and refuse to start while migrations are pending (used by the update scripts). The standalone command: `migrate.py [--check]` in each component, exit codes 0 / 2 (pending) / 1 (error).
- Old standalone scripts (`add_columns.py`, `scripts/add_*.py`) stay in place and are marked as superseded in the documentation.
- Tests: one file per component, with the oldest and the baseline (`3836049`) schemas embedded as SQL.
@@ -0,0 +1,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.
@@ -0,0 +1,52 @@
# Scenario 2: system services, Alpine, Debian, Ubuntu (2026-10-05)
Phase 3 of [Deployment_Scenarios_PLAN](2026-10-05_Deployment_Scenarios_PLAN.md). Guide: [Scenario 2: system services](../Deployment/Scenario2_System_Services.md).
## What was added
| Area | Content |
|---|---|
| `deploy/native/` | `install.sh`, `update.sh`, `backup.sh`, `restore.sh`, `build-ui.sh`, `lib.sh` (OS adapter for Alpine/OpenRC and Debian/Ubuntu/systemd), nginx template |
| Install | Packages, `ovpmon` user, code, two virtualenvs, easy-rsa workspace, `/etc/ovpmon/env` (random secret, admin password shown once), root helper + `doas`, service definitions, OpenVPN prerequisites, nginx with TLS on 8088, health checks. The firewall is **not** touched (hints are printed) |
| Update (phases) | preflight, **backup** (databases through the SQLite backup API, configuration, PKI, client configs, code with virtualenvs, system files; verified), source update, new code and virtualenvs prepared aside, **stop services (OpenVPN keeps running)** and swap code, **database migration as its own step** with the new code, UI/helper/doas/service files, start and health checks, **automatic rollback** from any failure after the stop |
| UI build | `build-ui.sh` builds the UI in a Node 20 container into a tarball; the host needs no Node |
| Debian/Ubuntu support in code | Root helper reads `/etc/ovpmon/helper.conf` (install dir, service manager `openrc|systemd`, unit, config path), validated strictly, defaults equal the old Alpine behaviour; `process.py` and `routers/server.py` use `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE`, `OVPMON_OPENVPN_CONFIG`. Debian/Ubuntu: unit `openvpn-server@server`, config `/etc/openvpn/server/server.conf` |
| Service definitions | `DOCS/General/systemd/*.service`, `DOCS/General/openrc/*` rewritten (user `ovpmon`, environment file, real commands, no `--reload`); `Service_Management.md` updated |
| Docs | `DOCS/Deployment/Scenario2_System_Services.md`; `Deployment_Native.md` is a pointer |
| Test | `APP_PROFILER/test_helper_config.py` (helper configuration, defaults, rejected values, command lines) |
## Defects found by the real runs and fixed
| Defect | Fix |
|---|---|
| The profiler unit set `ProtectKernelTunables` and `ProtectKernelModules`: systemd implements them with seccomp and then sets NoNewPrivileges implicitly, so the setuid `doas` failed with "not installed setuid" and the root helper never ran | Both options removed from the profiler unit; the reason and the check are in the unit and in the guide |
| OpenRC scripts replaced `PATH` in `start_pre`, dropping `/lib/rc/bin`: OpenRC itself failed with `ebegin: not found` | `PATH` is extended, not replaced (all three scripts) |
| The helper syntax check used `py_compile`, which fails on a read-only source tree | `compile()` without writing a `.pyc` |
## Verification (containers with a real init: systemd on Debian 12 and Ubuntu 24.04, OpenRC on Alpine 3.23)
| Check | Debian 12 | Ubuntu 24.04 | Alpine 3.23 |
|---|---|---|---|
| `install.sh`, health checks, admin seed removed | ok | ok | ok |
| PKI init, server config through the root helper, client, note | ok | ok | ok |
| OpenVPN started through the helper | `openvpn-server@server` | `openvpn-server@server` | `openvpn` (OpenRC) |
| `update.sh` on databases without a version (real data) | ok, migration phase | ok | ok |
| OpenVPN untouched by the update | same PID | active | active |
| Rollback after an injected failure (broken new Profiler) | ok, data intact | not run | ok, data intact |
| `backup.sh`, change, `restore.sh` | not run | ok | not run |
| pytest: helper config test and the earlier tests | passed (all five test files) |||
Test containers, images and the UI archive were removed afterwards.
## Notes and limits
- A container is not a host: no real firewall, cgroup and init details can differ. Run the procedure once on a VM of the target OS before production. Test containers needed explicit help (an init process for OpenRC, writable cgroup); these are test artefacts, not product defects.
- Ubuntu 22.04 and other Debian or Alpine versions are not tested (the script warns and needs `--force`).
- Not tested: BusyBox `su` paths on hosts other than the test image, an upgrade of an existing real Alpine host through `update.sh` (adoption without a state file is implemented, not exercised), a source tree that is itself the install directory.
- Updates need access to the Python package index (fresh virtualenvs).
- `openvpn-server@server` shows as failed at boot until a `server.conf` exists.
- The version in the logs is `unknown` when `git` is not installed or the source is not a checkout.
## Existing installations
An existing Alpine host installed by hand can be adopted: `update.sh` records the state on the first run. Keep a copy of `/etc/doas.d/*` and the helper before the first update; the update replaces files that carry the deploy marker and reports, but does not overwrite, files that differ and have none.
+261
View File
@@ -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
JWT_SECRET=$(openssl rand -hex 32)
OVPMON_INITIAL_ADMIN_USER=admin
OVPMON_INITIAL_ADMIN_PASSWORD=<strong password>
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 `<project>_<volume>`; 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/<name>.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/<UTC timestamp>/*.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 `<name>: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 `<db>.bak-<UTC timestamp>` 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/<UTC timestamp>/
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/<timestamp>-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 `<db>.bak-<timestamp>` 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 <other> --project <same name>`. 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 <service>` (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 `<db>.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 `<db>.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 `<name>: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).
@@ -0,0 +1,404 @@
# Scenario 2: installation as system services (no containers)
Install and update on **Alpine (OpenRC)**, **Debian** and **Ubuntu** (systemd) with the scripts in `deploy/native/`. Nothing runs in a container, nothing needs Node on the host.
| Script | Purpose |
|---|---|
| `deploy/native/build-ui.sh` | builds the web UI in a Node 20 container into `ui-dist.tar.gz` (on any machine with Docker) |
| `deploy/native/install.sh` | first installation: packages, user, code, virtualenvs, configuration, services, nginx with TLS, health checks |
| `deploy/native/update.sh` | update with a verified backup, a separate database migration step and automatic rollback; `--rollback` for a manual one |
| `deploy/native/backup.sh` / `restore.sh` | stand-alone backup (cron friendly) and restore |
| `deploy/native/lib.sh` | shared functions and the OS adapter (sourced, not executed) |
All scripts run as root, support `-h`, log in one style (UTC time stamp, `=== PHASE n ===`) and append every log line to `/var/log/ovpmon-deploy.log`.
## What is installed
```
Browser --https:8088--> nginx --/--------------> /var/www/ovpmon (UI files)
--/api/----------> 127.0.0.1:5001 ovpmon-api (gunicorn, APP_CORE)
--/profiles-api/-> 127.0.0.1:8000 ovpmon-profiler (uvicorn, APP_PROFILER)
ovpmon-gatherer (APP_CORE): OpenVPN status log -> monitoring database
ovpmon-profiler (user ovpmon) --doas--> /usr/local/sbin/ovpmon-helper (root) --> server.conf, CRL, OpenVPN service
```
The three `ovpmon-*` services run as the unprivileged user `ovpmon`. Only the helper acts as root, through six fixed `doas` rules, and it validates everything it installs (see [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md)). The services do not require OpenVPN to be running: the VPN server is created and started from the UI.
## Supported systems
| System | Tested version | Service manager | Notes |
|---|---|---|---|
| Alpine | 3.23 | OpenRC | the original reference platform |
| Debian | 12 | systemd | |
| Ubuntu | 24.04 LTS | systemd | needs the `universe` repository (`easy-rsa`, `opendoas`) |
Another version of these systems is refused with a warning unless you pass `--force` to `install.sh` (the update only warns). Other distributions are not supported (a Debian derivative works with `--force` at your own risk).
## Requirements
- A host with root access, a working package manager and Internet access (packages, Python packages from PyPI).
- `/dev/net/tun` for OpenVPN (a normal VM has it; in containers it must be passed in).
- Free space: about 1 GB for the code and virtualenvs (the script checks it), plus room for the backups.
- Python 3.9 or newer (Alpine 3.23: 3.12, Debian 12: 3.11, Ubuntu 24.04: 3.12).
- Free TCP ports `5001`, `8000` (on `127.0.0.1`) and the HTTPS port (default `8088`).
- The UI archive (see below). **The host needs no Node.js.**
- GNU tar (on Alpine the package `tar`; the installer adds it).
## Building the UI (any machine with Docker)
```bash
deploy/native/build-ui.sh # -> deploy/native/ui-dist.tar.gz
deploy/native/build-ui.sh -o /tmp/ui.tar.gz # another output file
OVPMON_NODE_IMAGE=node:20-alpine deploy/native/build-ui.sh --image node:22-alpine
```
The script runs `npm ci` (or `npm install` without a lock file) and `npm run build` in `node:20-alpine`. `APP_UI` is mounted read-only and copied inside the container, so **nothing is written into the source tree** except the output file. The archive holds the content of `dist/` with `index.html` at its top level. Without Docker the script stops with a clear message; you can then build elsewhere (`npm install && npm run build` in `APP_UI`) and pack `dist/` yourself (`tar -czf ui-dist.tar.gz -C dist .`).
Copy the archive to the target host together with the repository checkout and pass it with `--ui-dist FILE`. `install.sh` also picks up `deploy/native/ui-dist.tar.gz` automatically when it exists; `update.sh` uses a UI archive only when you pass `--ui-dist` explicitly (it never reinstalls a stale one).
## Install
Clone the repository on the target host, put the UI archive next to the scripts and run, as root:
### Alpine (OpenRC)
```sh
apk add git # only to clone; the script installs the rest
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
### Debian 12
```sh
apt-get update && apt-get install -y git
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
### Ubuntu 24.04
```sh
sudo -i
apt-get update && apt-get install -y git # make sure the "universe" component is enabled
git clone <repository> /root/ovpmon-src && cd /root/ovpmon-src
deploy/native/install.sh --ui-dist /root/ui-dist.tar.gz
```
Options:
| Option | Meaning |
|---|---|
| `--prefix DIR` | install directory (default `/opt/OpenVPN-Monitoring-Simple`); letters, digits, `. _ - /` only |
| `--ui-dist FILE` | UI archive from `build-ui.sh`; without it a placeholder page is installed |
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
| `--admin-user NAME` | login of the first administrator (default `admin`) |
| `--force` | continue on an untested OS version |
### Differences between the systems
| | Alpine 3.23 | Debian 12 / Ubuntu 24.04 |
|---|---|---|
| Packages | `python3 py3-pip nginx openvpn easy-rsa iptables bash doas openssl curl tar` | `python3 python3-venv python3-pip nginx openvpn easy-rsa iptables opendoas openssl curl ca-certificates tar iproute2` |
| Service manager | OpenRC: `rc-service NAME start\|stop\|restart\|status`, `rc-update add NAME default` | systemd: `systemctl start\|stop\|restart\|status NAME`, `systemctl enable NAME` |
| Our service files | `/etc/init.d/ovpmon-api`, `-gatherer`, `-profiler` (`supervise-daemon`, `command_user=ovpmon:ovpmon`) | `/etc/systemd/system/ovpmon-*.service` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`) |
| Service logs | `/var/log/ovpmon/ovpmon-<name>.log` | `journalctl -u ovpmon-<name>` |
| OpenVPN service | `openvpn`; config `/etc/openvpn/server.conf`, plus the link `/etc/openvpn/openvpn.conf -> server.conf` | `openvpn-server@server`; config `/etc/openvpn/server/server.conf` |
| nginx site | `/etc/nginx/http.d/ovpmon.conf` | `/etc/nginx/conf.d/ovpmon.conf` |
| doas | package `doas`; our rules in `/etc/doas.d/ovpmon.conf` (own file, as on the existing hosts) | package `opendoas`; our rules as a marked block inside `/etc/doas.conf` |
| `ovpmon` user | `adduser -S`, shell `/sbin/nologin` | `useradd --system`, shell `/usr/sbin/nologin` |
The nginx site does not collide with the distribution defaults: the default server of Alpine and Debian listens on port 80, ours on 8088, and both distribution `nginx.conf` files include the directory above (the installer checks the `include` line).
### What `install.sh` does
| Phase | Content |
|---|---|
| 0 Preflight | root, OS and version, service manager present, no existing installation (otherwise it points to `update.sh`), source checkout complete, UI archive readable, ports free, free space |
| 1 Packages | the table above; GNU tar, Python 3.9+ with `venv` and `sqlite3`, `easy-rsa` checked |
| 2 User and directories | user `ovpmon`; `/var/lib/ovpmon` (+ `staging/`), `/var/log/ovpmon`, `/var/log/openvpn` (with `openvpn-status.log` as `root:ovpmon 640`), `/etc/openvpn/scripts`, `/etc/ovpmon` |
| 3 Code | `APP_CORE` and `APP_PROFILER` copied to the prefix (without venvs, databases, logs, Dockerfiles), plus the scripts and templates under `deploy/` and `DOCS/General/` (so the install directory can run `update.sh --source ...`); `VERSION` |
| 4 Virtualenvs and easy-rsa | two virtualenvs (`pip install -r requirements.txt`, plus `gunicorn` for `APP_CORE`), an import check, the easy-rsa workspace copied from `/usr/share/easy-rsa` into `APP_PROFILER/easy-rsa` (a real directory, never a symlink), code made root-owned and read-only |
| 5 Configuration | `/etc/ovpmon/env` (random secret, generated administrator), `/etc/ovpmon/helper.conf`, `/usr/local/sbin/ovpmon-helper`, doas rules and a **self-test** (`ovpmon` runs the helper through doas), forwarding via `/etc/sysctl.d`, OpenVPN prerequisites (Alpine: the `openvpn.conf` link; Debian/Ubuntu: `/etc/openvpn/server/`; the OpenVPN service is **enabled, not started**: there is no `server.conf` yet) |
| 6 Services, UI, nginx | the three service definitions installed and enabled, UI files to `/var/www/ovpmon`, a self-signed EC certificate (`/etc/ovpmon/tls/`, SAN: host name, detected IP, `127.0.0.1`, `localhost`), the nginx site, nginx enabled and reloaded |
| 7 Start and checks | services started; health checks (below) |
| 8 Administrator | when a user exists in the monitoring database, the seed is removed from `/etc/ovpmon/env` and `ovpmon-api` is restarted; if the database cannot be read or is empty the seed stays and a warning says so |
Health checks: the three services are running; `http://127.0.0.1:5001/` answers; `http://127.0.0.1:8000/` returns 200; `https://127.0.0.1:<port>/` (with `-k`) returns 200; `/api/v1/user/me` and `/profiles-api/config` through nginx return 401 without a token.
The final summary shows the URL, the certificate fingerprint, the paths and the **generated administrator password once**. The state is recorded in `/etc/ovpmon/deploy.state` (prefix, HTTPS port, OS, version, dates). If the script fails it is **safe to run again**: it resumes, keeps the existing secret, certificate, easy-rsa workspace and data.
Then in the UI: sign in, change the password and enable 2FA, **PKI Configuration -> Initialize PKI**, generate the server configuration, start the VPN server.
### Without the script (outline)
Create the `ovpmon` user and the directories, copy the code, build both virtualenvs, write `/etc/ovpmon/env`, `helper.conf` and the doas rules from the templates, install the service definitions (`DOCS/General/systemd/*.service` or `DOCS/General/openrc/ovpmon-*`; replace `/opt/OpenVPN-Monitoring-Simple` if you use another prefix), copy the UI, add the nginx site from `deploy/native/nginx/ovpmon.conf.template` (replace `@HTTPS_PORT@`, `@WEB_ROOT@`, `@TLS_CRT@`, `@TLS_KEY@`). The commands are exactly what `install.sh` runs; reading the script is the shortest reference.
## Layout: what is where, who owns it
| Item | Path | Owner, mode |
|---|---|---|
| Code | `<prefix>/APP_CORE`, `<prefix>/APP_PROFILER` | `root:root`, read-only for others |
| Virtualenvs | `<prefix>/APP_CORE/venv`, `<prefix>/APP_PROFILER/venv` | `root:root` |
| **PKI** (CA, keys, certificates, CRL) | `<prefix>/APP_PROFILER/easy-rsa` (real directory) | `ovpmon:ovpmon` 750 |
| **Client profiles** | `<prefix>/APP_PROFILER/client-config` (real directory) | `ovpmon:ovpmon` 750 |
| Profiler log | `<prefix>/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 |
| Shipped settings file | `<prefix>/APP_CORE/config.ini`, `<prefix>/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it |
| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` |
| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 |
| Service environment | `/etc/ovpmon/env` | `root:root` 600 |
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) |
| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 |
| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 |
| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` |
| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` |
| OpenVPN logs | `/var/log/openvpn/openvpn.log`, `openvpn-status.log` (`root:ovpmon` 640) | `root` |
| Service logs | `/var/log/ovpmon/` (OpenRC) or the journal (systemd) | `ovpmon` / systemd |
| UI files | `/var/www/ovpmon` | `root:root` |
| Backups | `/var/backups/ovpmon/<UTC timestamp>/` | `root:root` 700 |
| Deployment log | `/var/log/ovpmon-deploy.log` | `root:root` 600 |
The profiler resolves `easy-rsa/` and `client-config/` relative to its working directory (`APP_PROFILER`) and keeps `client-config/<name>.ovpn` as a relative path in its database; therefore both are real directories inside `APP_PROFILER` (a symlinked `client-config` breaks the real-path checks and the `clear_pki` cleanup).
## Environment file and helper configuration
`/etc/ovpmon/env` (`root:root` 600) is read by the init system as root and handed to the services. Lines are `KEY=VALUE` without quotes or spaces (systemd and OpenRC read the same file).
| Variable | Default written by `install.sh` | Meaning |
|---|---|---|
| `OVPMON_API_SECRET_KEY` | random, 64 hex characters | signing key of both APIs; changing it logs everybody out; keep it across updates |
| `OVPMON_API_HOST`, `OVPMON_API_PORT` | `127.0.0.1`, `5001` | informational: gunicorn is started with `-b 127.0.0.1:5001` |
| `OVPMON_OPENVPN_MONITOR_DB_PATH` | `/var/lib/ovpmon/openvpn_monitor.db` | monitoring database |
| `OVPMON_PROFILER_DB_PATH` | `/var/lib/ovpmon/ovpn_profiler.db` | profiler database |
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | `/var/log/openvpn/openvpn-status.log` | status log read by the gatherer |
| `OVPMON_LOGGING_LEVEL` | `INFO` | |
| `OVPMON_CORS_ORIGINS` | `https://<host>:<https-port>` | extra allowed origin (the UI is same-origin behind nginx) |
| `OVPMON_RUNTIME` | `host` | forces host mode (never "container"), needed when the host itself runs inside a container |
| `OVPMON_OPENVPN_SERVICE` | `openvpn` (Alpine) / `openvpn-server@server` | service name for the root (non-helper) path |
| `OVPMON_OPENVPN_CONFIG` | `/etc/openvpn/server.conf` / `/etc/openvpn/server/server.conf` | server config path for the root (non-helper) path |
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | generated | seed, only while the users table is empty; removed by `install.sh` after the first start |
| `OVPMON_AUTO_MIGRATE` | unset | `0` makes the services refuse to start while migrations are pending |
With the unprivileged profiler the API only stages `server.conf`; **the helper configuration decides where it is installed and which service is controlled.**
`/etc/ovpmon/helper.conf` (INI, section `[helper]`, `root:root`, not group/world writable, otherwise the helper refuses to run). Without the file the helper uses the built-in values of the Alpine layout.
| Key | Alpine (written) | Debian/Ubuntu (written) | Rule |
|---|---|---|---|
| `install_dir` | `/opt/OpenVPN-Monitoring-Simple` | same | absolute, no `..`; the PKI is `<install_dir>/APP_PROFILER/easy-rsa/pki` |
| `service_manager` | `openrc` | `systemd` | `openrc` or `systemd` |
| `service_unit` | `openvpn` | `openvpn-server@server` | `^[A-Za-z0-9@._-]{1,64}$`, not starting with `-` or `.` |
| `config_path` | `/etc/openvpn/server.conf` | `/etc/openvpn/server/server.conf` | absolute, below `/etc/openvpn/`, ends with `.conf` |
| `staged_path` | `/var/lib/ovpmon/staging/server.conf` | same | absolute, below `/var/lib/ovpmon/` |
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
## Firewall, NAT and forwarding (manual)
The scripts **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. You open the ports and give the VPN clients access yourself. Replace `eth0` with the uplink interface and `172.20.1.0/24` with the VPN subnet of the server settings.
```sh
# iptables: services
iptables -A INPUT -p tcp --dport 8088 -j ACCEPT # UI (your HTTPS port)
iptables -A INPUT -p udp --dport 1194 -j ACCEPT # OpenVPN (your VPN port)
# iptables: NAT and forwarding for the VPN clients
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o eth0 -j MASQUERADE
iptables -A FORWARD -i tun+ -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
```
nftables equivalent:
```sh
nft add table inet ovpmon
nft 'add chain inet ovpmon input { type filter hook input priority 0 ; }'
nft add rule inet ovpmon input tcp dport 8088 accept
nft add rule inet ovpmon input udp dport 1194 accept
nft 'add chain inet ovpmon forward { type filter hook forward priority 0 ; }'
nft add rule inet ovpmon forward iifname "tun*" oifname "eth0" accept
nft add rule inet ovpmon forward iifname "eth0" oifname "tun*" ct state established,related accept
nft 'add table ip ovpmon_nat'
nft 'add chain ip ovpmon_nat postrouting { type nat hook postrouting priority 100 ; }'
nft add rule ip ovpmon_nat postrouting ip saddr 172.20.1.0/24 oifname "eth0" masquerade
```
(Add the `input`/`forward` rules only when your firewall policy is `drop`; a chain with priority 0 and policy accept does not block anything on its own.)
Persistence:
| System | Make the rules survive a reboot |
|---|---|
| Alpine | `rc-service iptables save && rc-update add iptables` (rules in `/etc/iptables/rules-save`); nftables: `rc-update add nftables`, rules in `/etc/nftables.nft` |
| Debian / Ubuntu | `apt-get install iptables-persistent`, then `netfilter-persistent save`; nftables: put the rules in `/etc/nftables.conf` and `systemctl enable nftables` |
## Update
```sh
deploy/native/update.sh # run from the checkout with the new version
deploy/native/update.sh --ui-dist /root/ui-dist.tar.gz # also replace the UI files
deploy/native/update.sh --source /root/ovpmon-src --yes # another checkout, no questions
deploy/native/update.sh --no-pull # sources already in place / offline
deploy/native/update.sh --rollback # manual rollback to the newest backup
```
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix` and the HTTPS port come from `/etc/ovpmon/deploy.state`. The update needs access to PyPI for the new virtualenvs.
Each phase is logged separately:
| Phase | What happens | If it fails |
|---|---|---|
| 0 Preflight | installation present, no unfinished install, source checkout complete, UI archive readable, services state, databases found, free space (backup and new code) | nothing was changed |
| 1 **Backup** | verified backup in `/var/backups/ovpmon/<UTC timestamp>/` (see below) | the update is **refused**, nothing was changed |
| 2 Sources | `git pull --ff-only` of the source checkout (skipped with `--no-pull` or without git) | nothing was changed |
| 3 Prepare | new code copied to `<prefix>.new`, fresh virtualenvs with `pip install -r requirements.txt`, import check; new UI extracted next to the web root. **The running system is not touched** | nothing was changed |
| 4 Stop and swap | the three application services are stopped (**OpenVPN keeps running**, VPN users stay connected); a final consistent snapshot; each code directory is renamed to `<dir>.old-<time>`, the new one moved in; **PKI, client profiles, `profiler.log`, `config.ini` and any database files below the code directory are moved over, never replaced**; virtualenv paths fixed | automatic rollback |
| 5 **Database migration** | its own step, see below | automatic rollback, **nothing is started** |
| 6 Files | UI swap; helper; `helper.conf` (when missing); doas rules; service definitions; missing environment keys added (existing values never changed); nginx site; each replaced only when it differs and is managed by these scripts; units reloaded | automatic rollback |
| 7 Start | services started, health checks, helper self-test | automatic rollback |
| 8 Finish | the old code directories are removed (never one that still holds PKI data), the newest 5 backups kept, state recorded | |
The new `deploy/native/*.sh` take effect on the next run (the running script is not replaced).
### Database migration as its own step
After the services are stopped and the new code is in place, and **before anything is started**, `update.sh` runs for each database, with the **new** code, as user `ovpmon` and with the variables of `/etc/ovpmon/env` loaded:
| Database | Command (working directory) |
|---|---|
| Profiler | `APP_PROFILER/venv/bin/python migrate.py` in `<prefix>/APP_PROFILER` |
| Monitoring | `APP_CORE/venv/bin/python migrate.py` in `<prefix>/APP_CORE` |
For each one: `migrate.py --check` (exit 0 up to date, 2 pending, 1 error or database newer than the code), the migration when 2, and a second check. The reports are printed. A failure or a "too new" database aborts **before any service starts** and triggers the rollback. Migrations are additive, run after an integrity check and a consistent copy `<db>.bak-<UTC timestamp>` next to the database, and are verified afterwards; details in [Database migrations](../General/Database_Migrations.md). The migration also runs by itself when a service starts, so a manual file replacement is safe too; `update.sh` only makes it a visible, controlled step.
### Backup (phase 1, `backup.sh`)
```sh
deploy/native/backup.sh # backup into /var/backups/ovpmon/<UTC timestamp>/
deploy/native/backup.sh --stop # services stopped during the copy, started afterwards
deploy/native/backup.sh --keep 14 # afterwards keep the newest 14
```
Cron example (nightly, 14 kept): `30 3 * * * /opt/OpenVPN-Monitoring-Simple/deploy/native/backup.sh --keep 14 >> /var/log/ovpmon-backup.log 2>&1`.
| Content | File in the backup |
|---|---|
| both databases, consistent copies from the SQLite backup API (integrity-checked, owner and mode kept) | `db/monitor.db`, `db/profiler.db` |
| `/etc/ovpmon` (environment, helper configuration, certificate, state) | `etc-ovpmon.tar.gz` |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | `etc-openvpn.tar.gz` |
| PKI `APP_PROFILER/easy-rsa` | `easy-rsa.tar.gz` |
| client profiles `APP_PROFILER/client-config` | `client-config.tar.gz` |
| `APP_CORE` and `APP_PROFILER` including the virtualenvs (needed for rollback) | `code.tar.gz` |
| helper, service definitions, nginx site, sysctl file, doas file (Alpine) | `system.tar.gz` |
| doas block (Debian/Ubuntu) | `doas-block.txt` |
| UI files | `ui.tar.gz` |
| checksums, description, completion marker | `SHA256SUMS`, `MANIFEST`, `COMPLETE` |
Every archive is verified (`tar -tzf`), the checksums are checked and each database copy passes `PRAGMA integrity_check` before `COMPLETE` is written; **only a `COMPLETE` backup is ever used**. `update.sh` backs up twice: in phase 1, and again as a final snapshot once the services are stopped (the code archive is reused). The backup holds private keys, password hashes and the signing secret: the directory is mode 700, the files mode 600. Keep copies off the host.
### Restore
```sh
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z # asks, stops, saves the current state, restores
deploy/native/restore.sh /var/backups/ovpmon/20261005T101500Z --yes --start
```
It verifies the backup, stops the three application services, saves the **current state** to `/var/backups/ovpmon/<time>-pre-restore` (`OVPMON_NO_SAFETY_BACKUP=1` skips this), then restores code, databases, `/etc/ovpmon`, `/etc/openvpn`, PKI, client profiles, helper, service definitions, nginx site, UI and doas rules. A replaced database is kept as `<db>.failed-<time>`. OpenVPN is not stopped. On a new host run `install.sh` first, then `restore.sh`.
Manual equivalent (services stopped, paths for the default prefix):
```sh
B=/var/backups/ovpmon/20261005T101500Z
( cd $B && sha256sum -c SHA256SUMS )
tar -xzpf $B/code.tar.gz -C /opt/OpenVPN-Monitoring-Simple # after moving the current APP_CORE and APP_PROFILER aside
tar -xzpf $B/easy-rsa.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
tar -xzpf $B/client-config.tar.gz -C /opt/OpenVPN-Monitoring-Simple/APP_PROFILER
cp -p $B/db/profiler.db /var/lib/ovpmon/ovpn_profiler.db # the backup was made with the sqlite backup API
cp -p $B/db/monitor.db /var/lib/ovpmon/openvpn_monitor.db
tar -xzpf $B/etc-ovpmon.tar.gz -C / && tar -xzpf $B/etc-openvpn.tar.gz -C /
tar -xzpf $B/system.tar.gz -C / # helper, service definitions, nginx site
```
A single database can also be put back from its migration copy `<db>.bak-<time>` in `/var/lib/ovpmon`: stop the services, copy it over the database, start the OLD release.
### Automatic rollback and `--rollback`
On any failure from phase 4 on: the services are stopped, **code, databases, `/etc/ovpmon`, `/etc/openvpn`, helper, doas rules, service definitions, nginx site and UI files are restored from the backup of this run**, the services are started and checked, and the result is reported with the backup path.
How the code is restored: the current (new or half-swapped) code directories are renamed to `<dir>.rollback-<time>`, `code.tar.gz` is extracted (old code **and old virtualenvs**, so no Internet is needed), and the PKI and client profiles, which the update never replaced, are moved back from the directory that held them. They are restored from `easy-rsa.tar.gz` / `client-config.tar.gz` only if they are missing. The failed databases are kept as `<db>.failed-<time>`. If the rollback itself fails the message says where the backup is and how to retry (`update.sh --rollback` or `restore.sh`).
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Existing installations (adoption)
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
## What is preserved on update
| Item | On update |
|---|---|
| Databases | Kept in place, backed up twice (consistent copies), migrated additively with their own `<db>.bak-*` copy; restored automatically if the update fails after the stop |
| PKI (`APP_PROFILER/easy-rsa`): CA, keys, certificates, CRL | Moved, never replaced or deleted, backed up |
| Client profiles (`APP_PROFILER/client-config`) | Moved, never replaced or deleted, backed up |
| `/etc/ovpmon/env` (secret, DB paths) | Kept; only missing keys are added; copied into every backup |
| `/etc/ovpmon/helper.conf`, TLS certificate and key | Kept (helper.conf is rewritten only while it carries our marker and differs) |
| `/etc/openvpn` (`server.conf`, `crl.pem`, scripts, `ipp.txt`) | Not touched by the update; backed up |
| OpenVPN process and VPN sessions | Not stopped or restarted; connected users stay connected |
| `config.ini` of both components | Kept; the shipped one of the new version is saved as `config.ini.dist` when it differs |
| `profiler.log`, other `*.log` / `*.db` files below the code directories | Kept (moved) |
| Code, virtualenvs | **Replaced** (fresh virtualenvs; the old ones are in the backup) |
| UI files | Replaced only with `--ui-dist`; the previous ones are in the backup |
| Service definitions, nginx site, doas rules, helper | Replaced when they differ and are managed by these scripts; the previous ones are in the backup |
| User sessions | Stay valid while the secret is unchanged |
| Backups in `/var/backups/ovpmon` | The newest 5 kept, older ones pruned after a successful update; `-pre-restore` copies are never pruned automatically |
| Data directories (`/var/lib/ovpmon`, PKI, client profiles) | **Never deleted** by any script |
## Troubleshooting
| Symptom | Cause and action |
|---|---|
| `already installed ... use update.sh` / `an installation already exists` | `install.sh` never installs over an installation. Use `update.sh` (it adopts hand-made installations) |
| `installation stopped in phase ...` | Fix the cause and run `install.sh` again: it resumes and keeps secrets, certificate and data |
| `not a tested version ... needs --force` | Untested OS version: `install.sh --force` at your own risk |
| `ports ... already in use` | Another service uses 5001, 8000 or the HTTPS port: stop it or use `--https-port` |
| `pip install failed` | No access to the Python package index (proxy: `pip` honours `HTTPS_PROXY`); on Alpine check that `py3-pip` is installed |
| Health check fails | Alpine: `tail /var/log/ovpmon/ovpmon-api.log` (or `-gatherer`, `-profiler`); systemd: `journalctl -u ovpmon-api -n 50`. The scripts print the last lines of a failing service |
| `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 |
| Migration failed | Nothing was started and the rollback restored the databases; the report names the migration, the `<db>.bak-*` copy is in `/var/lib/ovpmon`. Keep the report |
| Profiler cannot start/stop OpenVPN, "helper failed" | The self-test warning of the scripts points at it: check the doas rules (`doas -C /etc/doas.conf` or `/etc/doas.d/ovpmon.conf`), `/etc/ovpmon/helper.conf` (must be `root:root` and not group/world writable; `su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status"` prints the reason) |
| `Configuration rejected` when generating the server config | The helper allowlist refused a directive, see [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md) |
| OpenVPN does not start on Debian/Ubuntu | `systemctl status openvpn-server@server`, `journalctl -u openvpn-server@server`; the config must be `/etc/openvpn/server/server.conf` and `/dev/net/tun` must exist |
| Clients connect but have no internet | Forwarding or NAT is missing: see the firewall section |
| nginx: `conflicting server name` / port in use | Another site uses the same port; change `--https-port` (or the `listen` line of the site and reload) |
| Browser warns about the certificate | It is self-signed; check the fingerprint printed by `install.sh`, or install a real certificate under `/etc/ovpmon/tls/` and reload nginx |
| UI shows the placeholder page | Installed without `--ui-dist`: `deploy/native/update.sh --ui-dist FILE` |
| `su`/`doas` self-test fails on a minimal container | Containers often lack `/etc/pam.d/doas` or a real init system; the services may still work (check health) |
## Host hardening (recommended, not done by the scripts)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`). Cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put your settings in a file that sorts first, for example `00-hardening.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (HTTP 401/429/503) on the nginx access log.
- Backends are bound to `127.0.0.1`; only the HTTPS port and the VPN port should be reachable from outside.
- Keep the system updated (`apk upgrade` / `apt-get upgrade`) and watch the advisories of OpenVPN, nginx and OpenSSH.
## Verify an installation
```sh
rc-status | grep -E "ovpmon|nginx|openvpn" # Alpine; Debian/Ubuntu: systemctl status 'ovpmon-*' nginx
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without a token
su -s /bin/sh ovpmon -c "doas -n /usr/local/sbin/ovpmon-helper service status" # JSON, not "Operation not permitted"
```
## Security notes
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
- The helper accepts six fixed commands, validates `server.conf` against an allowlist and reads its own root-owned configuration; nothing else runs as root. `ovpmon` owns the PKI including the CA key: a compromised profiler can issue client certificates (VPN access) but cannot become root.
- `/etc/ovpmon/env` is `root:root` 600 and never printed; the generated administrator password is shown once and removed from the file after the first start.
- Backups contain private keys, password hashes and the secret: mode 700/600, keep off-host copies encrypted.
- Both APIs listen on `127.0.0.1`; only nginx (HTTPS) and OpenVPN are reachable. Replace the self-signed certificate when a domain is available; consider restricting the UI by address or reaching it through the VPN.
- The scripts do not harden SSH or install fail2ban: see the next section.
Related: [Database migrations](../General/Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](Scenario1_Containers.md), [Deployment plan](../Changes/2026-10-05_Deployment_Scenarios_PLAN.md).
+103
View File
@@ -0,0 +1,103 @@
# Database Migrations
Both SQLite databases are upgraded by one mechanism: versioned, additive-only migrations with an automatic backup. A database from an older release is brought up to date at service start (or by `migrate.py`); a database is never dropped, rewritten or downgraded.
| Component | Database (default) | Module | Standalone command | Started by |
|---|---|---|---|---|
| `APP_PROFILER` | `ovpn_profiler.db` (`OVPMON_PROFILER_DB_PATH`) | `migrations.py` | `migrate.py` | `main.py` at import |
| `APP_CORE` | `openvpn_monitor.db` (`OVPMON_OPENVPN_MONITOR_DB_PATH`) | `migrations.py` | `migrate.py` | API and gatherer (`DatabaseManager.init_database`) |
The two components have separate build contexts and virtualenvs, so `migrations.py` is a separate copy in each (the generic part is identical). Keep them in sync when changing it.
## How it works
The table `schema_migrations(version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT)` records the applied migrations. The migrations are an ordered list in code (`MIGRATIONS`). A run does this:
1. Reads the state without a lock. Nothing pending: done, no write, no backup.
2. Takes a write lock (`BEGIN IMMEDIATE`, wait up to 60 s) and re-reads the state. This is what makes the API and the gatherer safe to start at the same time: the second process waits, then finds nothing pending and makes no second backup.
3. Refuses if the database is newer than the code (see Downgrade protection).
4. `PRAGMA integrity_check`. If it fails, nothing is changed.
5. If the database already holds tables: a consistent backup with the SQLite backup API to `<db>.bak-<UTC YYYYmmddTHHMMSS>` (same file permissions as the database), before anything is touched. A brand-new database gets no backup.
6. Applies each pending migration in its own savepoint. If one fails, it is rolled back, the run stops, the backup stays, and the service does not start (clear error naming the migration and the backup). Migrations that were completed before it are kept.
7. Before the commit: `PRAGMA integrity_check` and a comparison of the row count of every pre-existing table with the backup. On a mismatch everything is rolled back and the error names the backup file.
8. After a successful run that made a backup, only the newest 5 `<db>.bak-*` files of this database are kept; older ones are deleted.
Migrations only add (`CREATE TABLE IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN`, `CREATE INDEX IF NOT EXISTS`). They never drop or rewrite data.
## Startup behaviour
| Setting | Behaviour at service start |
|---|---|
| default (`OVPMON_AUTO_MIGRATE` unset or `1`) | Pending migrations are applied automatically, after the backup. |
| `OVPMON_AUTO_MIGRATE=0` | The service only checks. While migrations are pending it refuses to start (log and stderr message "run 'python migrate.py' first", exit code 1). Used by update scripts that run `migrate.py` as a separate step. |
Whenever the database cannot be used (too new, pending with auto-migrate off, failed migration, failed integrity check) the service logs a critical message, prints `FATAL: ...` to stderr and exits with code 1. There is no traceback. Note: the previous `init_database()` of `APP_CORE` only logged schema errors and went on; now a schema problem stops the start.
The service user needs write access to the database directory (backups are created next to the database).
## Standalone command: `migrate.py`
Run it from the component directory, with the component's virtualenv and the same environment as the service (it uses the same configuration to find the database). No extra dependencies.
```sh
cd APP_PROFILER # or APP_CORE
python migrate.py # apply pending migrations (backup first)
python migrate.py --check # only report, change nothing
python migrate.py --db /path/to/other.db # override the configured database file
```
| Exit code | Meaning |
|---|---|
| 0 | Done / up to date |
| 2 | `--check` only: migrations are pending |
| 1 | Error, or the database is newer than the code |
Output: database path, schema version (before -> after), applied migrations, backup path. Run it as the user that owns the database files, so new backups keep the right owner.
## Backups and restore
Backups are `<db>.bak-<YYYYmmddTHHMMSS>` (UTC) next to the database, for example `ovpn_profiler.db.bak-20261005T101500`. They are made only when migrations are pending and the database is not new. To restore:
```sh
# 1. stop the services that use this database
# 2. keep the current file for analysis, then put the backup back
mv ovpn_profiler.db ovpn_profiler.db.broken
cp ovpn_profiler.db.bak-20261005T101500 ovpn_profiler.db
# 3. start the services of the OLD release (the backup has the old schema)
```
The backup is a normal SQLite file and holds the same secrets as the database (password hashes, 2FA secrets); it has the same permissions. Restoring a backup to run the new release again is fine: the pending migrations are applied again at start.
## Downgrade protection
If `schema_migrations` holds a version higher than the code knows (the database was migrated by a newer release and then an older release was started), the database is not touched and the service does not start. The message tells to install the newer release or to restore a matching backup. `migrate.py --check` exits with 1 in this case.
## Adding a migration
In the component's `migrations.py`:
1. Write a function `_m002_<what>(conn)`. It gets the `sqlite3` connection inside a transaction: do not commit, do not open another connection. Only additive statements, idempotent (`IF NOT EXISTS`, check `PRAGMA table_info` before `ADD COLUMN`).
2. Append `Migration(2, "<what>", _m002_<what>)` to `MIGRATIONS`. Versions are consecutive and are never changed or removed after release.
3. `APP_PROFILER`: a brand-new database is created from the models (`FRESH_SCHEMA`, the `create_all` equivalent) and all migrations are recorded without running them, so the models must already contain the change. Migrations 2+ only serve existing databases.
4. `APP_CORE`: there is no separate fresh schema; migration 1 plus the following ones run on a new database. Keep migration 1 unchanged and do the new work in the new migration.
5. Add a case to `test_migrations.py` (an old schema in, rows kept, new column present).
## Pre-versioned databases
A database from a release before this mechanism has the tables but no `schema_migrations`. It is treated as "nothing applied": the backup is made, migration 1 (baseline) runs and the result is recorded.
- `APP_PROFILER` migration 1 is generated from the SQLAlchemy models: tables that are missing are created, every missing model column is added with `ALTER TABLE ... ADD COLUMN`. The type comes from the column type; a scalar default becomes `DEFAULT <literal>` (so existing rows get it: Boolean `0`/`1`, numbers, strings), a JSON/list default becomes `'[]'`; other columns stay `NULL`. It covers all columns that the old scripts added (`is_revoked`, `is_expired`, `expiration_date` in `user_profiles`; `public_ip`, `tun_mtu`, `mssfix` in `system_settings`) and `note`. Existing indexes and constraints of existing tables are not touched.
- `APP_CORE` migration 1 is the former `init_database()`: `CREATE TABLE IF NOT EXISTS` for all tables and indexes, and the missing `users.totp_secret` and `users.is_2fa_enabled` columns.
## Superseded scripts
`APP_PROFILER/add_columns.py`, `APP_PROFILER/scripts/add_public_ip_column.py` and `APP_PROFILER/scripts/add_mtu_mss_columns.py` are superseded by migration 1 and must not be needed any more; they stay in place unchanged for reference. `ensure_columns()` in `APP_PROFILER/database.py` was removed.
## Tests
One pytest file per component builds an old database from an embedded SQL schema (the oldest reconstructable one and the baseline of commit `3836049`), runs the migration and checks data, new columns, the backup, the stamp, the no-op second run and the downgrade protection.
```sh
cd APP_PROFILER && python -m pytest test_migrations.py
cd APP_CORE && python -m pytest test_migrations.py # pip install -r requirements-dev.txt first
```
+4 -47
View File
@@ -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 <<EOT
JWT_SECRET=$(openssl rand -hex 32)
OVPMON_INITIAL_ADMIN_USER=<login>
OVPMON_INITIAL_ADMIN_PASSWORD=<strong password>
EOT
chmod 600 .env
```
2. `docker-compose up -d --build`
3. Open `http://<host>`, 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
```
+6 -81
View File
@@ -1,87 +1,12 @@
# Deployment: system services (no containers)
Tested on **Alpine 3.23 (OpenRC)**; Debian/Ubuntu (systemd) differs only in service manager. Unit/init templates: [`systemd/`](systemd), [`openrc/`](openrc/INSTALL.md). Generic notes: [Deployment](Deployment.md), [Service management](Service_Management.md), [Nginx](Nginx_Configuration.md).
This page is now a pointer. Installation and update on **Alpine (OpenRC), Debian and Ubuntu (systemd)** are done with the scripts in `deploy/native/` and described in **[Scenario 2: system services](../Deployment/Scenario2_System_Services.md)**: install, update with a separate database migration step, backup, restore, rollback, firewall and NAT commands, layout, environment file, troubleshooting and the "what is preserved" table.
## 1. Packages
Quick start (as root, from a checkout of the repository; build the UI with `deploy/native/build-ui.sh` on a machine with Docker first):
- Alpine: `apk add python3 py3-pip nginx nodejs npm openvpn easy-rsa iptables bash`
- Debian/Ubuntu: `apt install python3-venv nginx nodejs npm openvpn easy-rsa iptables`
## 2. Backend
```bash
cd APP_CORE && python3 -m venv venv && venv/bin/pip install -r requirements.txt gunicorn
cd APP_PROFILER && python3 -m venv venv && venv/bin/pip install -r requirements.txt
mkdir -p APP_PROFILER/easy-rsa && cp -r /usr/share/easy-rsa/* APP_PROFILER/easy-rsa/ # Docker entrypoint does this automatically
```sh
deploy/native/install.sh --ui-dist ui-dist.tar.gz # first installation
deploy/native/update.sh --ui-dist ui-dist.tar.gz # later: update with backup and rollback
```
## 3. Environment file
`/etc/ovpmon/env` (chmod 600), loaded by the services:
```
OVPMON_API_SECRET_KEY=<openssl rand -hex 32>
OVPMON_API_HOST=127.0.0.1
OVPMON_API_PORT=5001
OVPMON_OPENVPN_MONITOR_DB_PATH=/var/lib/ovpmon/openvpn_monitor.db
OVPMON_OPENVPN_MONITOR_LOG_PATH=/var/log/openvpn/openvpn-status.log
OVPMON_PROFILER_DB_PATH=/var/lib/ovpmon/ovpn_profiler.db
OVPMON_LOGGING_LEVEL=INFO
OVPMON_CORS_ORIGINS=https://<HOST>:8088
```
Create `/var/lib/ovpmon`, `/var/log/ovpmon`, `/var/log/openvpn`. For the first start also set `OVPMON_INITIAL_ADMIN_USER` / `OVPMON_INITIAL_ADMIN_PASSWORD`, then remove them.
## 4. Services
| Service | Command | Listens |
|---|---|---|
| `ovpmon-api` | `APP_CORE/venv/bin/gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app` (cwd `APP_CORE`) | 127.0.0.1:5001 |
| `ovpmon-gatherer` | `APP_CORE/venv/bin/python openvpn_gatherer_v3.py` (cwd `APP_CORE`) | - |
| `ovpmon-profiler` | `APP_PROFILER/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000` (cwd `APP_PROFILER`) | 127.0.0.1:8000 |
OpenRC (Alpine): `supervisor=supervise-daemon`, `respawn_delay=3`, source `/etc/ovpmon/env` in `start_pre`, then `rc-update add <svc> default && rc-service <svc> start`. systemd: use the units from `systemd/` with `EnvironmentFile=/etc/ovpmon/env`.
The Profiler restarts OpenVPN through `rc-service openvpn` (Alpine) or `systemctl openvpn`; on Alpine link the config: `ln -s server.conf /etc/openvpn/openvpn.conf` and enable the `openvpn` service.
## 4a. Run as an unprivileged user (recommended)
Create the `ovpmon` user, give it the data directories, add `command_user="ovpmon:ovpmon"` to the init scripts (or `User=ovpmon` in systemd units), install the root helper and the doas rules. The API then renders `server.conf` to `/var/lib/ovpmon/staging/`; the helper validates and installs it, publishes the CRL for OpenVPN and controls the `openvpn` service. Full procedure, helper source and results: [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md); files in [`privilege-separation/`](privilege-separation/).
## 5. UI and Nginx (HTTPS on 8088)
```bash
cd APP_UI && npm install && npm run build
mkdir -p /var/www/ovpmon && cp -r dist/. /var/www/ovpmon/
```
Certificate (self-signed, replace with a real one when a domain is available):
```bash
mkdir -p /etc/ovpmon/tls && cd /etc/ovpmon/tls
openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 825 \
-subj "/CN=ovpmon" -addext "subjectAltName=IP:<HOST-IP>,DNS:ovpmon" -keyout ovpmon.key -out ovpmon.crt
chmod 600 ovpmon.key
```
Nginx server (`/etc/nginx/http.d/ovpmon.conf` on Alpine): `listen 8088 ssl`, TLS 1.2/1.3, `error_page 497 =301 https://$host:8088$request_uri`, security headers, `limit_req` (5 r/min) on `/api/auth/login`, `/` → static UI, `/api/` → `127.0.0.1:5001`, `/profiles-api/` → `127.0.0.1:8000/api/`. Full listing: [Nginx configuration](Nginx_Configuration.md). Do not declare a second `ssl_session_cache shared:SSL` zone with a different size than the main `nginx.conf`.
## 6. First run
1. `https://<host>:8088/` → sign in with the seeded admin → **Account**: change username/password, enable 2FA.
2. **PKI Configuration → Initialize PKI** → generate server config → start OpenVPN → create profiles.
## 7. Host hardening (recommended)
- SSH: key-only (`PasswordAuthentication no`, `KbdInteractiveAuthentication no`, `PermitRootLogin prohibit-password`); note that cloud-init drop-ins in `/etc/ssh/sshd_config.d/` can override the main file, so put settings in `00-*.conf`.
- fail2ban: jails `sshd` and one for `POST /api/auth/login` (401/429/503) on the Nginx access log.
- Backends bound to `127.0.0.1`; only 8088 (UI/API) and the VPN port are public.
## 8. Verify
```bash
rc-status | grep -E "ovpmon|nginx|openvpn" # or: systemctl status ovpmon-*
ss -tlnp | grep -E ":(8088|5001|8000) "
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/ # 200
curl -sk -o /dev/null -w "%{http_code}\n" https://127.0.0.1:8088/profiles-api/config # 401 without token
```
Related: [Nginx configuration](Nginx_Configuration.md), [Service management](Service_Management.md), [Database migrations](Database_Migrations.md), [Privilege separation](../Changes/2026-09-30_Privilege_Separation.md), [Scenario 1: containers](../Deployment/Scenario1_Containers.md). The service definitions are in [`systemd/`](systemd) and [`openrc/`](openrc/INSTALL.md).
+3
View File
@@ -23,6 +23,9 @@ Welcome to the documentation for the OpenVPN Monitor suite.
- [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md)
- [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md)
- [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md)
- [Database migrations (2026-10-05)](../Changes/2026-10-05_DB_Migrations.md) · [reference](Database_Migrations.md)
- [Scenario 1: containers (2026-10-05)](../Changes/2026-10-05_Scenario1_Containers.md) · [guide](../Deployment/Scenario1_Containers.md)
- [Scenario 2: system services (2026-10-05)](../Changes/2026-10-05_Scenario2_System_Services.md) · [guide](../Deployment/Scenario2_System_Services.md)
## 🔍 Core Monitoring (`APP_CORE`)
The core module responsible for log parsing, real-time statistics, and the primary API.
+21 -83
View File
@@ -1,93 +1,31 @@
# Service Setup Guide
This guide describes how to set up the OpenVPN Monitor components as system services.
The OpenVPN Monitor components run as three system services under the unprivileged user `ovpmon`. `deploy/native/install.sh` installs and enables them (see [Scenario 2: system services](../Deployment/Scenario2_System_Services.md)); this page is the day-to-day reference.
## Components
| Service | Command (working directory under the install dir, default `/opt/OpenVPN-Monitoring-Simple`) | Listens |
|---|---|---|
| `ovpmon-api` | `APP_CORE/venv/bin/python -m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app` | 127.0.0.1:5001 |
| `ovpmon-gatherer` | `APP_CORE/venv/bin/python openvpn_gatherer_v3.py` | - |
| `ovpmon-profiler` | `APP_PROFILER/venv/bin/python -m uvicorn main:app --host 127.0.0.1 --port 8000` | 127.0.0.1:8000 |
1. **ovpmon-api**: The main Flask API (`APP/openvpn_api_v3.py`).
2. **ovpmon-gatherer**: The background data gatherer (`APP/openvpn_gatherer_v3.py`).
3. **ovpmon-profiler**: The new FastAPI profiler module (`NEW_MODULES/main.py`).
Settings: `/etc/ovpmon/env` (`root:root` 600). The services start after the network and do not depend on OpenVPN.
## Common Prerequisites
## Definitions
- **Install Directory**: `/opt/ovpmon` (Recommended)
- **Virtual Environment**: `/opt/ovpmon/venv`
- Alpine (OpenRC): [`openrc/ovpmon-*`](openrc/INSTALL.md) in `/etc/init.d/` (`supervise-daemon`, `command_user=ovpmon:ovpmon`, environment sourced in `start_pre`, log in `/var/log/ovpmon/`).
- Debian / Ubuntu (systemd): [`systemd/ovpmon-*.service`](systemd) in `/etc/systemd/system/` (`User=ovpmon`, `EnvironmentFile=/etc/ovpmon/env`, moderate hardening, log in the journal).
---
Install them with the scripts (they adjust the install directory); by hand, copy a file, replace `/opt/OpenVPN-Monitoring-Simple` if needed and enable it as below.
## 1. Alpine Linux (OpenRC)
## Commands
### Installation
| | OpenRC (Alpine) | systemd (Debian, Ubuntu) |
|---|---|---|
| Enable at boot | `rc-update add ovpmon-api default` | `systemctl enable ovpmon-api` |
| Start / stop / restart | `rc-service ovpmon-api start\|stop\|restart` | `systemctl start\|stop\|restart ovpmon-api` |
| Status | `rc-service ovpmon-api status` | `systemctl status ovpmon-api` |
| Log | `tail -f /var/log/ovpmon/ovpmon-api.log` | `journalctl -u ovpmon-api -f` |
| After editing `/etc/ovpmon/env` | restart the services | restart the services |
| After editing a unit file | - | `systemctl daemon-reload` |
1. **Copy Service Scripts**:
Copy the scripts from `Deployment/APP/openrc/` to `/etc/init.d/`.
```sh
cp DOCS/General/openrc/ovpmon-api /etc/init.d/
cp DOCS/General/openrc/ovpmon-gatherer /etc/init.d/
cp DOCS/General/openrc/ovpmon-profiler /etc/init.d/
```
2. **Set Permissions**:
```sh
chmod +x /etc/init.d/ovpmon-*
```
3. **Enable Services**:
```sh
rc-update add ovpmon-api default
rc-update add ovpmon-gatherer default
rc-update add ovpmon-profiler default
```
4. **Start Services**:
```sh
rc-service ovpmon-api start
rc-service ovpmon-gatherer start
rc-service ovpmon-profiler start
```
### Configuration
To override defaults (e.g., if you installed to a different directory), create files in `/etc/conf.d/`:
**File:** `/etc/conf.d/ovpmon-api` (example)
```sh
directory="/var/www/my-monitoring"
command_args="/var/www/my-monitoring/APP_CORE/openvpn_api_v3.py"
```
---
## 2. Debian / Ubuntu (Systemd)
### Installation Steps
1. **Copy Service Files**:
Copy the provided service files from `DOCS/General/systemd/` to `/etc/systemd/system/`.
```bash
cp DOCS/General/systemd/ovpmon-api.service /etc/systemd/system/
cp DOCS/General/systemd/ovpmon-gatherer.service /etc/systemd/system/
cp DOCS/General/systemd/ovpmon-profiler.service /etc/systemd/system/
```
2. **Reload Daemon**:
```bash
systemctl daemon-reload
```
3. **Enable Services** (Start on boot):
```bash
systemctl enable ovpmon-api ovpmon-gatherer ovpmon-profiler
```
4. **Start Services**:
```bash
systemctl start ovpmon-api ovpmon-gatherer ovpmon-profiler
```
5. **Check Status**:
```bash
systemctl status ovpmon-api
```
The OpenVPN server itself (`openvpn` on Alpine, `openvpn-server@server` on Debian/Ubuntu) is started and stopped from the UI through the root helper (`doas`); it is not an `ovpmon-*` service.
+3 -47
View File
@@ -1,49 +1,5 @@
# OpenRC Service Installation Guide
# OpenRC service scripts
This guide explains how to install and enable the `ovpmon-api` and `ovpmon-gatherer` services on an Alpine Linux (or other OpenRC-based) system.
`ovpmon-api`, `ovpmon-gatherer` and `ovpmon-profiler` are the OpenRC scripts (Alpine) of the system-services deployment. They run the services as the user `ovpmon`, source `/etc/ovpmon/env` in `start_pre` and are supervised by `supervise-daemon`.
## Prerequisites
- **Paths**: The scripts assume the application is installed at `/opt/ovpmon`.
- **Virtualenv**: A python virtual environment should exist at `/opt/ovpmon/venv`.
If your paths differ, you can edit the scripts directly or create configuration files in `/etc/conf.d/`.
## Installation Steps
1. **Copy the scripts to `/etc/init.d/`**:
```sh
cp ovpmon-api /etc/init.d/
cp ovpmon-gatherer /etc/init.d/
```
2. **Make them executable**:
```sh
chmod 755 /etc/init.d/ovpmon-api
chmod 755 /etc/init.d/ovpmon-gatherer
```
3. **Add to default runlevel** (to start on boot):
```sh
rc-update add ovpmon-api default
rc-update add ovpmon-gatherer default
```
4. **Start the services**:
```sh
rc-service ovpmon-api start
rc-service ovpmon-gatherer start
```
## Configuration (Optional)
You can override default variables without editing the script by creating files in `/etc/conf.d/`.
**Example `/etc/conf.d/ovpmon-api`**:
```sh
# Override installation directory
directory="/var/www/ovpmon/APP"
# Override command arguments
command_args="/var/www/ovpmon/APP/openvpn_api_v3.py --debug"
```
Do not copy them by hand: `deploy/native/install.sh` installs them (adjusting the install directory when it is not `/opt/OpenVPN-Monitoring-Simple`) and `deploy/native/update.sh` keeps them current. The full procedure, the layout and the systemd counterparts are in [Scenario 2: system services](../../Deployment/Scenario2_System_Services.md).
Regular → Executable
+32 -5
View File
@@ -1,16 +1,43 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor API (Flask under gunicorn, APP_CORE), OpenRC (Alpine).
# Install: deploy/native/install.sh renders this template (install dir, if not the default) into
# /etc/init.d/ovpmon-api. Manual use: copy it there (chmod 755), `rc-update add ovpmon-api default`,
# `rc-service ovpmon-api start`. Guide: DOCS/Deployment/Scenario2_System_Services.md
#
# Settings come from /etc/ovpmon/env (root:root 600), sourced in start_pre while still root; the
# daemon then runs as ovpmon. supervise-daemon restarts it after a crash.
# The service does not depend on openvpn: the VPN server is started from the UI through the root helper.
name="ovpmon-api"
description="OpenVPN Monitor API Service"
description="OpenVPN Monitor API (gunicorn)"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/APP"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_CORE"
command="/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python"
command_args="-m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/APP/openvpn_api_v3.py"
output_log="/var/log/ovpmon/ovpmon-api.log"
error_log="/var/log/ovpmon/ovpmon-api.log"
depend() {
need net
after firewall
}
start_pre() {
# log file writable for the service user (the log directory is owned by ovpmon)
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
# export the service environment; the file is data written by install.sh (KEY=VALUE lines)
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+25 -5
View File
@@ -1,16 +1,36 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor gatherer (reads the OpenVPN status log into the monitoring database, APP_CORE),
# OpenRC (Alpine). Install: see ovpmon-api. Settings come from /etc/ovpmon/env.
# The gatherer keeps running while OpenVPN is down (it waits for the status log).
name="ovpmon-gatherer"
description="OpenVPN Monitor Gatherer Service"
description="OpenVPN Monitor Gatherer"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/APP"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_CORE"
command="/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python"
command_args="openvpn_gatherer_v3.py"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/APP/openvpn_gatherer_v3.py"
output_log="/var/log/ovpmon/ovpmon-gatherer.log"
error_log="/var/log/ovpmon/ovpmon-gatherer.log"
depend() {
need net
after firewall
}
start_pre() {
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+29 -5
View File
@@ -1,16 +1,40 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Profiler API (FastAPI under uvicorn, APP_PROFILER), OpenRC (Alpine): PKI (easy-rsa),
# profiles, server settings. Install: see ovpmon-api. Settings come from /etc/ovpmon/env.
#
# Runs as ovpmon. Anything that needs root (install server.conf, publish the CRL, start/stop OpenVPN)
# goes through `doas /usr/local/sbin/ovpmon-helper <fixed args>` (rules: /etc/doas.conf or
# /etc/doas.d/ovpmon.conf, configuration: /etc/ovpmon/helper.conf).
# Started without --reload and without depending on openvpn.
name="ovpmon-profiler"
description="OpenVPN Monitor Profiler Service (FastAPI)"
description="OpenVPN Profiler API (uvicorn)"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=0
: ${directory:="/opt/ovpmon/NEW_MODULES"}
: ${command_user:="root"}
command_user="ovpmon:ovpmon"
directory="/opt/OpenVPN-Monitoring-Simple/APP_PROFILER"
command="/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/venv/bin/python"
command_args="-m uvicorn main:app --host 127.0.0.1 --port 8000"
command="/opt/ovpmon/venv/bin/python"
command_args="/opt/ovpmon/NEW_MODULES/main.py"
output_log="/var/log/ovpmon/ovpmon-profiler.log"
error_log="/var/log/ovpmon/ovpmon-profiler.log"
depend() {
need net
after firewall
}
start_pre() {
checkpath -f -m 0640 -o ovpmon:ovpmon "$output_log" || return 1
[ -r /etc/ovpmon/env ] || { eerror "/etc/ovpmon/env is missing"; return 1; }
set -a
. /etc/ovpmon/env
set +a
# extend, never replace: OpenRC itself needs /lib/rc/bin (ebegin, eend) on the PATH
export PATH="/usr/local/sbin:/usr/local/bin:$PATH"
}
+143 -8
View File
@@ -2,10 +2,30 @@
"""ovpmon-helper: the only root-side entry point for the unprivileged ovpmon services.
Usage (via doas): ovpmon-helper install-config
ovpmon-helper publish-crl
ovpmon-helper service start|stop|restart|status
install-config reads the staged OpenVPN server config, validates it against a strict
allowlist of directives and installs it atomically to /etc/openvpn/server.conf.
allowlist of directives and installs it atomically to the OpenVPN config path
(default /etc/openvpn/server.conf).
Optional configuration: /etc/ovpmon/helper.conf (INI, section [helper]). The helper runs through
doas with a stripped environment, so it reads its own root-owned file; the file must be owned by
root and not writable by group/other, otherwise the helper refuses to run. Without the file the
built-in defaults below apply (Alpine/OpenRC layout, unchanged behaviour). Keys:
[helper]
install_dir = /opt/OpenVPN-Monitoring-Simple # PKI = <install_dir>/APP_PROFILER/easy-rsa/pki
service_manager = openrc # openrc | systemd
service_unit = openvpn # systemd default: openvpn-server@server
config_path = /etc/openvpn/server.conf # Debian/Ubuntu: /etc/openvpn/server/server.conf
staged_path = /var/lib/ovpmon/staging/server.conf
Every value is validated strictly (absolute paths without "..", fixed prefixes, unit-name
pattern, fixed set of managers); unknown keys and invalid values make the helper refuse.
OpenRC runs `/sbin/rc-service <unit> <action>`; systemd runs `systemctl <action> <unit>`
(fixed argv, fixed PATH).
"""
import configparser
import ipaddress
import json
import os
@@ -16,17 +36,38 @@ import stat
import subprocess
import sys
STAGED = "/var/lib/ovpmon/staging/server.conf"
TARGET = "/etc/openvpn/server.conf"
PKI_DIR = "/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa/pki"
CONF_PATH = "/etc/ovpmon/helper.conf"
# Built-in defaults = the values that were hard-coded before helper.conf existed
DEFAULT_INSTALL_DIR = "/opt/OpenVPN-Monitoring-Simple"
DEFAULT_SERVICE_MANAGER = "openrc"
DEFAULT_SERVICE_UNIT = "openvpn"
DEFAULT_SYSTEMD_UNIT = "openvpn-server@server"
DEFAULT_CONFIG_PATH = "/etc/openvpn/server.conf"
DEFAULT_STAGED_PATH = "/var/lib/ovpmon/staging/server.conf"
# Active settings (defaults until apply_settings() is called by load_config())
INSTALL_DIR = DEFAULT_INSTALL_DIR
SERVICE_MANAGER = DEFAULT_SERVICE_MANAGER
SERVICE_UNIT = DEFAULT_SERVICE_UNIT
STAGED = DEFAULT_STAGED_PATH
TARGET = DEFAULT_CONFIG_PATH
PKI_DIR = INSTALL_DIR + "/APP_PROFILER/easy-rsa/pki"
CRL_SRC = PKI_DIR + "/crl.pem"
SCRIPTS_DIR = "/etc/openvpn/scripts"
STATUS_LOG = "/var/log/openvpn/openvpn-status.log"
CRL_SRC = PKI_DIR + "/crl.pem"
CRL_PUBLISHED = "/etc/openvpn/crl.pem"
CRL_MAX = 1024 * 1024
SERVICE_USER = "ovpmon"
MAX_SIZE = 64 * 1024
CIPHERS_RE = re.compile(r"^[A-Za-z0-9:_-]{1,200}$")
UNIT_RE = re.compile(r"^[A-Za-z0-9@._-]{1,64}$")
PATH_RE = re.compile(r"^/[A-Za-z0-9._/+@-]{1,200}$")
MANAGERS = ("openrc", "systemd")
CONF_KEYS = ("install_dir", "service_manager", "service_unit", "config_path", "staged_path")
RC_SERVICE = "/sbin/rc-service"
SYSTEMCTL_CANDIDATES = ("/usr/bin/systemctl", "/bin/systemctl")
os.environ["PATH"] = "/usr/sbin:/usr/bin:/sbin:/bin"
@@ -36,6 +77,7 @@ class Reject(Exception):
def under(path, base):
real = os.path.realpath(path)
base = os.path.realpath(base)
return real == base or real.startswith(base.rstrip("/") + "/")
@@ -44,6 +86,89 @@ def need(cond, msg):
raise Reject(msg)
# ---------------------------------------------------------------------------
# Optional configuration /etc/ovpmon/helper.conf
# ---------------------------------------------------------------------------
def clean_path(key, value, prefix=None, min_parts=1, suffix=None):
"""Strict check of an absolute path from helper.conf; returns it without a trailing slash."""
need(PATH_RE.fullmatch(value) is not None, key + ": must be an absolute path of letters, digits and . _ / + @ -")
path = value.rstrip("/") or "/"
parts = path.split("/")[1:]
need("" not in parts and "." not in parts and ".." not in parts, key + ": no empty, '.' or '..' components")
if prefix is not None:
need(path.startswith(prefix), key + ": must be below " + prefix)
need(len(parts) >= min_parts, key + ": path too short")
if suffix is not None:
need(path.endswith(suffix), key + ": must end with " + suffix)
return path
def parse_config(text):
"""Parse and validate the text of helper.conf. Returns a dict with the keys that are set."""
cp = configparser.ConfigParser(interpolation=None, strict=True)
try:
need(all(ord(c) < 128 for c in text), "helper.conf: ASCII only")
cp.read_string(text)
except configparser.Error as e:
raise Reject("helper.conf: " + str(e).splitlines()[0][:150])
need(cp.sections() == ["helper"], "helper.conf: exactly one section [helper] is required")
raw = dict(cp["helper"])
unknown = sorted(set(raw) - set(CONF_KEYS))
need(not unknown, "helper.conf: unknown key(s): " + ", ".join(unknown)[:100])
out = {}
if "install_dir" in raw:
out["install_dir"] = clean_path("install_dir", raw["install_dir"], min_parts=2)
if "service_manager" in raw:
need(raw["service_manager"] in MANAGERS, "service_manager: must be one of " + ", ".join(MANAGERS))
out["service_manager"] = raw["service_manager"]
if "service_unit" in raw:
need(UNIT_RE.fullmatch(raw["service_unit"]) is not None and raw["service_unit"][0] not in "-.",
"service_unit: must match " + UNIT_RE.pattern + " and not start with - or .")
out["service_unit"] = raw["service_unit"]
if "config_path" in raw:
out["config_path"] = clean_path("config_path", raw["config_path"], prefix="/etc/openvpn/", min_parts=3, suffix=".conf")
if "staged_path" in raw:
out["staged_path"] = clean_path("staged_path", raw["staged_path"], prefix="/var/lib/ovpmon/", min_parts=4)
return out
def apply_settings(settings):
"""Set the module-level settings from a validated dict (missing keys: built-in defaults)."""
global INSTALL_DIR, SERVICE_MANAGER, SERVICE_UNIT, STAGED, TARGET, PKI_DIR, CRL_SRC
INSTALL_DIR = settings.get("install_dir", DEFAULT_INSTALL_DIR)
SERVICE_MANAGER = settings.get("service_manager", DEFAULT_SERVICE_MANAGER)
default_unit = DEFAULT_SYSTEMD_UNIT if SERVICE_MANAGER == "systemd" else DEFAULT_SERVICE_UNIT
SERVICE_UNIT = settings.get("service_unit", default_unit)
TARGET = settings.get("config_path", DEFAULT_CONFIG_PATH)
STAGED = settings.get("staged_path", DEFAULT_STAGED_PATH)
PKI_DIR = INSTALL_DIR + "/APP_PROFILER/easy-rsa/pki"
CRL_SRC = PKI_DIR + "/crl.pem"
def load_config(path=None, owner_uid=0):
"""Read helper.conf (if it exists) and apply it. The file must be a regular file (no symlink)
owned by owner_uid (root) and not writable by group/other, otherwise Reject."""
path = path or CONF_PATH
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
except FileNotFoundError:
apply_settings({})
return {}
except OSError as e:
raise Reject("helper.conf cannot be opened: " + e.strerror)
try:
st = os.fstat(fd)
need(stat.S_ISREG(st.st_mode), "helper.conf must be a regular file")
need(st.st_uid == owner_uid and not st.st_mode & 0o022, "helper.conf must be owned by root and not group/other-writable")
need(st.st_size <= 4096, "helper.conf too large")
data = os.read(fd, 4097)
finally:
os.close(fd)
settings = parse_config(data.decode("ascii", "replace"))
apply_settings(settings)
return settings
def is_int(x, lo, hi):
return re.fullmatch(r"\d{1,6}", x) is not None and lo <= int(x) <= hi
@@ -183,8 +308,9 @@ def install_config():
f.write(text)
os.chmod(tmp, 0o644)
os.replace(tmp, TARGET)
if not os.path.lexists("/etc/openvpn/openvpn.conf"):
os.symlink("server.conf", "/etc/openvpn/openvpn.conf")
# OpenRC's openvpn service reads /etc/openvpn/openvpn.conf; systemd units use their own config path
if SERVICE_MANAGER == "openrc" and os.path.dirname(TARGET) == "/etc/openvpn" and not os.path.lexists("/etc/openvpn/openvpn.conf"):
os.symlink(os.path.basename(TARGET), "/etc/openvpn/openvpn.conf")
def prepare_status_log():
@@ -221,6 +347,14 @@ def publish_crl():
os.replace(tmp, CRL_PUBLISHED)
def service_command(action):
"""Fixed argv of the service manager (no shell, values come from the validated helper.conf)."""
if SERVICE_MANAGER == "systemd":
systemctl = next((p for p in SYSTEMCTL_CANDIDATES if os.path.exists(p)), SYSTEMCTL_CANDIDATES[0])
return [systemctl, action, SERVICE_UNIT]
return [RC_SERVICE, SERVICE_UNIT, action]
def service(action):
need(action in ("start", "stop", "restart", "status"), "invalid action")
if action in ("start", "restart"):
@@ -231,12 +365,13 @@ def service(action):
publish_crl()
except Exception:
pass # a broken CRL must not stop the VPN; crl-verify will then keep the previously published file
r = subprocess.run(["/sbin/rc-service", "openvpn", action], capture_output=True, text=True, timeout=60)
r = subprocess.run(service_command(action), capture_output=True, text=True, timeout=60)
return r.returncode, (r.stdout + r.stderr).strip()[-500:]
def main(argv):
try:
load_config()
if argv == ["install-config"]:
install_config()
print(json.dumps({"status": "ok"}))
+30 -5
View File
@@ -1,14 +1,39 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor API (Flask under gunicorn, APP_CORE).
# Install: deploy/native/install.sh renders this template (install dir, if not the default) into
# /etc/systemd/system/ovpmon-api.service. Manual use: copy it there, `systemctl daemon-reload`,
# `systemctl enable --now ovpmon-api`. Guide: DOCS/Deployment/Scenario2_System_Services.md
#
# Settings come from /etc/ovpmon/env (root:root 600; systemd reads it as root before the user switch).
# The service does not depend on openvpn: the VPN server is started from the UI through the root helper.
[Unit]
Description=OpenVPN Monitor API
Description=OpenVPN Monitor API (gunicorn)
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_CORE
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_CORE/openvpn_api_v3.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_CORE
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python -m gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app
Restart=always
RestartSec=5
RestartSec=3
# Hardening: code and virtualenv are root-owned and read-only for the service
NoNewPrivileges=yes
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
LockPersonality=yes
# Write access: databases (and their migration backups) and logs
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon
[Install]
WantedBy=multi-user.target
+25 -4
View File
@@ -1,14 +1,35 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Monitor gatherer (reads the OpenVPN status log into the monitoring database, APP_CORE).
# Install: see ovpmon-api.service. Settings come from /etc/ovpmon/env.
# The gatherer starts and keeps running while OpenVPN is down (it waits for the status log).
[Unit]
Description=OpenVPN Monitor Gatherer
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_CORE
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_CORE/openvpn_gatherer_v3.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_CORE
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_CORE/venv/bin/python openvpn_gatherer_v3.py
Restart=always
RestartSec=10
RestartSec=3
# Hardening: code and virtualenv are root-owned and read-only for the service
NoNewPrivileges=yes
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictRealtime=yes
LockPersonality=yes
# Write access: monitoring database (and its migration backups) and logs
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon
[Install]
WantedBy=multi-user.target
+35 -6
View File
@@ -1,15 +1,44 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# OpenVPN Profiler API (FastAPI under uvicorn, APP_PROFILER): PKI (easy-rsa), profiles, server settings.
# Install: see ovpmon-api.service. Settings come from /etc/ovpmon/env.
#
# The profiler runs as the unprivileged user ovpmon. Anything that needs root (install server.conf,
# publish the CRL, start/stop OpenVPN) goes through `doas /usr/local/sbin/ovpmon-helper <fixed args>`
# (rules: /etc/doas.conf, configuration: /etc/ovpmon/helper.conf). Therefore, unlike the other two
# services, this unit must NOT set NoNewPrivileges (doas is setuid) nor any seccomp-based option (see below), must not restrict capabilities,
# and must leave /etc/openvpn writable: the helper is a child of this process and inherits its
# mount namespace.
# Started without --reload and without depending on openvpn.
[Unit]
Description=OpenVPN Profiler API
Description=OpenVPN Profiler API (uvicorn)
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ovpmon/APP_PROFILER
# Running directly via python as main.py has uvicorn.run
ExecStart=/opt/ovpmon/venv/bin/python /opt/ovpmon/APP_PROFILER/main.py
User=ovpmon
Group=ovpmon
EnvironmentFile=/etc/ovpmon/env
WorkingDirectory=/opt/OpenVPN-Monitoring-Simple/APP_PROFILER
ExecStart=/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/venv/bin/python -m uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always
RestartSec=5
RestartSec=3
# Hardening (moderate, see the note above)
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
ProtectControlGroups=yes
# Deliberately absent: ProtectKernelTunables, ProtectKernelModules, RestrictRealtime, LockPersonality,
# SystemCallFilter, RestrictAddressFamilies, MemoryDenyWriteExecute, RestrictNamespaces. They are enforced with a seccomp filter, and for an
# unprivileged unit systemd then sets NoNewPrivileges implicitly, which breaks the setuid doas
# ("doas: not installed setuid"). Verify with: grep NoNewPrivs /proc/<main pid>/status (must be 0)
# Write access: databases and logs; PKI, client profiles and the profiler log inside the install dir;
# /etc/openvpn and /var/log/openvpn for the root helper (a leading "-" ignores a missing path)
ReadWritePaths=/var/lib/ovpmon /var/log/ovpmon /opt/OpenVPN-Monitoring-Simple/APP_PROFILER/easy-rsa /opt/OpenVPN-Monitoring-Simple/APP_PROFILER/client-config
ReadWritePaths=-/opt/OpenVPN-Monitoring-Simple/APP_PROFILER/profiler.log
ReadWritePaths=-/etc/openvpn -/var/log/openvpn
[Install]
WantedBy=multi-user.target
+5 -2
View File
@@ -13,8 +13,8 @@ Nginx is the only public entry point: `/` UI, `/api/` Monitoring API, `/profiles
## Quick start
- **Containers:** `docker-compose up -d --build`, open `http://<host>`. Details: [Deployment: Docker](DOCS/General/Deployment_Docker.md).
- **System services** (systemd / OpenRC, no containers): [Deployment: native](DOCS/General/Deployment_Native.md).
- **Containers:** `deploy/docker/install.sh --variant a|b`, open `http://<host>`. Details: [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) (update, backup, rollback included).
- **System services** (Alpine/OpenRC, Debian and Ubuntu/systemd, no containers): `deploy/native/install.sh`; details, update and rollback: [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md).
After the first start: sign in, open **PKI Configuration** → **Initialize PKI**, generate the server config, start OpenVPN, create profiles.
@@ -65,6 +65,9 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US
| 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](DOCS/Changes/2026-10-04_Async_PKI_Init.md) |
| 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) |
| 2026-10-05 | Scenario 2: install and update as system services on Alpine, Debian, Ubuntu; helper config for systemd; backup, restore, automatic rollback | [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md) · [change](DOCS/Changes/2026-10-05_Scenario2_System_Services.md) |
## Notes
+70
View File
@@ -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"]
+92
View File
@@ -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 (<db>.bak-<UTC timestamp> 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
+86
View File
@@ -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
+89
View File
@@ -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/<UTC timestamp>/ with <volume>.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 <directory>
# 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"
+190
View File
@@ -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:-<server-address>}"
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 <<EOF
Next steps:
1. Open the Web UI and sign in.
2. PKI Configuration -> 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
+616
View File
@@ -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 "service<TAB>image name<TAB>image 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 "<repo>: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: <volume>.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 <backups>/<ts>-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 '
}
+80
View File
@@ -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/<timestamp>-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
+261
View File
@@ -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/<timestamp>-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 <name>: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 $?
+103
View File
@@ -0,0 +1,103 @@
#!/bin/sh
# Back up everything that matters of a system-services installation (usable from cron).
#
# deploy/native/backup.sh [--prefix DIR] [--stop] [--keep N]
#
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --stop stop the application services during the backup and start them again afterwards
# (OpenVPN keeps running). The databases are copied with the SQLite backup API either way, so
# they are consistent without --stop; --stop only makes the PKI/client files and the databases
# one single moment in time
# --keep N afterwards keep only the newest N backups (default: keep all)
#
# Result: /var/backups/ovpmon/<UTC timestamp>/ (mode 700, files mode 600; OVPMON_BACKUP_DIR changes the root):
# database copies, /etc/ovpmon, /etc/openvpn, PKI (easy-rsa), client profiles, code with virtualenvs, helper,
# service definitions, nginx site, UI files, doas rules, MANIFEST, SHA256SUMS and COMPLETE (written last).
# Exit code 0 only if the backup was written and verified. Restore: deploy/native/restore.sh <directory>
# The backup holds private keys and password hashes: keep it private and store copies off the host.
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
STOP=0
KEEP=""
STOPPED=0
FORCE=1
cleanup() {
_rc=$?
set +e
if [ "$STOPPED" = 1 ]; then
log "starting the application services again"
start_app_services >/dev/null 2>&1 || warn "could not start all services again: start them (ovpmon-api, ovpmon-gatherer, ovpmon-profiler)"
STOPPED=0
fi
release_lock
exit "$_rc"
}
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$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_root
check_os
require_init
check_gnu_tar
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
[ -d "$PREFIX/APP_CORE" ] && [ -d "$PREFIX/APP_PROFILER" ] && [ -f "$ENV_FILE" ] \
|| die "no installation found (need $PREFIX/APP_CORE, $PREFIX/APP_PROFILER and $ENV_FILE): wrong --prefix?"
log "backup of the installation in $PREFIX"
mkdir -p "$BACKUP_ROOT"
chmod 700 "$BACKUP_ROOT"
_kb=$(du -sk "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$DATA_DIR" "$ETC_DIR" /etc/openvpn "$WEB_ROOT" 2>/dev/null | awk '{ s += $1 } END { print s + 0 }')
_need=$(( _kb / 1024 + 50 ))
[ "$_need" -ge "$MIN_FREE_BACKUP_MB" ] || _need="$MIN_FREE_BACKUP_MB"
check_free "$BACKUP_ROOT" "$_need" "the backup"
BACKUP_DIR="$BACKUP_ROOT/$(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 ]; then
_any=0
for _s in $SERVICES; do svc_active "$_s" && _any=1; done
if [ "$_any" = 1 ]; then
log "stopping the application services for a single-moment copy"
STOPPED=1
stop_app_services || die "could not stop the services"
fi
fi
make_backup "$BACKUP_DIR" backup "$PREFIX" || 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"
+70
View File
@@ -0,0 +1,70 @@
#!/bin/sh
# Build the web UI (APP_UI, Vue/Vite) in a Node 20 container into a tarball for install.sh / update.sh.
#
# deploy/native/build-ui.sh [-o FILE] [--image IMAGE]
#
# -o FILE output tarball (default: deploy/native/ui-dist.tar.gz); its top level is the content of dist/
# --image IMAGE Node image (default node:20-alpine, or OVPMON_NODE_IMAGE)
#
# Needs Docker on the machine that builds (not on the target host, which needs no Node at all).
# Nothing is written into the source tree: APP_UI is mounted read-only and copied inside the
# container; only the output file is created. Then, on the target host:
# deploy/native/install.sh --ui-dist deploy/native/ui-dist.tar.gz
# deploy/native/update.sh --ui-dist deploy/native/ui-dist.tar.gz
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
log() { printf '%s %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
usage() { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; }
OUT="$SCRIPT_DIR/ui-dist.tar.gz"
IMAGE="${OVPMON_NODE_IMAGE:-node:20-alpine}"
while [ $# -gt 0 ]; do
case "$1" in
-o) [ $# -ge 2 ] || die "-o needs a value"; OUT="$2"; shift 2 ;;
--image) [ $# -ge 2 ] || die "--image needs a value"; IMAGE="$2"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
command -v docker >/dev/null 2>&1 || die "docker not found in PATH. This script builds the UI in a Node 20 container; install Docker on the build machine (the target host does not need it), or build APP_UI yourself (npm install && npm run build) and pack the content of dist/ as a .tar.gz with index.html at its top level"
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)"
[ -f "$ROOT_DIR/APP_UI/package.json" ] || die "APP_UI/package.json not found in $ROOT_DIR"
case "$OUT" in /*) ;; *) OUT="$PWD/$OUT" ;; esac
OUT_DIR=$(dirname "$OUT")
OUT_NAME=$(basename "$OUT")
mkdir -p "$OUT_DIR"
OUT_DIR=$(cd "$OUT_DIR" && pwd)
TMP_NAME=".$OUT_NAME.tmp.$$"
trap 'rm -f "$OUT_DIR/$TMP_NAME"' EXIT
log "building the UI with $IMAGE (APP_UI is mounted read-only, nothing is written into the source tree)"
# npm ci when a lock file exists (reproducible), npm install otherwise (as the all-in-one Dockerfile)
docker run --rm \
-v "$ROOT_DIR/APP_UI":/src:ro \
-v "$OUT_DIR":/out \
-e TMP_NAME="$TMP_NAME" -e HOST_UID="$(id -u)" -e HOST_GID="$(id -g)" \
"$IMAGE" sh -c '
set -eu
mkdir /build
tar -C /src --exclude=node_modules --exclude=dist -cf - . | tar -C /build -xf -
cd /build
if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi
npm run build
[ -f dist/index.html ] || { echo "build produced no dist/index.html" >&2; exit 1; }
tar -czf "/out/$TMP_NAME" -C dist .
chown "$HOST_UID:$HOST_GID" "/out/$TMP_NAME"
' || die "the UI build failed (see the output above)"
tar -tzf "$OUT_DIR/$TMP_NAME" | grep -q -E '^(\./)?index\.html$' || die "the archive has no index.html"
mv "$OUT_DIR/$TMP_NAME" "$OUT"
trap - EXIT
log "UI archive written: $OUT ($(du -h "$OUT" | awk '{print $1}'))"
log "use it with: deploy/native/install.sh --ui-dist $OUT or deploy/native/update.sh --ui-dist $OUT"
+444
View File
@@ -0,0 +1,444 @@
#!/bin/sh
# Install OpenVPN Monitor & Profiler as system services (no containers): Alpine (OpenRC), Debian, Ubuntu (systemd).
#
# deploy/native/install.sh [--prefix DIR] [--ui-dist FILE] [--https-port N] [--host-name NAME]
# [--admin-user NAME] [--force]
#
# --prefix install directory (default /opt/OpenVPN-Monitoring-Simple): APP_CORE, APP_PROFILER, venvs
# --ui-dist UI tarball made by deploy/native/build-ui.sh (the host needs no Node). Without it a
# placeholder page is installed; add the UI later with update.sh --ui-dist
# --https-port HTTPS port of the web UI (default 8088)
# --host-name DNS name or IP of this host: certificate name and CORS origin (default: detected address)
# --admin-user login of the initial administrator (default: admin); the password is generated
# --force continue on an untested OS version / Debian derivative
#
# Run as root from a checkout of the repository. Refuses when an installation exists (use update.sh).
# After a failure it is safe to run again: every step is idempotent and nothing is generated twice.
# It does NOT touch the firewall: NAT/forwarding commands are printed and documented.
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX="$DEFAULT_PREFIX"
UI_DIST=""
HTTPS_PORT=8088
HOST_NAME=""
ADMIN_USER="admin"
FORCE=0
CURRENT_PHASE="start"
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--ui-dist) [ $# -ge 2 ] || die "--ui-dist needs a value"; UI_DIST="$2"; shift 2 ;;
--https-port) [ $# -ge 2 ] || die "--https-port needs a value"; HTTPS_PORT="$2"; shift 2 ;;
--host-name) [ $# -ge 2 ] || die "--host-name needs a value"; HOST_NAME="$2"; shift 2 ;;
--admin-user) [ $# -ge 2 ] || die "--admin-user needs a value"; ADMIN_USER="$2"; shift 2 ;;
--force) FORCE=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
valid_prefix "$PREFIX" || die "invalid --prefix '$PREFIX' (absolute path of letters, digits, . _ - and /)"
valid_port "$HTTPS_PORT" || die "invalid --https-port '$HTTPS_PORT'"
case "$ADMIN_USER" in
""|*[!A-Za-z0-9._-]*) die "invalid --admin-user (letters, digits, . _ - only)" ;;
esac
case "$HOST_NAME" in
*[!A-Za-z0-9.-]*) die "invalid --host-name (letters, digits, . and - only)" ;;
esac
[ -z "$UI_DIST" ] || case "$UI_DIST" in /*) ;; *) UI_DIST="$PWD/$UI_DIST" ;; esac
SRC="$ROOT_DIR"
on_exit() {
_rc=$?
set +e
trap '' INT TERM
if [ "$_rc" -ne 0 ]; then
log "install stopped in phase '$CURRENT_PHASE'. Nothing is lost: fix the cause and run the script again (it resumes; existing secrets, certificates and data are kept)" >&2
fi
[ -z "${TMPD:-}" ] || rm -rf "$TMPD"
release_lock
exit "$_rc"
}
TMPD=$(mktemp -d /tmp/ovpmon-install.XXXXXX) || die "cannot create a temporary directory"
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="0 preflight"
phase 0 "preflight"
need_root
check_os
require_init
acquire_lock
# An existing installation is updated, not installed over
if [ -f "$STATE_FILE" ]; then
die "already installed (state file $STATE_FILE). To upgrade use: $SCRIPT_DIR/update.sh"
fi
if [ ! -f "$INCOMPLETE_MARK" ]; then
for _p in "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$ENV_FILE" "$(unit_file ovpmon-api)"; do
if [ -e "$_p" ]; then
die "an installation already exists ($_p). install.sh never installs over one. To upgrade or adopt it use: $SCRIPT_DIR/update.sh"
fi
done
fi
[ -f "$SRC/APP_CORE/openvpn_api_v3.py" ] && [ -f "$SRC/APP_PROFILER/main.py" ] \
|| die "run the script from a complete checkout of the repository (APP_CORE and APP_PROFILER not found in $SRC)"
if [ -z "$UI_DIST" ] && [ -f "$SCRIPT_DIR/ui-dist.tar.gz" ]; then
UI_DIST="$SCRIPT_DIR/ui-dist.tar.gz"
log "using the UI archive $UI_DIST"
fi
if [ -n "$UI_DIST" ]; then
check_ui_archive "$UI_DIST"
else
warn "no --ui-dist: a placeholder page is installed instead of the web UI (build it with deploy/native/build-ui.sh, then update.sh --ui-dist FILE)"
fi
# ports: ours may already be bound when the script is resumed
if svc_active ovpmon-api 2>/dev/null; then
log "ovpmon services are already running (resumed install): application ports not checked"
else
check_port 5001 tcp "monitoring API"
check_port 8000 tcp "profiler API"
fi
if [ ! -f "$NGINX_SITE" ]; then
check_port "$HTTPS_PORT" tcp "HTTPS (UI)"
fi
if port_in_use 1194 udp; then log "note: 1194/udp is in use; OpenVPN uses the port set in the server settings of the UI"; fi
check_free "$PREFIX" "$MIN_FREE_PREFIX_MB" "the installation (code and virtualenvs)"
check_free /var/lib 256 "data"
mkdir -p "$ETC_DIR"
chmod 755 "$ETC_DIR"
: > "$INCOMPLETE_MARK"
chmod 600 "$INCOMPLETE_MARK"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="1 packages"
phase 1 "packages"
log "installing: $PKG_LIST"
# shellcheck disable=SC2086
pkg_install $PKG_LIST
check_gnu_tar
python3 -c 'import sys, sqlite3, venv; sys.exit(0 if sys.version_info >= (3, 9) else 1)' \
|| die "Python 3.9 or newer with the sqlite3 and venv modules is required (found: $(python3 --version 2>&1))"
for _c in curl openssl nginx openvpn; do
command -v "$_c" >/dev/null 2>&1 || die "$_c is not available after the package installation"
done
[ -f "$EASYRSA_SRC/easyrsa" ] || die "$EASYRSA_SRC/easyrsa not found (package easy-rsa)"
check_nginx_include
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="2 user and directories"
phase 2 "service user and directories"
ensure_service_user
ensure_dir "$DATA_DIR" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$DATA_DIR/staging" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$APP_LOG_DIR" "$SERVICE_USER:$SERVICE_USER" 750
ensure_dir "$OVPN_LOG_DIR" root:root 755
# distribution-owned directories are only created when missing, never re-owned
for _d in /etc/openvpn "$(dirname "$OVPN_CONFIG")"; do
if [ ! -d "$_d" ]; then mkdir -p "$_d"; chmod 755 "$_d"; fi
done
ensure_dir /etc/openvpn/scripts root:root 755
# status log: written by OpenVPN (root), read by the gatherer (group ovpmon); the helper keeps these rights
if [ ! -e "$OVPN_LOG_DIR/openvpn-status.log" ]; then : > "$OVPN_LOG_DIR/openvpn-status.log"; fi
chown root:"$SERVICE_USER" "$OVPN_LOG_DIR/openvpn-status.log"
chmod 640 "$OVPN_LOG_DIR/openvpn-status.log"
log "directories ready: $DATA_DIR, $APP_LOG_DIR, $OVPN_LOG_DIR, /etc/openvpn/scripts, $ETC_DIR"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="3 code"
phase 3 "application code to $PREFIX"
mkdir -p "$PREFIX"
chmod 755 "$PREFIX"
copy_component "$SRC/APP_CORE" "$PREFIX/APP_CORE"
copy_component "$SRC/APP_PROFILER" "$PREFIX/APP_PROFILER"
sync_deploy_files "$SRC" "$PREFIX"
echo "$(version_of "$SRC")" > "$PREFIX/VERSION"
log "code installed (version $(cat "$PREFIX/VERSION")); the virtualenvs and data are not part of the copy"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="4 virtualenvs and easy-rsa"
phase 4 "Python virtualenvs and the easy-rsa workspace"
make_venv "$PREFIX/APP_CORE" gunicorn
make_venv "$PREFIX/APP_PROFILER"
smoke_component "$PREFIX/APP_CORE" core || die "the APP_CORE virtualenv cannot import the application's dependencies"
smoke_component "$PREFIX/APP_PROFILER" profiler || die "the APP_PROFILER virtualenv cannot import the application's dependencies"
log "dependencies import correctly"
# easy-rsa workspace: real directory owned by the service user (never a symlink); never overwritten
if [ ! -f "$PREFIX/APP_PROFILER/easy-rsa/easyrsa" ]; then
mkdir -p "$PREFIX/APP_PROFILER/easy-rsa"
cp -R "$EASYRSA_SRC"/. "$PREFIX/APP_PROFILER/easy-rsa/"
chown -R "$SERVICE_USER:$SERVICE_USER" "$PREFIX/APP_PROFILER/easy-rsa"
chmod 750 "$PREFIX/APP_PROFILER/easy-rsa"
log "easy-rsa workspace created from $EASYRSA_SRC"
else
log "easy-rsa workspace exists: kept"
fi
ensure_runtime_files "$PREFIX"
lock_down_code "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER"
compile_code "$PREFIX/APP_CORE"
compile_code "$PREFIX/APP_PROFILER"
log "code and virtualenvs are root-owned and read-only for the service user; easy-rsa, client-config and profiler.log belong to $SERVICE_USER"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="5 configuration"
phase 5 "configuration: environment file, root helper, doas, forwarding"
detect_ip() {
local ip
ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -n 1 || true)
[ -n "$ip" ] || ip=$(hostname -i 2>/dev/null | awk '{print $1}' || true)
case "$ip" in ""|127.*) ip="" ;; esac
printf '%s' "$ip"
}
HOST_IP=$(detect_ip)
CERT_HOST="${HOST_NAME:-${HOST_IP:-localhost}}"
SHOW_USER=""
SHOW_PASSWORD=""
if [ -f "$ENV_FILE" ]; then
log "$ENV_FILE exists and is kept as it is"
else
SECRET=$(openssl rand -hex 32 2>/dev/null || true)
[ "${#SECRET}" -eq 64 ] || SECRET=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
[ "${#SECRET}" -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/native/install.sh on $(date -u '+%Y-%m-%d %H:%M:%S') UTC. root:root 600: keep it private, never commit it."
echo "# Read by the init system (systemd EnvironmentFile / OpenRC start_pre) as root; the services run as $SERVICE_USER."
echo "OVPMON_API_SECRET_KEY=$SECRET"
echo "OVPMON_API_HOST=127.0.0.1"
echo "OVPMON_API_PORT=5001"
echo "OVPMON_OPENVPN_MONITOR_DB_PATH=$DATA_DIR/openvpn_monitor.db"
echo "OVPMON_OPENVPN_MONITOR_LOG_PATH=$OVPN_LOG_DIR/openvpn-status.log"
echo "OVPMON_PROFILER_DB_PATH=$DATA_DIR/ovpn_profiler.db"
echo "OVPMON_LOGGING_LEVEL=INFO"
echo "OVPMON_CORS_ORIGINS=https://$CERT_HOST:$HTTPS_PORT"
echo "# This is a host install, never a container (matters when the host itself runs inside a container)"
echo "OVPMON_RUNTIME=host"
echo "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE"
echo "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"
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"
} > "$ENV_FILE"
)
chown root:root "$ENV_FILE"
chmod 600 "$ENV_FILE"
unset SECRET ADMIN_PASSWORD
log "$ENV_FILE created (root:root 600, random secret)"
fi
# helper configuration (read by the root helper; strictly validated there)
_tmp="$TMPD/helper.conf"
helper_conf_text "$PREFIX" > "$_tmp"
if install_managed "$_tmp" "$HELPER_CONF" 644 "deploy/native/lib.sh helper_conf_text"; then log "$HELPER_CONF written (root:root 644)"; else log "$HELPER_CONF unchanged"; fi
[ -f "$HELPER_CONF" ] || die "$HELPER_CONF could not be written"
if install_helper "$SRC"; then log "helper installed: $HELPER_DEST (root:root 755)"; else log "helper unchanged: $HELPER_DEST"; fi
rc=0
install_doas "$SRC" || rc=$?
doas_target
case "$rc" in
0) log "doas rules installed ($DOAS_MODE: $DOAS_FILE)" ;;
1) log "doas rules unchanged ($DOAS_FILE)" ;;
2) warn "doas rules NOT installed: add the rules of DOCS/General/privilege-separation/doas-ovpmon.conf to $DOAS_FILE yourself" ;;
esac
if doas_selftest; then log "self-test: $SERVICE_USER can call the helper through doas"; else warn "the helper self-test failed: the profiler will not be able to configure or start OpenVPN until this is fixed"; fi
# IP forwarding (persistent) and the OpenVPN service prerequisites
printf '# %s\nnet.ipv4.ip_forward = 1\n' "$MARKER" > "$SYSCTL_FILE"
chmod 644 "$SYSCTL_FILE"
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || warn "could not enable net.ipv4.ip_forward now (it is set for the next boot); on a container the host must allow it"
if [ "$INIT" = openrc ]; then
rc-update add sysctl boot >/dev/null 2>&1 || true
fi
if [ "$OS_FAMILY" = alpine ]; then
# the OpenRC service reads /etc/openvpn/openvpn.conf: link it to server.conf (as the helper does)
if [ ! -e /etc/openvpn/openvpn.conf ] && [ ! -L /etc/openvpn/openvpn.conf ]; then
ln -s server.conf /etc/openvpn/openvpn.conf
log "/etc/openvpn/openvpn.conf -> server.conf"
fi
fi
svc_enable "$OVPN_SERVICE" || warn "could not enable the OpenVPN service $OVPN_SERVICE"
log "OpenVPN service $OVPN_SERVICE enabled, NOT started (no server.conf yet: generate it in the UI first)"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="6 services, UI, nginx"
phase 6 "service definitions, web UI, TLS certificate and nginx"
for s in $SERVICES; do
_tmp="$TMPD/$s"
render_unit "$SRC" "$s" "$PREFIX" "$_tmp"
if [ "$INIT" = systemd ]; then _mode=644; else _mode=755; fi
rc=0
install_managed "$_tmp" "$(unit_file "$s")" "$_mode" "$(unit_src "$SRC" "$s")" || rc=$?
case "$rc" in
0) log "installed $(unit_file "$s")" ;;
1) log "unchanged $(unit_file "$s")" ;;
2) warn "$(unit_file "$s") is not ours: left untouched" ;;
esac
done
svc_defs_reload
for s in $SERVICES; do svc_enable "$s" || warn "could not enable $s"; done
log "services enabled at boot: $SERVICES"
# UI files
mkdir -p "$(dirname "$WEB_ROOT")"
if [ -n "$UI_DIST" ]; then
stage_ui "$UI_DIST" "$WEB_ROOT.new"
swap_dir "$WEB_ROOT.new" "$WEB_ROOT" "$WEB_ROOT.old"
rm -rf "$WEB_ROOT.old"
log "UI files installed to $WEB_ROOT from $UI_DIST"
elif [ ! -f "$WEB_ROOT/index.html" ]; then
mkdir -p "$WEB_ROOT"
cat > "$WEB_ROOT/index.html" <<'EOF'
<!doctype html><meta charset="utf-8"><title>OpenVPN Monitor</title>
<h1>OpenVPN Monitor</h1><p>The web UI is not installed yet. Build it with deploy/native/build-ui.sh and run deploy/native/update.sh --ui-dist FILE.</p>
EOF
chmod -R a+rX "$WEB_ROOT"
log "placeholder page written to $WEB_ROOT"
fi
# TLS certificate: self-signed, never regenerated
mkdir -p "$TLS_DIR"
chmod 750 "$TLS_DIR"
if [ -f "$TLS_DIR/ovpmon.crt" ] && [ -f "$TLS_DIR/ovpmon.key" ]; then
log "TLS certificate exists: kept ($TLS_DIR/ovpmon.crt)"
else
SAN="DNS:ovpmon,DNS:localhost,IP:127.0.0.1"
[ -z "$HOST_IP" ] || SAN="$SAN,IP:$HOST_IP"
if [ -n "$HOST_NAME" ] && [ "$HOST_NAME" != "$HOST_IP" ]; then
case "$HOST_NAME" in
*[!0-9.]*) SAN="$SAN,DNS:$HOST_NAME" ;;
*) SAN="$SAN,IP:$HOST_NAME" ;;
esac
fi
( umask 077
openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 825 \
-subj "/CN=$CERT_HOST" -addext "subjectAltName=$SAN" \
-keyout "$TLS_DIR/ovpmon.key" -out "$TLS_DIR/ovpmon.crt" >/dev/null 2>&1 ) \
|| die "cannot create the self-signed certificate"
chmod 600 "$TLS_DIR/ovpmon.key"
chmod 644 "$TLS_DIR/ovpmon.crt"
log "self-signed TLS certificate created for $SAN"
fi
# nginx site
_tmp="$TMPD/ovpmon.conf"
mkdir -p "$NGINX_CONF_DIR"
render_nginx "$SRC" "$HTTPS_PORT" "$_tmp"
rc=0
install_managed "$_tmp" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
case "$rc" in
0) log "nginx site written: $NGINX_SITE (HTTPS on $HTTPS_PORT)" ;;
1) log "nginx site unchanged: $NGINX_SITE" ;;
2) die "$NGINX_SITE exists and is not ours; remove or rename it, then run the script again" ;;
esac
svc_enable nginx || warn "could not enable nginx at boot"
nginx_apply || die "nginx did not accept the configuration (see above)"
log "nginx running with the new site"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="7 start and health checks"
phase 7 "start the services and check them"
for s in $SERVICES; do
if svc_active "$s"; then
log "restarting $s (resumed install)"
svc_restart "$s" >/dev/null 2>&1 || { show_service_log "$s"; die "$s failed to restart"; }
else
log "starting $s"
svc_start "$s" >/dev/null 2>&1 || { show_service_log "$s"; die "$s failed to start"; }
fi
done
health_check "$HTTPS_PORT" || die "health checks failed (see above). Logs: $APP_LOG_DIR/ (OpenRC) or journalctl -u ovpmon-api -u ovpmon-gatherer -u ovpmon-profiler (systemd)"
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="8 initial administrator"
phase 8 "initial administrator"
resolve_db_paths "$PREFIX"
if [ -n "$(env_get OVPMON_INITIAL_ADMIN_USER)$(env_get OVPMON_INITIAL_ADMIN_PASSWORD)" ]; then
COUNT=$(users_count "$DB_MONITOR" || true)
case "$COUNT" in
""|*[!0-9]*)
warn "cannot read the users table (got '$COUNT'): OVPMON_INITIAL_ADMIN_* are LEFT in $ENV_FILE. Remove them by hand after you have logged in, then restart ovpmon-api"
;;
0)
warn "the users table is empty: the administrator was not created. OVPMON_INITIAL_ADMIN_* stay in $ENV_FILE. Check the log of ovpmon-api"
;;
*)
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_FILE, restarting ovpmon-api without them"
if ! svc_restart ovpmon-api >/dev/null 2>&1 || ! wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]'; then
# the seed is gone from the file: the one-time credentials must not be lost
printf '\n Administrator (shown ONCE): login %s, password %s\n' "$SHOW_USER" "$SHOW_PASSWORD"
die "ovpmon-api did not come back after removing the seed (see its log)"
fi
;;
esac
else
COUNT=$(users_count "$DB_MONITOR" || true)
case "$COUNT" in
0) warn "no users exist and $ENV_FILE has no OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD: add them and restart ovpmon-api" ;;
*) log "users already exist: nothing to seed" ;;
esac
fi
# ---------------------------------------------------------------------------------------------
CURRENT_PHASE="finish"
state_set OVPMON_PREFIX "$PREFIX"
state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
state_set OVPMON_VERSION "$(cat "$PREFIX/VERSION")"
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "$(now_iso)"
rm -f "$INCOMPLETE_MARK"
UPLINK=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* dev \([^ ]*\).*/\1/p' | head -n 1 || true)
UPLINK="${UPLINK:-<uplink-interface>}"
FP=$(openssl x509 -noout -fingerprint -sha256 -in "$TLS_DIR/ovpmon.crt" 2>/dev/null | sed 's/^.*=//' || true)
printf '\n'
log "=== INSTALLED: $OS_ID $OS_VERSION_ID, $INIT, prefix $PREFIX ==="
printf ' Web UI: https://%s:%s/ (self-signed certificate; SHA-256 %s)\n' "${HOST_NAME:-${HOST_IP:-<server-address>}}" "$HTTPS_PORT" "${FP:-n/a}"
printf ' Config: %s (root:root 600), helper: %s, %s\n' "$ENV_FILE" "$HELPER_CONF" "$HELPER_DEST"
printf ' Data: %s (databases), %s/APP_PROFILER/easy-rsa (PKI), %s/APP_PROFILER/client-config\n' "$DATA_DIR" "$PREFIX" "$PREFIX"
printf ' Logs: %s, %s\n' "$APP_LOG_DIR" "$OVPN_LOG_DIR"
if [ -n "$SHOW_PASSWORD" ]; then
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"
fi
cat <<EOF
Next steps:
1. Open the Web UI and sign in; change the password and enable 2FA (Account).
2. PKI Configuration -> Initialize PKI (wait until it finishes).
3. Generate the server configuration and start the VPN server in the UI
(the profiler installs $OVPN_CONFIG through the root helper and controls $OVPN_SERVICE).
4. Firewall (NOT configured by this script): open ${HTTPS_PORT}/tcp and the VPN port (1194/udp by default),
and give the VPN clients internet access, for example (replace the subnet with the one of the server settings):
iptables -t nat -A POSTROUTING -s 172.20.1.0/24 -o $UPLINK -j MASQUERADE
iptables -A FORWARD -i tun+ -o $UPLINK -j ACCEPT
iptables -A FORWARD -i $UPLINK -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
net.ipv4.ip_forward is enabled ($SYSCTL_FILE). Persistence and nftables variants: see the guide.
5. Replace the self-signed certificate ($TLS_DIR/ovpmon.crt and .key) with a real one when a domain is available.
Update later with: $SCRIPT_DIR/update.sh Backup: $SCRIPT_DIR/backup.sh
Log of this run: $DEPLOY_LOG
EOF
+1135
View File
File diff suppressed because it is too large. Load diff
+75
View File
@@ -0,0 +1,75 @@
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
#
# HTTPS site of OpenVPN Monitor & Profiler. Rendered by install.sh / update.sh: they fill in the HTTPS port
# (default 8088), the UI directory (/var/www/ovpmon) and the certificate and key paths (/etc/ovpmon/tls/ovpmon.crt
# and .key: self-signed by install.sh; replace them with a real certificate under the same names, or edit this
# file and remove the marker line above so that updates leave it alone).
# Installed to the nginx include directory (Alpine /etc/nginx/http.d, Debian/Ubuntu /etc/nginx/conf.d),
# both are included in the http {} block of the distribution nginx.conf. No ssl_session_cache is declared
# here on purpose: a second "shared:SSL" zone with another size would conflict with nginx.conf.
# Reference: DOCS/General/Nginx_Configuration.md, APP_UI/default.conf.template
# 5 login attempts per minute per client address (the application has its own lockout as well)
limit_req_zone $binary_remote_addr zone=ovpmon_login:1m rate=5r/m;
server {
listen @HTTPS_PORT@ ssl;
server_name _;
ssl_certificate @TLS_CRT@;
ssl_certificate_key @TLS_KEY@;
ssl_protocols TLSv1.2 TLSv1.3;
server_tokens off;
client_max_body_size 2m;
# Plain HTTP on the TLS port: redirect to HTTPS
error_page 497 =301 https://$host:@HTTPS_PORT@$request_uri;
# Security headers (declared only here: add_header in a location would drop these)
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
add_header Cache-Control "no-store" always;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
root @WEB_ROOT@;
index index.html;
# UI (single-page application)
location / {
try_files $uri $uri/ /index.html;
}
# Login: rate limited
location = /api/auth/login {
limit_req zone=ovpmon_login burst=3 nodelay;
limit_req_status 503;
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Monitoring API (Flask, APP_CORE)
location /api/ {
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header Authorization;
}
# Profiler API (FastAPI, APP_PROFILER): /profiles-api/x is /api/x inside the profiler
location /profiles-api/ {
proxy_pass http://127.0.0.1:8000/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix /profiles-api;
proxy_read_timeout 120s;
}
}
+91
View File
@@ -0,0 +1,91 @@
#!/bin/sh
# Restore an installation from a backup directory (made by backup.sh or update.sh).
#
# deploy/native/restore.sh BACKUP_DIR [--prefix DIR] [--yes] [--start]
#
# BACKUP_DIR e.g. /var/backups/ovpmon/20261005T101500Z
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --start start the services after the restore (default: only print the command)
#
# The application services are stopped (after confirmation). The CURRENT state is first saved to
# <backups>/<timestamp>-pre-restore (OVPMON_NO_SAFETY_BACKUP=1 skips it); then code, databases,
# /etc/ovpmon, /etc/openvpn, PKI, client profiles, helper, service definitions, nginx site, UI and doas
# rules are put back from the backup. OpenVPN is not touched. The packages and the ovpmon user must
# exist (on a new host run install.sh first, then restore).
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
ASSUME_YES=0
START=0
SRC=""
FORCE=1
RESTORE_STAMP=$(stamp)
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$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=$(abs_dir "$SRC")
trap release_lock EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
need_root
check_os
require_init
check_gnu_tar
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX=$(manifest_get "$SRC" prefix)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
getent passwd "$SERVICE_USER" >/dev/null 2>&1 || die "user $SERVICE_USER does not exist: run install.sh first"
BK_PREFIX=$(manifest_get "$SRC" prefix)
if [ -n "$BK_PREFIX" ] && [ "$BK_PREFIX" != "$PREFIX" ]; then
die "the backup was made for install directory '$BK_PREFIX', this host uses '$PREFIX' (use --prefix $BK_PREFIX)"
fi
log "backup: $SRC"
[ -f "$SRC/MANIFEST" ] && sed 's/^/ /' "$SRC/MANIFEST"
[ -f "$SRC/COMPLETE" ] || warn "the backup is not marked COMPLETE (an interrupted backup?)"
[ "$(manifest_get "$SRC" init)" = "$INIT" ] || warn "the backup comes from a host with service manager '$(manifest_get "$SRC" init)', this one uses '$INIT': service definitions and the helper configuration are restored as saved"
log "verifying the backup"
verify_backup "$SRC" || die "the backup is damaged or incomplete: nothing was changed"
log "code, databases, configuration, PKI and client profiles will be REPLACED by this backup (the current state is saved first)"
confirm "Stop the services and restore?" || die "aborted by the user"
stop_app_services || die "could not stop the application services"
if [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then
_safe="$BACKUP_ROOT/$(stamp)-pre-restore"
log "saving the current state first: $_safe"
mkdir -p "$BACKUP_ROOT"; chmod 700 "$BACKUP_ROOT"
make_backup "$_safe" pre-restore "$PREFIX" || die "the safety backup failed: nothing was changed"
fi
restore_all "$SRC" "$PREFIX" full || die "the restore failed (see above). The backup is intact: $SRC"
log "restore complete"
if [ "$START" = 1 ]; then
svc_defs_reload || true
start_app_services || die "the services did not start after the restore"
health_check "$(state_get OVPMON_HTTPS_PORT)" || die "the health checks failed after the restore"
else
log "start the services when ready: $(for _s in $SERVICES; do printf '%s ' "$_s"; done)(rc-service <name> start / systemctl start <name>)"
fi
+486
View File
@@ -0,0 +1,486 @@
#!/bin/sh
# Update OpenVPN Monitor & Profiler (system services) without touching the data.
#
# deploy/native/update.sh [--prefix DIR] [--ui-dist FILE] [--source DIR] [--no-pull] [--yes] [--rollback]
#
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
# --ui-dist UI tarball from build-ui.sh; without it the UI files are left as they are
# --source checkout with the new version (default: the repository this script is in)
# --no-pull no "git pull --ff-only" of the source checkout (offline hosts, sources already in place)
# --yes no confirmation questions
# --rollback restore code, databases, configuration, PKI and client profiles from the newest backup
#
# Phases: 0 preflight, 1 BACKUP (verified, /var/backups/ovpmon/<UTC time>/), 2 git pull, 3 PREPARE the new
# code and virtualenvs next to the install dir (old code untouched), 4 STOP the application services (OpenVPN
# keeps running) and swap the code in, 5 DATABASE MIGRATION as its own step with the new code (nothing is
# started on an unmigrated database), 6 UI, nginx, helper, doas rules, service definitions, 7 START and health
# checks. A failure after the stop triggers an automatic rollback from the backup of this run.
# The PKI (easy-rsa), client profiles and databases are never replaced or deleted by an update.
# See DOCS/Deployment/Scenario2_System_Services.md and DOCS/General/Database_Migrations.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
usage() {
sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//'
}
PREFIX=""
UI_DIST=""
SOURCE=""
NO_PULL=0
ASSUME_YES=0
DO_ROLLBACK=0
FORCE=1 # an update never refuses on an untested OS version (install.sh decides that)
BACKUP_DIR=""
CURRENT_PHASE="start"
ROLLBACK_ARMED=0
SWAP_BEGAN=0
STAMP=$(stamp)
RESTORE_STAMP="$STAMP"
STAGING=""
HTTPS_PORT=""
OLD_VERSION="unknown"
NEW_VERSION="unknown"
UI_STAGED=0
SERVICES_WERE_RUNNING=0
# ---------------------------------------------------------------------------------------------
# Rollback
# ---------------------------------------------------------------------------------------------
rollback_failed() {
log "!!! ROLLBACK FAILED: $1" >&2
log "!!! Your data is safe in the backup: $BACKUP_DIR" >&2
log "!!! Retry: $SCRIPT_DIR/update.sh --rollback (or restore everything: $SCRIPT_DIR/restore.sh $BACKUP_DIR)" >&2
}
# Automatic rollback after a failure from phase 4 on (called from the EXIT trap)
auto_rollback() {
printf '\n' >&2
log "!!! UPDATE FAILED in phase: $CURRENT_PHASE" >&2
stop_app_services >/dev/null 2>&1 || true
if [ "$SWAP_BEGAN" = 1 ]; then
log "!!! Automatic rollback: code, databases, configuration and system files are restored from $BACKUP_DIR" >&2
RESTORE_STAMP="$STAMP"
if ! restore_all "$BACKUP_DIR" "$PREFIX" auto; then
rollback_failed "the restore from the backup failed (see above)"
return 0
fi
else
log "!!! The code was not replaced yet: the old version is started again" >&2
fi
svc_defs_reload || true
if ! start_app_services; then
rollback_failed "the previous version could not be started"
return 0
fi
if ! health_check "$HTTPS_PORT"; then
rollback_failed "the previous version did not become healthy"
return 0
fi
log "!!! ROLLED BACK: the previous version ($OLD_VERSION) runs 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 system was changed. Backup: $BACKUP_DIR" >&2
fi
fi
if [ -n "$STAGING" ] && [ -f "$STAGING/.ovpmon-staging" ]; then rm -rf "$STAGING"; fi
[ "$UI_STAGED" = 0 ] || rm -rf "$WEB_ROOT.new"
[ -z "${TMPD:-}" ] || rm -rf "$TMPD"
release_lock
exit "$_rc"
}
manual_rollback() {
local safe
BACKUP_DIR=$(latest_backup)
[ -n "$BACKUP_DIR" ] || die "no complete backup found in $BACKUP_ROOT"
log "newest complete backup: $BACKUP_DIR"
sed 's/^/ /' "$BACKUP_DIR/MANIFEST"
[ "$(manifest_get "$BACKUP_DIR" prefix)" = "$PREFIX" ] || die "the backup belongs to install directory '$(manifest_get "$BACKUP_DIR" prefix)', not '$PREFIX' (use --prefix)"
log "code, databases, configuration, PKI and client profiles will be REPLACED by this backup; the current state is saved first to $BACKUP_ROOT/<timestamp>-pre-restore"
confirm "Restore from this backup and start the previous version?" || die "aborted by the user"
phase R1 "stop the application services"
stop_app_services || die "could not stop the services"
if [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then
phase R2 "safety backup of the current state"
safe="$BACKUP_ROOT/$(stamp)-pre-restore"
make_backup "$safe" pre-restore "$PREFIX" || die "the safety backup failed: nothing was changed"
log "current state saved: $safe"
fi
phase R3 "restore from the backup"
RESTORE_STAMP="$STAMP"
restore_all "$BACKUP_DIR" "$PREFIX" full || die "the restore failed (see above). The backup is intact: $BACKUP_DIR"
phase R4 "start"
svc_defs_reload || true
start_app_services || die "the services did not start after the restore"
health_check "$HTTPS_PORT" || die "the health checks failed after the restore"
printf '\n'
log "=== ROLLBACK DONE: the state of $BACKUP_DIR is in use ==="
}
# ---------------------------------------------------------------------------------------------
# Phase 5 helper: one component's database, with the NEW code, as the service user with its environment
# ---------------------------------------------------------------------------------------------
migrate_component() { # NAME DIR
local name dir rc out
name="$1"; dir="$2"
log "--- $name database: check ---"
rc=0
out=$(run_as_service_user "$dir" "$dir/venv/bin/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=$(run_as_service_user "$dir" "$dir/venv/bin/python" migrate.py 2>&1) || rc=$?
indent "$out"
[ "$rc" -eq 0 ] || die "$name: the migration failed with exit code $rc"
rc=0
out=$(run_as_service_user "$dir" "$dir/venv/bin/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"
}
# Phase 4 helper: data that lives below a code directory moves to the new one (same file system, rename)
preserve_data() { # OLD_DIR NEW_DIR NAME
local old new item f
old="$1"; new="$2"
if [ "$3" = APP_PROFILER ]; then
for item in easy-rsa client-config profiler.log; do
if [ -e "$old/$item" ] && [ ! -e "$new/$item" ]; then
mv "$old/$item" "$new/$item" || die "cannot move $item to the new code directory"
log " kept $3/$item"
fi
done
fi
# config.ini is configuration: the current one stays, the shipped one is saved next to it
if [ -f "$old/config.ini" ]; then
if [ -f "$new/config.ini" ] && ! cmp -s "$old/config.ini" "$new/config.ini"; then
mv "$new/config.ini" "$new/config.ini.dist"
log " $3/config.ini kept (the shipped one of the new version is config.ini.dist)"
else
rm -f "$new/config.ini"
fi
mv "$old/config.ini" "$new/config.ini"
fi
# legacy data files that older installations kept next to the code (databases, logs)
for f in "$old"/*.db "$old"/*.db-* "$old"/*.log; do
[ -e "$f" ] || continue
item=$(basename "$f")
if [ ! -e "$new/$item" ]; then mv "$f" "$new/$item"; log " kept $3/$item"; fi
done
}
detect_https_port() {
[ -f "$NGINX_SITE" ] || return 0
sed -n 's/^[[:space:]]*listen[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]][[:space:]]*ssl.*/\1/p' "$NGINX_SITE" | head -n 1
}
# apply_file RESULT_CODE LABEL: log what install_managed / install_doas did
report() {
case "$1" in
0) log " updated: $2"; CHANGES=$((CHANGES + 1)) ;;
1) log " unchanged: $2" ;;
*) log " NOT touched (not managed by these scripts): $2" ;;
esac
}
# ---------------------------------------------------------------------------------------------
main() {
while [ $# -gt 0 ]; do
case "$1" in
--prefix) [ $# -ge 2 ] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
--ui-dist) [ $# -ge 2 ] || die "--ui-dist needs a value"; UI_DIST="$2"; shift 2 ;;
--source) [ $# -ge 2 ] || die "--source needs a value"; SOURCE="$2"; shift 2 ;;
--no-pull) NO_PULL=1; shift ;;
--yes|-y) ASSUME_YES=1; shift ;;
--rollback) DO_ROLLBACK=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown option: $1" ;;
esac
done
TMPD=$(mktemp -d /tmp/ovpmon-update.XXXXXX) || die "cannot create a temporary directory"
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
need_root
check_os
require_init
acquire_lock
[ -n "$PREFIX" ] || PREFIX=$(state_get OVPMON_PREFIX)
[ -n "$PREFIX" ] || PREFIX="$DEFAULT_PREFIX"
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
HTTPS_PORT=$(state_get OVPMON_HTTPS_PORT)
[ -n "$HTTPS_PORT" ] || HTTPS_PORT=$(detect_https_port || true)
SOURCE="${SOURCE:-$ROOT_DIR}"
case "$UI_DIST" in ""|/*) ;; *) UI_DIST="$PWD/$UI_DIST" ;; esac
if [ "$DO_ROLLBACK" = 1 ]; then
[ -f "$ENV_FILE" ] || die "$ENV_FILE not found: nothing is installed"
manual_rollback
return 0
fi
# ----- Phase 0 -------------------------------------------------------------------------
CURRENT_PHASE="0 preflight"
phase 0 "preflight"
log "install directory: $PREFIX; source: $SOURCE; backups: $BACKUP_ROOT"
check_gnu_tar
command -v python3 >/dev/null 2>&1 || die "python3 not found"
command -v curl >/dev/null 2>&1 || die "curl not found"
[ ! -f "$INCOMPLETE_MARK" ] || die "an unfinished install.sh run exists ($INCOMPLETE_MARK): run install.sh again to finish it, then update"
[ -d "$PREFIX/APP_CORE" ] && [ -d "$PREFIX/APP_PROFILER" ] && [ -f "$ENV_FILE" ] \
|| die "no installation found (need $PREFIX/APP_CORE, $PREFIX/APP_PROFILER and $ENV_FILE): wrong --prefix? Use install.sh for a new host"
if [ -f "$STATE_FILE" ]; then
log "installed version: $(state_get OVPMON_VERSION), installed $(state_get OVPMON_INSTALLED_AT)"
else
warn "no state file ($STATE_FILE): this installation was not made by install.sh; it is adopted and recorded after a successful update. Files that these scripts do not manage (init scripts, nginx site, doas file) are left as they are"
fi
OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || echo "unknown")
for _f in APP_CORE/openvpn_api_v3.py APP_CORE/openvpn_gatherer_v3.py APP_CORE/migrate.py APP_CORE/requirements.txt \
APP_PROFILER/main.py APP_PROFILER/migrate.py APP_PROFILER/requirements.txt \
DOCS/General/privilege-separation/ovpmon-helper DOCS/General/privilege-separation/doas-ovpmon.conf \
deploy/native/nginx/ovpmon.conf.template; do
[ -f "$SOURCE/$_f" ] || die "the source directory is not a complete checkout: $SOURCE/$_f is missing (--source)"
done
for _s in $SERVICES; do
[ -f "$(unit_src "$SOURCE" "$_s")" ] || die "service definition missing in the source: $(unit_src "$SOURCE" "$_s")"
done
if [ "$(abs_dir "$SOURCE")" = "$(abs_dir "$PREFIX")" ]; then
log "the source is the install directory itself (a checkout used as the install directory): git pull changes the live files, so a rollback is armed from phase 2"
PULL_TOUCHES_LIVE=1
else
PULL_TOUCHES_LIVE=0
fi
if [ -n "$UI_DIST" ]; then
check_ui_archive "$UI_DIST"
log "UI archive: $UI_DIST"
else
log "no --ui-dist: the UI files stay as they are (if APP_UI changed, build and pass a new archive)"
fi
SERVICES_WERE_RUNNING=1
for _s in $SERVICES; do
if svc_known "$_s"; then
log " $_s: $(svc_state_word "$_s")"
svc_active "$_s" || SERVICES_WERE_RUNNING=0
else
log " $_s: no service definition yet (it will be installed)"
SERVICES_WERE_RUNNING=0
fi
done
if [ "$SERVICES_WERE_RUNNING" = 0 ]; then
warn "not all application services are running"
confirm "Continue anyway? (the services will be started at the end)" || die "aborted by the user"
fi
log " OpenVPN ($OVPN_SERVICE): $(svc_state_word "$OVPN_SERVICE") (not touched by the update)"
resolve_db_paths "$PREFIX"
for _d in "$DB_MONITOR" "$DB_PROFILER"; do
if [ -f "$_d" ]; then log "database: $_d ($(du -h "$_d" | awk '{print $1}'))"; else warn "database not found yet: $_d"; fi
done
mkdir -p "$BACKUP_ROOT"
chmod 700 "$BACKUP_ROOT"
_kb=$(du -sk "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER" "$DATA_DIR" "$ETC_DIR" /etc/openvpn "$WEB_ROOT" 2>/dev/null | awk '{ s += $1 } END { print s + 0 }')
_need=$(( _kb / 1024 * 2 + 100 ))
[ "$_need" -ge "$MIN_FREE_BACKUP_MB" ] || _need="$MIN_FREE_BACKUP_MB"
check_free "$BACKUP_ROOT" "$_need" "the backup"
check_free "$(dirname "$PREFIX")" "$MIN_FREE_PREFIX_MB" "the new code and virtualenvs"
log "plan: backup -> git pull -> prepare (staging) -> stop -> swap code -> DATABASE MIGRATION -> files -> start (automatic rollback after the stop)"
confirm "Update now?" || die "aborted by the user"
# ----- Phase 1: backup -----------------------------------------------------------------
CURRENT_PHASE="1 backup"
phase 1 "BACKUP (databases, configuration, PKI, client profiles, code, system files)"
BACKUP_DIR="$BACKUP_ROOT/$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"
if ! make_backup "$BACKUP_DIR" update "$PREFIX"; 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 "$SOURCE" 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
if [ "$PULL_TOUCHES_LIVE" = 1 ]; then ROLLBACK_ARMED=1; SWAP_BEGAN=1; fi # the live files change: restore them on failure
git -C "$SOURCE" pull --ff-only || die "git pull --ff-only failed (local changes, diverged history, no network, or 'dubious ownership': git config --global --add safe.directory $SOURCE). The running system was not changed. Fix the checkout, or use --no-pull"
fi
NEW_VERSION=$(version_of "$SOURCE")
log "source version: $OLD_VERSION -> $NEW_VERSION"
if [ "$NO_PULL" = 0 ] && [ "$PULL_TOUCHES_LIVE" = 0 ]; then
log "note: if deploy/native/*.sh changed, the new versions are used from the next run"
fi
# ----- Phase 3: prepare ----------------------------------------------------------------
CURRENT_PHASE="3 prepare"
phase 3 "PREPARE the new code and virtualenvs (the running system is not touched)"
STAGING="${PREFIX}.new"
if [ -e "$STAGING" ]; then
[ -f "$STAGING/.ovpmon-staging" ] || die "$STAGING exists and was not created by this script: remove or rename it"
rm -rf "$STAGING"
fi
mkdir -p "$STAGING"
: > "$STAGING/.ovpmon-staging"
copy_component "$SOURCE/APP_CORE" "$STAGING/APP_CORE"
copy_component "$SOURCE/APP_PROFILER" "$STAGING/APP_PROFILER"
make_venv "$STAGING/APP_CORE" gunicorn
make_venv "$STAGING/APP_PROFILER"
smoke_component "$STAGING/APP_CORE" core || die "the new APP_CORE virtualenv cannot import the application's dependencies"
smoke_component "$STAGING/APP_PROFILER" profiler || die "the new APP_PROFILER virtualenv cannot import the application's dependencies"
lock_down_code "$STAGING/APP_CORE" "$STAGING/APP_PROFILER"
log "new code and virtualenvs are ready in $STAGING (dependencies installed and importable)"
if [ -n "$UI_DIST" ]; then
stage_ui "$UI_DIST" "$WEB_ROOT.new"
UI_STAGED=1
log "new UI files are ready in $WEB_ROOT.new"
fi
# ----- Phase 4: stop and swap ----------------------------------------------------------
CURRENT_PHASE="4 stop and swap"
phase 4 "STOP the application services (OpenVPN keeps running) and swap the code in"
ROLLBACK_ARMED=1 # from here on a failure restores the backup
stop_app_services || die "could not stop the application services"
log "final consistent snapshot (nothing writes to the databases now)"
make_backup "$BACKUP_DIR" update "$PREFIX" 1 || die "the final snapshot failed"
SWAP_BEGAN=1
for _c in APP_CORE APP_PROFILER; do
mv "$PREFIX/$_c" "$PREFIX/$_c.old-$STAMP" || die "cannot move the old $_c aside"
mv "$STAGING/$_c" "$PREFIX/$_c" || die "cannot move the new $_c into place"
preserve_data "$PREFIX/$_c.old-$STAMP" "$PREFIX/$_c" "$_c"
fix_venv_paths "$PREFIX/$_c" "$STAGING/$_c" "$PREFIX/$_c"
log " $_c replaced (the old one is kept as $_c.old-$STAMP until the update succeeds)"
done
rm -rf "$STAGING"
ensure_runtime_files "$PREFIX"
lock_down_code "$PREFIX/APP_CORE" "$PREFIX/APP_PROFILER"
compile_code "$PREFIX/APP_CORE"
compile_code "$PREFIX/APP_PROFILER"
smoke_component "$PREFIX/APP_CORE" core || die "the relocated APP_CORE virtualenv does not work"
smoke_component "$PREFIX/APP_PROFILER" profiler || die "the relocated APP_PROFILER virtualenv does not work"
log "PKI, client profiles and databases were not touched"
# ----- Phase 5: database migration -----------------------------------------------------
CURRENT_PHASE="5 database migration"
phase 5 "DATABASE MIGRATION (own step; no service is started on an unmigrated database)"
log "run with the NEW code, as user $SERVICE_USER, with the environment of $ENV_FILE; reports below"
migrate_component "profiler" "$PREFIX/APP_PROFILER"
migrate_component "monitoring" "$PREFIX/APP_CORE"
log "all databases are up to date"
# ----- Phase 6: files ------------------------------------------------------------------
CURRENT_PHASE="6 files"
phase 6 "UI, nginx site, helper, doas rules, service definitions"
CHANGES=0
if [ "$UI_STAGED" = 1 ]; then
swap_dir "$WEB_ROOT.new" "$WEB_ROOT" "$WEB_ROOT.old"
UI_STAGED=0
log " UI files replaced (the previous ones are in the backup)"
CHANGES=$((CHANGES + 1))
fi
rc=0; install_helper "$SOURCE" || rc=$?
report "$rc" "$HELPER_DEST"
# helper.conf: written when missing (adopted hosts), kept when it is not ours
helper_conf_text "$PREFIX" > "$TMPD/helper.conf"
rc=0; install_managed "$TMPD/helper.conf" "$HELPER_CONF" 644 "deploy/native/lib.sh helper_conf_text" || rc=$?
report "$rc" "$HELPER_CONF"
rc=0; install_doas "$SOURCE" || rc=$?
doas_target
report "$rc" "doas rules ($DOAS_FILE)"
if [ ! -f "$SYSCTL_FILE" ]; then
printf '# %s\nnet.ipv4.ip_forward = 1\n' "$MARKER" > "$SYSCTL_FILE"; chmod 644 "$SYSCTL_FILE"
log " added: $SYSCTL_FILE"
fi
# service definitions
for _s in $SERVICES; do
render_unit "$SOURCE" "$_s" "$PREFIX" "$TMPD/$_s"
if [ "$INIT" = systemd ]; then _mode=644; else _mode=755; fi
rc=0; install_managed "$TMPD/$_s" "$(unit_file "$_s")" "$_mode" "$(unit_src "$SOURCE" "$_s")" || rc=$?
report "$rc" "$(unit_file "$_s")"
done
svc_defs_reload
for _s in $SERVICES; do svc_enable "$_s" || warn "could not enable $_s at boot"; done
# environment: add the settings of this version when they are missing (existing values are never changed)
for _kv in "OVPMON_RUNTIME=host" "OVPMON_OPENVPN_SERVICE=$OVPN_SERVICE" "OVPMON_OPENVPN_CONFIG=$OVPN_CONFIG"; do
_k=${_kv%%=*}
if [ -z "$(env_get "$_k")" ]; then
kv_set "$ENV_FILE" "$_k" "${_kv#*=}" 600
log " added $_k to $ENV_FILE"
fi
done
# OpenVPN prerequisites that may be missing on an adopted host
[ -d "$(dirname "$OVPN_CONFIG")" ] || { mkdir -p "$(dirname "$OVPN_CONFIG")"; chmod 755 "$(dirname "$OVPN_CONFIG")"; }
[ -d /etc/openvpn/scripts ] || ensure_dir /etc/openvpn/scripts root:root 755
# nginx site (only when it is ours and the port is known)
if [ -n "$HTTPS_PORT" ]; then
render_nginx "$SOURCE" "$HTTPS_PORT" "$TMPD/ovpmon.conf"
rc=0; install_managed "$TMPD/ovpmon.conf" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
report "$rc" "$NGINX_SITE"
if [ "$rc" = 0 ]; then
nginx_apply || die "nginx did not accept the new site (it is restored from the backup)"
log " nginx reloaded"
fi
else
warn "no HTTPS port known (no state file and no nginx site found): the nginx site is not managed"
fi
sync_deploy_files "$SOURCE" "$PREFIX"
echo "$NEW_VERSION" > "$PREFIX/VERSION"
log "$CHANGES file(s) changed in this phase"
# ----- Phase 7: start ------------------------------------------------------------------
CURRENT_PHASE="7 start"
phase 7 "START the services and check them"
start_app_services
if svc_known nginx && ! svc_active nginx; then svc_start nginx >/dev/null 2>&1 || warn "nginx is not running"; fi
health_check "$HTTPS_PORT" || die "the new version did not become healthy"
doas_selftest && log "self-test: $SERVICE_USER can call the helper through doas" || warn "the helper self-test failed: starting OpenVPN from the UI may not work (see $DOAS_FILE and $HELPER_CONF)"
# ----- Done ----------------------------------------------------------------------------
ROLLBACK_ARMED=0
CURRENT_PHASE="finish"
phase 8 "finish"
for _c in APP_CORE APP_PROFILER; do safe_remove_old "$PREFIX/$_c.old-$STAMP"; done
rm -rf "$WEB_ROOT.old"
state_set OVPMON_PREFIX "$PREFIX"
[ -z "$HTTPS_PORT" ] || state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
state_set OVPMON_VERSION "$NEW_VERSION"
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "adopted $(now_iso)"
state_set OVPMON_LAST_UPDATE "$(now_iso)"
prune_backups
printf '\n'
log "=== UPDATE SUCCESSFUL: $OLD_VERSION -> $NEW_VERSION ==="
printf ' Install dir: %s\n' "$PREFIX"
printf ' Backup: %s (the newest %s backups are kept)\n' "$BACKUP_DIR" "$KEEP_BACKUPS"
printf ' Rollback: %s --rollback\n' "$0"
printf ' OpenVPN was not restarted by the update: connected VPN users stayed connected.\n'
printf ' Log of this run: %s\n' "$DEPLOY_LOG"
}
main "$@"; exit $?
+64
View File
@@ -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:
+32 -2
View File
@@ -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: