Files

89 lines
2.9 KiB
Bash
Raw Permalink Normal View History

#!/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/Containers/README.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"