"""Backup job and restore engine. One background job at a time for the whole service (a backup or a restore), like the async PKI initialization: the state lives in memory of the single Profiler process, results go to the history in ovpmon_backup.db. """ import copy import logging import os import shutil import sqlite3 import subprocess import sys import tempfile import threading from datetime import datetime, timezone from typing import Optional import migrations from database import SessionLocal, engine as sa_engine from . import BackupError, Busy, Invalid, crypto, destinations, package, store from services import pki, process logger = logging.getLogger(__name__) PRE_RESTORE_FOLDER = "pre-restore" PRE_RESTORE_KEEP = 5 _lock = threading.Lock() _job = {"kind": None, "state": "idle", "stages": [], "results": [], "warnings": [], "started_at": None, "finished_at": None, "message": None, "relogin": False} # --- paths --------------------------------------------------------------------------------- def profiler_db_path() -> str: from database import db_path return os.path.abspath(db_path) def monitor_db_path() -> str: env = os.environ.get("OVPMON_OPENVPN_MONITOR_DB_PATH", "").strip() return os.path.abspath(env) if env else os.path.join(os.path.dirname(profiler_db_path()), "openvpn_monitor.db") def pki_dir() -> str: return pki.PKI_DIR def client_dir() -> str: return os.path.join(os.getcwd(), "client-config") def runtime() -> str: return "container" if process.is_container() else "host" def _work_dir() -> str: """Temporary directory for a job: next to the local backups (they have room by definition), else the system temporary directory.""" base = os.environ.get("OVPMON_BACKUP_WORK_DIR", "").strip() or os.path.join(destinations.local_root(), ".work") try: os.makedirs(base, mode=0o700, exist_ok=True) except OSError: base = None return tempfile.mkdtemp(prefix="job-", dir=base) # --- job state ----------------------------------------------------------------------------- def _now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def status() -> dict: with _lock: return copy.deepcopy(_job) def is_running() -> bool: with _lock: return _job["state"] == "running" def _claim(kind: str, stages: list, results: list) -> None: with _lock: if _job["state"] == "running": raise Busy(f"A {_job['kind']} is already running") _job.update(kind=kind, state="running", stages=[{"name": n, "state": "pending"} for n in stages], results=results, warnings=[], started_at=_now(), finished_at=None, message=None, relogin=False) def _stage(name: str, state: str = "running") -> None: with _lock: for s in _job["stages"]: if s["name"] == name: s["state"] = state elif s["state"] == "running" and state == "running": s["state"] = "done" def _warn(text: str) -> None: logger.warning(f"[BACKUP] {text}") with _lock: _job["warnings"].append(text) def _finish(state: str, message: str, relogin: bool = False) -> None: with _lock: for s in _job["stages"]: if s["state"] == "running": s["state"] = "done" if state in ("done", "partial") else "error" _job.update(state=state, message=message, finished_at=_now(), relogin=relogin) def _result(index: int, **fields) -> None: with _lock: _job["results"][index].update(fields) # --- destinations -------------------------------------------------------------------------- def build_dest(rec: dict) -> destinations.Destination: if not rec.get("secrets_ok", True): raise BackupError("Stored secrets of this destination cannot be decrypted " "(the JWT secret changed). Edit the destination and enter them again.") return destinations.build_destination(rec["type"], rec["params"], rec["secrets"]) def test_destination(dest_id: int) -> dict: rec = store.get_destination(dest_id, with_secrets=True) if not rec: raise Invalid("Destination not found") try: message = build_dest(rec).test() except destinations.NeedsTrust as e: # SFTP: the host key is not pinned (or changed): show it, the administrator decides store.set_last_result(dest_id, False, str(e)) return {"ok": False, "message": str(e), "needs_trust": True, "fingerprint": e.fingerprint, "key_type": e.key_type, "key_changed": e.changed} except BackupError as e: store.set_last_result(dest_id, False, str(e)) return {"ok": False, "message": str(e)} except Exception as e: # a driver error that is not mapped: report it, never crash the API logger.exception("Destination test failed") message = f"{type(e).__name__}: {str(e)[:200]}" store.set_last_result(dest_id, False, message) return {"ok": False, "message": message} store.set_last_result(dest_id, True, message) return {"ok": True, "message": message} def effective_server_name() -> tuple: """(name, source): the server name of the settings, else the public address from the VPN settings, else the host name. The name goes into the package names.""" name = store.get_server_name() if name and package.SERVER_NAME_RE.match(name): return name, "setting" try: conn = sqlite3.connect(f"file:{profiler_db_path()}?mode=ro", uri=True, timeout=5) try: row = conn.execute("SELECT public_ip FROM system_settings LIMIT 1").fetchone() finally: conn.close() name = package.sanitize_name(row[0]) if row and row[0] else "" if name: return name, "public_ip" except sqlite3.Error: pass # no settings yet (or the column is absent): fall through return package.host_name(), "hostname" def trust_host_key(dest_id: int, fingerprint: str) -> dict: """Pin the host key the server shows now, if it is the one the administrator saw (`fingerprint`).""" rec = store.get_destination(dest_id, with_secrets=True) if not rec: raise Invalid("Destination not found") cls = destinations.DESTINATION_TYPES.get(rec["type"]) if not cls or not cls.PIN_PARAMS: raise Invalid("This destination type has no host key") if not destinations.FINGERPRINT_RE.match(fingerprint or ""): raise Invalid("Invalid fingerprint") shown, key_type = build_dest(rec).fetch_host_key() if shown != fingerprint: raise Invalid("The server now shows a different host key than the one you saw: run Test again") params = dict(rec["params"], host_key=shown, host_key_type=key_type) store.save_destination(rec["id"], rec["name"], rec["type"], rec["enabled"], rec["retention_count"], params, rec["secrets"]) store.set_last_result(rec["id"], True, f"Host key {shown} trusted") return store.get_destination(rec["id"]) def list_packages(dest_id: int) -> list: """Packages of our name pattern in the destination, newest first.""" rec = store.get_destination(dest_id, with_secrets=True) if not rec: raise Invalid("Destination not found") items = [] for obj in build_dest(rec).list(): meta = package.parse_package_name(obj["name"]) if meta: items.append({"name": obj["name"], "server_name": meta["host"], "created_at": meta["created_at"], "encrypted": meta["encrypted"], "size": obj["size"], "_key": (meta["stamp"], meta["seq"], obj["name"])}) items.sort(key=lambda i: i["_key"], reverse=True) for i in items: del i["_key"] return items def put_unique(dest: destinations.Destination, path: str, base_name: str) -> str: """Store the package under base_name, or under -2, -3 ... when the destination already has a package of that second. Returns the name used.""" meta = package.parse_package_name(base_name) name = package.unique_package_name(meta["host"], meta["stamp"], meta["encrypted"], (o["name"] for o in dest.list())) dest.put(path, name) return name def rotate(dest: destinations.Destination, keep: int, keep_name: str, server_name: str) -> int: """Delete the oldest packages of this server name beyond `keep` (never keep_name). Packages with another name in the same folder (other servers, or made under an earlier name or by host name) are not ours to delete. Returns the number removed.""" mine = [] for obj in dest.list(): meta = package.parse_package_name(obj["name"]) if meta and meta["host"] == server_name: mine.append(((meta["stamp"], meta["seq"]), obj["name"])) mine.sort(reverse=True) removed = 0 for _key, name in mine[max(keep, 1):]: if name != keep_name: dest.delete(name) removed += 1 return removed # --- package creation ---------------------------------------------------------------------- def create_package(work: str, passphrase: Optional[str]): """Build (and encrypt, if a passphrase is given) a package in `work`. Returns (path, name, manifest); name is the plain name, a destination may add -2, -3 when that second is taken (put_unique).""" stamp = package.utc_stamp() server_name, _source = effective_server_name() plain = os.path.join(work, "package.tar.gz") manifest = package.build_package(plain, work, profiler_db_path(), monitor_db_path(), pki_dir(), client_dir(), runtime(), server_name) path = plain if passphrase: path = os.path.join(work, "package.enc") crypto.encrypt_file(plain, path, passphrase) os.remove(plain) return path, package.package_name(server_name, stamp, bool(passphrase)), manifest # --- backup job ---------------------------------------------------------------------------- def start_backup(destination_ids: Optional[list] = None) -> None: all_dests = store.list_destinations(with_secrets=True) if destination_ids is None: selected = [d for d in all_dests if d["enabled"]] else: by_id = {d["id"]: d for d in all_dests} selected = [] for i in dict.fromkeys(destination_ids): if i not in by_id: raise Invalid(f"Destination {i} not found") if not by_id[i]["enabled"]: raise Invalid(f"Destination '{by_id[i]['name']}' is disabled") selected.append(by_id[i]) if not selected: raise Invalid("No destinations selected: add and enable a destination first") if any(d["type"] in destinations.REMOTE_TYPES for d in selected) and not store.has_passphrase(): raise Invalid("A passphrase is required for remote destinations: set the encryption passphrase first") passphrase = store.get_passphrase() stages = ["package"] + (["encrypt"] if passphrase else []) + ["upload"] results = [{"destination_id": d["id"], "name": d["name"], "type": d["type"], "state": "pending", "message": None, "package": None} for d in selected] _claim("backup", stages, results) hist_id = store.history_start("backup") threading.Thread(target=_backup_worker, args=(selected, passphrase, hist_id), daemon=True).start() def _backup_worker(selected: list, passphrase: Optional[str], hist_id: int) -> None: work = None try: work = _work_dir() _stage("package") # create_package encrypts too: show the second stage once the tar is written path, name, manifest = create_package(work, passphrase) if passphrase: _stage("encrypt", "done") _stage("upload") size = os.path.getsize(path) server_name = manifest["server_name"] for i, rec in enumerate(selected): _result(i, state="running") try: dest = build_dest(rec) stored = put_unique(dest, path, name) note = f"{stored} ({size // 1024} KB)" try: removed = rotate(dest, rec["retention_count"], stored, server_name) if removed: note += f", {removed} old removed" except Exception as e: logger.warning(f"[BACKUP] rotation failed for '{rec['name']}': {type(e).__name__}") note += f", rotation failed: {str(e)[:150]}" _result(i, state="ok", message=note, package=stored) store.set_last_result(rec["id"], True, note) except Exception as e: msg = str(e)[:300] if isinstance(e, BackupError) else f"{type(e).__name__}: {str(e)[:200]}" logger.error(f"[BACKUP] destination '{rec['name']}' failed: {msg}") _result(i, state="error", message=msg) store.set_last_result(rec["id"], False, msg) with _lock: results = copy.deepcopy(_job["results"]) ok = sum(1 for r in results if r["state"] == "ok") if ok == len(results): state, message = "done", f"Backup stored in {ok} destination(s)" elif ok: state, message = "partial", f"Backup stored in {ok} of {len(results)} destinations" else: state, message = "error", "Backup failed in every destination" _finish(state, message) store.history_finish(hist_id, state, message, results) except Exception as e: logger.exception("Backup failed") message = str(e)[:500] if isinstance(e, BackupError) else f"Backup failed: {type(e).__name__}: {str(e)[:300]}" for i in range(len(selected)): _result(i, state="skipped", message="Package was not created") _finish("error", message) store.history_finish(hist_id, "error", message, []) finally: if work: shutil.rmtree(work, ignore_errors=True) # --- restore ------------------------------------------------------------------------------- RESTORE_STAGES = ["download", "decrypt", "verify", "prepare", "safety_backup", "stop_openvpn", "replace", "finalize"] def start_restore(destination_id: int, package_name: str, passphrase: Optional[str]) -> None: rec = store.get_destination(destination_id, with_secrets=True) if not rec: raise Invalid("Destination not found") meta = package.parse_package_name(package_name) if not meta: raise Invalid("Invalid package name") if meta["encrypted"] and not passphrase: raise Invalid("The package is encrypted: enter its passphrase") if pki.is_init_running(): raise Busy("PKI initialization is running") if is_running(): raise Busy(f"A {status()['kind']} is already running") # Only names from the destination's listing are restored if package_name not in {o["name"] for o in build_dest(rec).list()}: raise Invalid("The package is not in the destination") stages = [s for s in RESTORE_STAGES if s != "decrypt" or meta["encrypted"]] _claim("restore", stages, [{"destination_id": rec["id"], "name": rec["name"], "type": rec["type"], "state": "running", "message": None, "package": package_name}]) pki.set_restore_running(True) hist_id = store.history_start("restore") threading.Thread(target=_restore_worker, args=(rec, package_name, meta["encrypted"], passphrase, hist_id), daemon=True).start() def core_dir() -> Optional[str]: """Directory of the monitoring component (it owns the migrations of openvpn_monitor.db): migrate.py with migrations.py and db.py (standard library only). OVPMON_CORE_DIR (profiler image: /opt/core), else APP_CORE next to APP_PROFILER (system services, all-in-one container). None for an old profiler image without that directory.""" env = os.environ.get("OVPMON_CORE_DIR", "").strip() if not env: code = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) env = os.path.join(os.path.dirname(code), "APP_CORE") if all(os.path.isfile(os.path.join(env, f)) for f in ("migrate.py", "migrations.py", "db.py")): return env return None def _migrate_monitor(db_file: str) -> None: """Bring the monitoring database of the package up to this release's schema. The migrations live in the monitoring component, which this process cannot import (separate virtualenv). Its own migrate.py runs on the staged copy with the interpreter of APP_CORE/venv (or this one: the code uses the standard library only). Without the code on disk (an old profiler image) only a package with exactly the schema of the running monitoring database is accepted: the monitoring services would otherwise read an unmigrated database.""" version = package.schema_version(db_file) core = core_dir() if core: venv_python = os.path.join(core, "venv", "bin", "python") python = venv_python if os.path.isfile(venv_python) else sys.executable try: r = subprocess.run([python, "migrate.py", "--db", db_file], cwd=core, capture_output=True, text=True, timeout=300) except (OSError, subprocess.TimeoutExpired) as e: raise BackupError(f"Cannot run the monitoring database migration: {e}") from e if r.returncode != 0: lines = [ln for ln in (r.stderr or r.stdout or "").strip().splitlines() if ln.strip()] raise BackupError("The monitoring database of the package cannot be migrated: " + (lines[-1][:300] if lines else f"exit code {r.returncode}")) return live = package.schema_version(monitor_db_path()) if not live: raise BackupError("The monitoring database schema cannot be checked: the monitoring component " "is not available to this service and its database is not initialized") if version != live: which = "newer" if (version or 0) > live else "older" raise BackupError( f"The package has a {which} monitoring database schema ({version}) than this installation " f"({live}). The migration code of the monitoring component (OVPMON_CORE_DIR) is not " f"available to this service. Rebuild the profiler image or restore on the same release.") def _prepare_staged(extracted: str, manifest: dict) -> None: """Checks and migrations on the unpacked copies: nothing of the running system is touched yet.""" prof = os.path.join(extracted, package.DB_PROFILER) mon = os.path.join(extracted, package.DB_MONITOR) for path in (prof, mon): if not package.integrity_ok(path): raise BackupError(f"{os.path.basename(path)} in the package failed the integrity check") version, latest = package.schema_version(prof), migrations.latest_version() if version is None or version > latest: raise BackupError(f"The package was made by a newer release (profiler database schema {version}, " f"this release knows up to {latest}). Update this installation first.") try: migrations.run(prof) except migrations.MigrationError as e: raise BackupError(f"The profiler database of the package cannot be migrated: {str(e)[:300]}") from e _migrate_monitor(mon) def _safety_backup() -> str: """Package of the current state in the local pre-restore folder. Raises when it cannot be made.""" try: passphrase = store.get_passphrase() except BackupError: passphrase = None _warn("The safety copy is not encrypted: the stored passphrase cannot be decrypted") work = _work_dir() try: path, name, manifest = create_package(work, passphrase) dest = destinations.LocalDestination({"folder": PRE_RESTORE_FOLDER}, {}) name = put_unique(dest, path, name) try: rotate(dest, PRE_RESTORE_KEEP, name, manifest["server_name"]) except Exception as e: logger.warning(f"[BACKUP] pre-restore rotation failed: {type(e).__name__}") return name finally: shutil.rmtree(work, ignore_errors=True) def _replace_db(target: str, new_file: str, tag: str, undo: list) -> None: """Atomic replacement of a database file. The old file (and its -wal/-shm) is kept under a .old- name until the whole restore succeeded.""" tmp = f"{target}.restore-{tag}" old = f"{target}.old-{tag}" shutil.copyfile(new_file, tmp) os.chmod(tmp, (os.stat(target).st_mode & 0o777) if os.path.exists(target) else 0o600) if os.path.exists(target): try: os.link(target, old) except OSError: shutil.copy2(target, old) undo.append(("db", target, old)) # A leftover journal of the old database must never be applied to the new file for suffix in ("-wal", "-shm"): if os.path.exists(target + suffix): os.replace(target + suffix, old + suffix) else: undo.append(("db_new", target, old)) os.replace(tmp, target) def _swap_dir(target: str, extracted: str, tag: str, undo: list) -> None: """Replace the CONTENT of a directory (the directory itself may be a volume mount point): old entries move into .restore-old-, new ones come from .restore-new-.""" os.makedirs(target, mode=0o700, exist_ok=True) staged = os.path.join(target, f".restore-new-{tag}") old = os.path.join(target, f".restore-old-{tag}") if os.path.isdir(extracted): shutil.copytree(extracted, staged) else: os.mkdir(staged, 0o700) os.mkdir(old, 0o700) undo.append(("dir", target, old, staged)) for name in os.listdir(target): if not name.startswith(".restore-"): os.replace(os.path.join(target, name), os.path.join(old, name)) for name in os.listdir(staged): os.replace(os.path.join(staged, name), os.path.join(target, name)) os.rmdir(staged) def _remove(path: str) -> None: if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path, ignore_errors=True) elif os.path.lexists(path): os.remove(path) def _rollback(undo: list) -> None: for item in reversed(undo): try: if item[0] == "db": _, target, old = item for suffix in ("", "-wal", "-shm"): if os.path.exists(old + suffix): os.replace(old + suffix, target + suffix) elif item[0] == "db_new": _remove(item[1]) else: _, target, old, staged = item for name in os.listdir(target): if not name.startswith(".restore-"): _remove(os.path.join(target, name)) for name in os.listdir(old): os.replace(os.path.join(old, name), os.path.join(target, name)) shutil.rmtree(old, ignore_errors=True) shutil.rmtree(staged, ignore_errors=True) except Exception: logger.exception("[BACKUP] rollback step failed") def _commit(undo: list) -> None: for item in undo: if item[0] == "db": for suffix in ("", "-wal", "-shm"): if os.path.lexists(item[2] + suffix): _remove(item[2] + suffix) elif item[0] == "dir": shutil.rmtree(item[2], ignore_errors=True) shutil.rmtree(item[3], ignore_errors=True) def _apply_server_config() -> bool: """Regenerate server.conf and publish the CRL through the same code as POST /server/configure.""" from fastapi import HTTPException from routers import server as server_router db = SessionLocal() try: server_router.configure_server(db) return True except HTTPException as e: _warn(f"server.conf was not regenerated: {e.detail}") except Exception as e: _warn(f"server.conf was not regenerated: {type(e).__name__}: {str(e)[:200]}") finally: db.close() return False def _start_openvpn(was_running: bool) -> None: if not was_running: return res = process.control_service("start") if res.get("status") == "error": _warn(f"OpenVPN was running before the restore, but could not be started: {res.get('message')}") def _restore_worker(rec: dict, name: str, encrypted: bool, passphrase: Optional[str], hist_id: int) -> None: work = None undo = [] was_running = False stopped = False committed = False try: work = _work_dir() downloaded = os.path.join(work, "downloaded") _stage("download") build_dest(rec).get(name, downloaded) archive = downloaded if encrypted: _stage("decrypt") archive = os.path.join(work, "package.tar.gz") crypto.decrypt_file(downloaded, archive, passphrase) os.remove(downloaded) elif crypto.is_encrypted(downloaded): raise BackupError("The package is encrypted but its name says it is not") _stage("verify") extracted = os.path.join(work, "extracted") manifest = package.safe_extract(archive, extracted) os.remove(archive) _stage("prepare") _prepare_staged(extracted, manifest) _stage("safety_backup") safety = _safety_backup() _stage("stop_openvpn") was_running = process.get_process_stats().get("status") == "running" if was_running: res = process.control_service("stop") if res.get("status") == "error": raise BackupError(f"Cannot stop OpenVPN: {res.get('message')}") stopped = True _stage("replace") tag = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") try: sa_engine.dispose() _swap_dir(pki_dir(), os.path.join(extracted, "pki"), tag, undo) _swap_dir(client_dir(), os.path.join(extracted, "client-config"), tag, undo) _replace_db(monitor_db_path(), os.path.join(extracted, package.DB_MONITOR), tag, undo) _replace_db(profiler_db_path(), os.path.join(extracted, package.DB_PROFILER), tag, undo) marker = pki._marker_path() if os.path.exists(marker): os.remove(marker) except Exception: logger.exception("[BACKUP] replacement failed, rolling back") _rollback(undo) sa_engine.dispose() raise _commit(undo) committed = True sa_engine.dispose() _stage("finalize") configured = _apply_server_config() if configured: _start_openvpn(was_running) elif was_running: _warn("OpenVPN was running before the restore and was not started") message = f"Restored from {name}. The previous state is saved as {PRE_RESTORE_FOLDER}/{safety}" _result(0, state="ok", message=message) _finish("done", message, relogin=True) store.history_finish(hist_id, "done", message, status()["results"]) except Exception as e: logger.exception("Restore failed") message = str(e)[:500] if isinstance(e, BackupError) else f"Restore failed: {type(e).__name__}: {str(e)[:300]}" if committed: message += ". The data was restored, but the final steps failed (see the log)." else: message += ". Nothing was changed." if not undo else ". The previous state was put back." if stopped: try: _start_openvpn(True) except Exception: logger.exception("[BACKUP] OpenVPN start after a failed restore") _result(0, state="error", message=message) _finish("error", message) store.history_finish(hist_id, "error", message, status()["results"]) finally: pki.set_restore_running(False) if work: shutil.rmtree(work, ignore_errors=True)