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>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 09:24:55 +03:00
1 parent e556d6d4b9
commit 1c49d0b9c2
17 files changed
+1930 -50

No files matched your search

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