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>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 10:45:24 +03:00
1 parent 1c49d0b9c2
commit 4abd2044f0
26 files changed
+3326 -255

No files matched your search

+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 $?