#!/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 } # Variant B (docker-compose.yml) uses additional_contexts: Docker Compose v2.17.0 or newer MIN_COMPOSE_VERSION="2.17.0" # version_ge FOUND REQUIRED: pure comparison of MAJOR.MINOR[.PATCH] versions, no docker involved. # A leading 'v' and any suffix after the numbers (-desktop.1, +build, -rc1) are ignored. # Returns 0 if FOUND >= REQUIRED, 1 if FOUND < REQUIRED, 2 if either value cannot be parsed. version_ge() { local f r fa fb fc ra rb rc f=$(printf '%s' "$1" | sed -n 's/^[vV]\{0,1\}\([0-9][0-9]*\)\.\([0-9][0-9]*\)\(\.\([0-9][0-9]*\)\)\{0,1\}.*$/\1 \2 \4/p') r=$(printf '%s' "$2" | sed -n 's/^[vV]\{0,1\}\([0-9][0-9]*\)\.\([0-9][0-9]*\)\(\.\([0-9][0-9]*\)\)\{0,1\}.*$/\1 \2 \4/p') [ -n "$f" ] && [ -n "$r" ] || return 2 set -- $f; fa=$1; fb=$2; fc=${3:-0} set -- $r; ra=$1; rb=$2; rc=${3:-0} [ "$fa" -gt "$ra" ] && return 0 [ "$fa" -lt "$ra" ] && return 1 [ "$fb" -gt "$rb" ] && return 0 [ "$fb" -lt "$rb" ] && return 1 [ "$fc" -ge "$rc" ] && return 0 return 1 } # need_compose_version: variant B needs Docker Compose v2.17+ (additional_contexts). Variant A works # with any compose. Call after need_docker (DC_BIN) and set_variant (VARIANT). need_compose_version() { local v rc [ "$VARIANT" = b ] || return 0 if [ "$DC_BIN" != "docker compose" ]; then die "variant B needs the Docker Compose plugin v$MIN_COMPOSE_VERSION or newer ('docker compose', the build uses additional_contexts), but only the legacy 'docker-compose' (v1) was found. Install the plugin (docker-compose-plugin package, see https://docs.docker.com/compose/install/) or use variant A (--variant a), which works with any compose" fi v=$(docker compose version --short 2>/dev/null | head -n 1 || true) rc=0 version_ge "$v" "$MIN_COMPOSE_VERSION" || rc=$? case "$rc" in 0) log "docker compose version $v (required for variant B: $MIN_COMPOSE_VERSION or newer)" ;; 1) die "variant B needs Docker Compose v$MIN_COMPOSE_VERSION or newer (the build uses additional_contexts), found v${v#v}. Update the Docker Compose plugin (docker-compose-plugin package, see https://docs.docker.com/compose/install/) or use variant A (--variant a), which works with any compose" ;; *) warn "cannot parse the docker compose version ('$v'); variant B needs v$MIN_COMPOSE_VERSION or newer, continuing without the check" ;; esac } # 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/Containers/Operations.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" } # secret_problem KEY: JWT key rule (same as APP_CORE/secret_key.py: not empty, no change-me/changeme, # at least 32 characters). Prints the reason (never the key) and returns 1 when the key is not acceptable. # Use it as: if reason=$(secret_problem "$key"); then ...ok...; else ...$reason...; fi (set -e safe) secret_problem() { local _lc case "$1" in *[![:space:]]*) ;; *) printf 'not set or empty'; return 1 ;; esac _lc=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]') case "$_lc" in *change-me*|*changeme*) printf 'a placeholder/default value (contains change-me)'; return 1 ;; esac if [ "${#1}" -lt 32 ]; then printf 'too short (%s characters, at least 32 required)' "${#1}" return 1 fi return 0 } # csp_extra_problem VALUE: extra origins for the connect-src directive of the Content-Security-Policy # (OVPMON_CSP_CONNECT_EXTRA in .env). Allowed: empty, or origins https://host[:port] and # http://host[:port] separated by spaces (host: letters, digits, dots, hyphens; no path, quotes, ; or commas). # Anything else would let a value inject its own CSP directive. Prints the reason and returns 1 when the # value is not acceptable. Use it as: if reason=$(csp_extra_problem "$v"); then ...ok...; else ...; fi csp_extra_problem() { local _t _rest _host _port [ -n "$1" ] || return 0 case "$1" in *[!A-Za-z0-9.:/\ -]*) printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;; " "*|*" ") printf 'starts or ends with a space'; return 1 ;; esac set -f for _t in $1; do case "$_t" in https://*) _rest=${_t#https://} ;; http://*) _rest=${_t#http://} ;; *) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;; esac _host=${_rest%%:*} _port="" case "$_rest" in *:*) _port=${_rest#*:} ;; esac case "$_host" in ""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;; esac if [ -n "$_port" ]; then case "$_port" in *[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;; esac if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then set +f; printf "'%s' has a port out of range" "$_t"; return 1 fi fi case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac done set +f return 0 } check_env_file() { local _reason [ -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 ! _reason=$(secret_problem "$(env_get JWT_SECRET)"); then die "JWT_SECRET in $ENV_FILE is $_reason: the API refuses to start with a weak signing key. Set a random value of at least 32 characters (for example: openssl rand -hex 32); note that a changed key signs out all users" fi if ! _reason=$(csp_extra_problem "$(env_get OVPMON_CSP_CONNECT_EXTRA)"); then die "OVPMON_CSP_CONNECT_EXTRA in $ENV_FILE is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty" fi if [ -n "$(find "$ENV_FILE" \( -perm -040 -o -perm -004 \) 2>/dev/null)" ]; then warn ".env is readable by other users; fix with: chmod 600 $ENV_FILE" fi } valid_port() { case "$1" in ""|*[!0-9]*) return 1 ;; esac [ "$1" -ge 1 ] && [ "$1" -le 65535 ] } # --------------------------------------------------------------------------------------------- # Host checks # --------------------------------------------------------------------------------------------- # port_in_use PORT tcp|udp: 0 = in use, 1 = free, 2 = cannot tell port_in_use() { local fl case "$2" in tcp) fl=-ltn ;; *) fl=-lun ;; esac if command -v ss >/dev/null 2>&1; then ss $fl 2>/dev/null | awk -v p=":$1\$" '$4 ~ p { f = 1 } END { exit !f }' && return 0 || return 1 elif command -v netstat >/dev/null 2>&1; then netstat $fl 2>/dev/null | awk -v p=":$1\$" '$4 ~ p { f = 1 } END { exit !f }' && return 0 || return 1 fi return 2 } # check_port PORT PROTO LABEL: dies if the port is busy check_port() { local rc port_in_use "$1" "$2" && rc=0 || rc=$? case "$rc" in 0) die "$3 port $1/$2 is already in use on this host. Choose another one (--http-port / --vpn-port, or OVPMON_HTTP_PORT / OVPMON_VPN_PORT in .env)" ;; 2) warn "cannot check whether port $1/$2 is free (no ss or netstat)" ;; esac return 0 } # free_mb DIR: free space in MB (empty if unknown) free_mb() { df -Pk "$1" 2>/dev/null | awk 'NR == 2 { print int($4 / 1024) }' } # check_free DIR MIN_MB LABEL check_free() { local f f=$(free_mb "$1") if [ -z "$f" ]; then warn "cannot determine free space for $3 ($1)" elif [ "$f" -lt "$2" ]; then die "not enough free space for $3: ${f} MB free in $1, at least $2 MB required (override: OVPMON_MIN_FREE_MB / OVPMON_MIN_FREE_BACKUP_MB)" else log "free space for $3: ${f} MB ($1)" fi } docker_root_dir() { local d d=$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true) [ -n "$d" ] && [ -d "$d" ] && [ -r "$d" ] && { echo "$d"; return 0; } echo /var/lib } acquire_lock() { local pid if mkdir "$LOCK_DIR" 2>/dev/null; then echo $$ > "$LOCK_DIR/pid" LOCK_HELD=1 return 0 fi pid=$(cat "$LOCK_DIR/pid" 2>/dev/null || true) if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then die "another deploy script is running (pid $pid)" fi warn "removing stale lock $LOCK_DIR" rm -rf "$LOCK_DIR" mkdir "$LOCK_DIR" || die "cannot create lock $LOCK_DIR" echo $$ > "$LOCK_DIR/pid" LOCK_HELD=1 } release_lock() { if [ "${LOCK_HELD:-0}" = 1 ]; then rm -rf "$LOCK_DIR" LOCK_HELD=0 fi } # --------------------------------------------------------------------------------------------- # Health # --------------------------------------------------------------------------------------------- service_state() { # SERVICE -> healthy|starting|unhealthy|running|exited|missing ... local cid cid=$(dc ps -a -q "$1" 2>/dev/null | head -n 1) [ -n "$cid" ] || { echo missing; return 0; } docker container inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$cid" 2>/dev/null || echo unknown } show_failed_logs() { local s st for s in $SERVICES; do st=$(service_state "$s") case "$st" in healthy|running) ;; *) log "--- last log lines of $s (state: $st) ---" >&2 dc logs --tail 30 "$s" 2>&1 | sed 's/^/ /' >&2 || true ;; esac done } # wait_healthy [SECONDS]: 0 when every service is healthy (or running without a health check) wait_healthy() { local t w all fail s st t="${1:-$HEALTH_TIMEOUT}" w=0 log "waiting for the stack to become healthy (up to ${t}s): $SERVICES" while :; do all=1 fail=0 for s in $SERVICES; do st=$(service_state "$s") case "$st" in healthy|running) ;; starting|created) all=0 ;; *) all=0; fail=1; log "service $s is $st" >&2 ;; esac done if [ "$all" = 1 ]; then log "stack is healthy" return 0 fi if [ "$fail" = 1 ]; then show_failed_logs return 1 fi if [ "$w" -ge "$t" ]; then log "timeout: the stack is not healthy after ${t}s" >&2 show_failed_logs return 1 fi sleep 3 w=$((w + 3)) done } # --------------------------------------------------------------------------------------------- # Images (:previous tags for rollback) # --------------------------------------------------------------------------------------------- image_repo() { # strip a tag, keep a registry port: repo:tag -> repo case "${1##*/}" in *:*) echo "${1%:*}" ;; *) echo "$1" ;; esac } # record_images DIR: images.tsv with "serviceimage nameimage id" of the existing containers record_images() { local s cid name id : > "$1/images.tsv" for s in $SERVICES; do cid=$(dc ps -a -q "$s" 2>/dev/null | head -n 1) if [ -z "$cid" ]; then warn "no container for service $s: no previous image recorded for it" continue fi name=$(docker container inspect -f '{{.Config.Image}}' "$cid") id=$(docker container inspect -f '{{.Image}}' "$cid") printf '%s\t%s\t%s\n' "$s" "$name" "$id" >> "$1/images.tsv" done chmod 600 "$1/images.tsv" } # tag_previous DIR: tag the recorded images ":previous" (so a rebuild does not orphan them) tag_previous() { local s name id [ -s "$1/images.tsv" ] || { warn "no recorded images: rollback to previous images will not be possible"; return 0; } while IFS="$(printf '\t')" read -r s name id; do case "$name" in sha256:*) warn "image of $s has no name: cannot tag it"; continue ;; esac docker tag "$id" "$(image_repo "$name"):previous" || die "cannot tag previous image of $s" log " $s: $(image_repo "$name"):previous = $id" done < "$1/images.tsv" } # --------------------------------------------------------------------------------------------- # Backup and restore of the five volumes (throwaway container, volumes mounted read-only for backup) # --------------------------------------------------------------------------------------------- backup_stamp() { date -u '+%Y%m%dT%H%M%SZ'; } # Files created by the container are root-owned; give them to the calling user (not in rootless mode) _backup_owner() { case "$(docker info --format '{{.SecurityOptions}}' 2>/dev/null)" in *rootless*) echo "" ;; *) echo "$(id -u):$(id -g)" ;; esac } # backup_volumes DIR: .tar.gz for each existing volume, volumes.tsv, SHA256SUMS. Archives are # written under a temporary name and renamed when complete, so an old archive is never half replaced. backup_volumes() { local dir n v real own dir="$1" mkdir -p "$dir" chmod 700 "$dir" : > "$dir/volumes.tsv.new" # replaces volumes.tsv only when every archive is done n=0 for v in $VOLUMES; do real=$(volume_name "$v") if [ -z "$real" ]; then warn "volume $v of project $PROJECT does not exist: skipped" continue fi log " archiving $v ($real)" docker run --rm -v "$real":/data:ro -v "$dir":/backup "$BACKUP_IMAGE" \ sh -c "tar -czf /backup/$v.tar.gz.tmp -C /data . && mv /backup/$v.tar.gz.tmp /backup/$v.tar.gz" \ || { log "backup of volume $v failed" >&2; return 1; } printf '%s\t%s\n' "$v" "$real" >> "$dir/volumes.tsv.new" n=$((n + 1)) done [ "$n" -gt 0 ] || { log "no volumes found for project $PROJECT: nothing to back up" >&2; return 1; } mv "$dir/volumes.tsv.new" "$dir/volumes.tsv" own=$(_backup_owner) docker run --rm -v "$dir":/backup "$BACKUP_IMAGE" \ sh -c "cd /backup && sha256sum *.tar.gz > SHA256SUMS && chmod 600 *.tar.gz SHA256SUMS volumes.tsv && { [ -z '$own' ] || chown '$own' *.tar.gz SHA256SUMS volumes.tsv; }" \ || { log "cannot finish backup (checksums)" >&2; return 1; } } # verify_backup DIR: archive of every volume in volumes.tsv exists and is a readable gzip tar verify_backup() { local dir v real dir="$1" [ -s "$dir/volumes.tsv" ] || { log "backup $dir has no volumes.tsv" >&2; return 1; } while IFS="$(printf '\t')" read -r v real; do [ -s "$dir/$v.tar.gz" ] || { log "archive $v.tar.gz is missing or empty in $dir" >&2; return 1; } done < "$dir/volumes.tsv" docker run --rm -v "$dir":/backup:ro "$BACKUP_IMAGE" \ sh -c 'for f in /backup/*.tar.gz; do tar -tzf "$f" >/dev/null || { echo "corrupt archive: $f" >&2; exit 1; }; done' \ || return 1 } git_head() { git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || echo "n/a" } write_manifest() { # DIR KIND { echo "created_utc=$(date -u '+%Y-%m-%dT%H:%M:%SZ')" echo "kind=$2" echo "variant=$VARIANT" echo "project=$PROJECT" echo "compose_file=$(basename "$COMPOSE_FILE")" echo "git_commit=$(git_head)" } > "$1/MANIFEST" chmod 600 "$1/MANIFEST" } # make_backup DIR KIND: full backup into DIR, verified, marked COMPLETE (only complete backups are used) make_backup() { local dir dir="$1" rm -f "$dir/COMPLETE" backup_volumes "$dir" || return 1 if [ -f "$ENV_FILE" ]; then ( umask 077; cp "$ENV_FILE" "$dir/.env" ) fi write_manifest "$dir" "$2" log "verifying the backup" verify_backup "$dir" || return 1 date -u '+%Y-%m-%dT%H:%M:%SZ' > "$dir/COMPLETE" chmod 600 "$dir/COMPLETE" } # list_backups: timestamp directories, oldest first list_backups() { [ -d "$BACKUP_ROOT" ] || return 0 ls -1 "$BACKUP_ROOT" 2>/dev/null | grep -E '^[0-9]{8}T[0-9]{6}Z$' | sort || true } # latest_backup: path of the newest COMPLETE backup (empty if none) latest_backup() { local b for b in $(list_backups | sort -r); do if [ -f "$BACKUP_ROOT/$b/COMPLETE" ]; then echo "$BACKUP_ROOT/$b" return 0 fi done return 0 } # prune_backups [KEEP]: keep the newest KEEP timestamp directories (default 5) prune_backups() { local keep keep="${1:-$KEEP_BACKUPS}" list_backups | sort -r | awk -v k="$keep" 'NR > k' | while read -r b; do log "removing old backup $BACKUP_ROOT/$b" rm -rf "${BACKUP_ROOT:?}/$b" done } # restore_volumes DIR SAFETY: replace the content of the volumes with the archives of DIR. # The stack must be stopped. SAFETY=1 first saves the current content to /-pre-restore. # Volumes are emptied and refilled, never removed. restore_volumes() { local dir safe v real dir="$1" verify_backup "$dir" || { log "backup $dir failed verification: nothing was changed" >&2; return 1; } # Refuse if anything still uses the volumes while IFS="$(printf '\t')" read -r v real; do if [ -n "$(docker ps -q --filter "volume=$real")" ]; then log "volume $real is in use by a running container: stop the stack first" >&2 return 1 fi done < "$dir/volumes.tsv" if [ "${2:-0}" = 1 ] && [ "${OVPMON_NO_SAFETY_BACKUP:-0}" != 1 ]; then safe="$BACKUP_ROOT/$(backup_stamp)-pre-restore" log "saving the current content first: $safe" make_backup "$safe" "pre-restore" || { log "safety backup failed: nothing was changed" >&2; return 1; } fi while IFS="$(printf '\t')" read -r v real; do if ! docker volume inspect "$real" >/dev/null 2>&1; then log " creating missing volume $real" docker volume create \ --label "com.docker.compose.project=$PROJECT" \ --label "com.docker.compose.volume=$v" "$real" >/dev/null || return 1 fi log " restoring $v ($real)" docker run --rm -v "$real":/data -v "$dir":/backup:ro "$BACKUP_IMAGE" \ sh -c "rm -rf /data/* /data/.[!.]* /data/..?* && tar -xzf /backup/$v.tar.gz -C /data" \ || { log "restore of volume $v failed: restore again from $dir before starting anything" >&2; return 1; } done < "$dir/volumes.tsv" } # start_previous DIR: start the images recorded in DIR/images.tsv (tagged :previous) with the same # compose file, through a generated override file; no build. DC_OVERRIDE stays set afterwards, so # the following dc calls (health wait, status) see the same configuration. start_previous() { local dir ov s name id dir="$1" [ -s "$dir/images.tsv" ] || { log "no images.tsv in $dir: cannot start previous images" >&2; return 1; } ov="$dir/compose.previous.yml" { echo "# generated: runs the images recorded before the update" echo "services:" } > "$ov" while IFS="$(printf '\t')" read -r s name id; do case "$name" in sha256:*) log "image of $s has no name" >&2; return 1 ;; esac docker image inspect "$id" >/dev/null 2>&1 || { log "previous image $id of $s is no longer present" >&2; return 1; } docker tag "$id" "$(image_repo "$name"):previous" || return 1 printf ' %s:\n image: %s:previous\n' "$s" "$(image_repo "$name")" >> "$ov" done < "$dir/images.tsv" DC_OVERRIDE="$ov" dc up -d --no-build --force-recreate } # users_count: rows in the users table of the monitoring database (empty if it cannot be read) users_count() { dc exec -T "$SEED_SERVICE" python -c 'import os, sqlite3; c = sqlite3.connect("file:" + os.environ["OVPMON_OPENVPN_MONITOR_DB_PATH"] + "?mode=ro", uri=True); print(c.execute("SELECT COUNT(*) FROM users").fetchone()[0])' 2>/dev/null | tail -n 1 | tr -d '\r ' }