sentry-util/sentry-util.sh

112 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
set -eo pipefail
DOCKER_VOLUMES="sentry-postgres sentry-data sentry-redis sentry-zookeeper sentry-kafka sentry-clickhouse sentry-symbolicator"
BACKUP_BASE_DIR="."
BACKUP_DIR_PREFIX="backup-"
CONTAINER_VOLUME_BASE_DIR="/volumes"
CONTAINER_BACKUP_BASE_DIR="/backup"
SCRIPT_DIR="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
SCRIPT_NAME="sentry-util.sh"
function_exists() {
set +e
declare -f -F $1 > /dev/null
local ret=$?
set -e
echo $ret
}
function backup {
[ ! -z "$BACKUP_BASE_DIR" ] && mkdir -p "$BACKUP_BASE_DIR"
local today=$(date +%Y%m%d)
local backup_dir=$(readlink -f "$BACKUP_BASE_DIR/$BACKUP_DIR_PREFIX$today")
mkdir -p "$backup_dir"
echo "Creating backup directory '$backup_dir'..."
run_container "backup-volumes" "-v $backup_dir:$CONTAINER_BACKUP_BASE_DIR"
}
function restore {
local backup_date=$1
if [ -z "$backup_date" ]; then
echo 1>&2 "Vous devez spécifier une date au format YYYYMMDD en premier argument."
exit 1
fi
local backup_dir=$(readlink -f "$BACKUP_BASE_DIR/$BACKUP_DIR_PREFIX$backup_date")
if [ ! -d "$backup_dir" ]; then
echo 1>&2 "Le dossier de sauvegarde '$backup_dir' n'existe pas."
exit 1
fi
run_container "restore-volumes" "-v $backup_dir:$CONTAINER_BACKUP_BASE_DIR"
}
function rotate {
local retention=${1:-2}
local backup_dirs=( $(find -maxdepth 1 -type d -name "$BACKUP_DIR_PREFIX*" -printf "%f\n" | sort -r) )
echo "Rotating backups (retention: $retention)"
echo "Found ${#backup_dirs[@]} backup(s)"
for d in ${backup_dirs[@]:$retention}; do
local abs_dir="$(readlink -f $d)"
echo "Deleting backup '$abs_dir'"
rm -rf "$abs_dir"
done
}
function run_container {
local docker_cmd="$1"
local additional_docker_args="$2"
local volume_args=""
for volume in $DOCKER_VOLUMES; do
volume_args="$volume_args -v $volume:$CONTAINER_VOLUME_BASE_DIR/$volume"
done
docker run --rm \
$volume_args \
$additional_docker_args \
-v "$SCRIPT_DIR/$SCRIPT_NAME:/usr/local/bin/$SCRIPT_NAME" \
bash:5 \
/usr/local/bin/$SCRIPT_NAME $docker_cmd
}
function backup-volumes {
for volume in $DOCKER_VOLUMES; do
local volume_dir="$CONTAINER_VOLUME_BASE_DIR/$volume"
echo "Copying volume '$volume' data..."
rm -rf "$CONTAINER_BACKUP_BASE_DIR/$volume"
cp -aR "$volume_dir" "$CONTAINER_BACKUP_BASE_DIR/"
done
}
function restore-volumes {
for volume in $DOCKER_VOLUMES; do
local volume_dir="$CONTAINER_VOLUME_BASE_DIR/$volume"
echo "Restoring volume '$volume' data..."
rm -rf "$volume_dir/"*
cp -aR "$CONTAINER_BACKUP_BASE_DIR/$volume/"* "$volume_dir/"
done
}
function main {
local command=$1
local command_args=${@:2}
if [ "$(function_exists $command)" == "1" ]; then
echo 1>&2 "La commande '$command' n'existe pas."
exit 1
fi
$command $command_args
}
main $@