74 lines
2.0 KiB
Bash
Executable File
74 lines
2.0 KiB
Bash
Executable File
#!/bin/bash
|
|
# @params:
|
|
# 1* => docker database running container name
|
|
# 2* => directory to place compressed backups when finished
|
|
# 3 => (optional) number of backups to keep
|
|
|
|
## NEEDS packages: cpulimit, docker
|
|
|
|
set -o allexport
|
|
if [[ $1 == '' || $2 == '' ]]; then
|
|
echo 'E| Parameters are incorrect. Please specify "container_name /path/for/backups"'
|
|
exit 1
|
|
fi
|
|
|
|
[[ ! -d $2 ]] && mkdir -p $2
|
|
|
|
set -e
|
|
umask 077
|
|
CLIM1=${CPU_LIMIT_DUMP:-70}
|
|
CLIM2=${CPU_LIMIT_XZ:-20}
|
|
IMGTYPE=$(docker inspect --format='{{.Config.Image}}' $1 | cut -f1 -d:)
|
|
[[ $BACKTS == '' ]] && BACKTS=`date +"%Y%m%d"`.`echo $RANDOM|md5sum|head -c8`
|
|
TMPDIR=/var/tmp/dumps
|
|
mkdir -p $TMPDIR
|
|
|
|
echo 'docker-db-dump: '$1-$BACKTS
|
|
|
|
if [[ $IMGTYPE == 'postgres' ]]; then
|
|
docker exec $1 env | grep -i postgres_ > /tmp/.env-docker-db-dump
|
|
source /tmp/.env-docker-db-dump && rm /tmp/.env-docker-db-dump
|
|
DB=${POSTGRES_DB}
|
|
if [[ $DB == '' ]]; then
|
|
DB=${POSTGRES_USER}
|
|
fi
|
|
DBU=''
|
|
if [[ $POSTGRES_USER != '' ]]; then
|
|
DBU='-U'${POSTGRES_USER}
|
|
fi
|
|
echo "nice -n 19 docker exec -upostgres $1 pg_dump $DBU $DB > $TMPDIR/$1.sql" \
|
|
> /tmp/.postgres-docker-db-dump
|
|
cpulimit -q -l $CLIM1 -f -- bash /tmp/.postgres-docker-db-dump
|
|
rm /tmp/.postgres-docker-db-dump
|
|
|
|
elif [[ $IMGTYPE == 'mariadb' || $IMGTYPE == 'mysql' ]]; then
|
|
cat <<EOLFF > /tmp/.mysql-docker-db-dump
|
|
#!/bin/bash
|
|
if [[ \$MYSQL_ROOT_PASSWORD != '' ]]; then
|
|
mysqldump -uroot -p\$MYSQL_ROOT_PASSWORD \$MYSQL_DATABASE
|
|
else
|
|
mysqldump -u\$MYSQL_USER -p\$MYSQL_PASSWORD \$MYSQL_DATABASE
|
|
fi
|
|
rm /docker-db-dump.sh
|
|
EOLFF
|
|
chmod +x /tmp/.mysql-docker-db-dump
|
|
docker cp /tmp/.mysql-docker-db-dump $1:/docker-db-dump.sh
|
|
echo "nice -n 19 docker exec $1 /docker-db-dump.sh > $TMPDIR/$1.sql" \
|
|
> /tmp/.mysql-docker-db-dump
|
|
cpulimit -l $CLIM1 -f -- bash /tmp/.mysql-docker-db-dump
|
|
rm /tmp/.mysql-docker-db-dump
|
|
|
|
else
|
|
echo 'FATAL: image not supported "'$IMGTYPE'"'
|
|
exit 2
|
|
fi
|
|
|
|
set -x
|
|
cpulimit -l $CLIM2 -f -- nice -n 19 xz -9 $TMPDIR/$1.sql
|
|
mv $TMPDIR/$1.sql.xz $2/$BACKTS-$1.sql.xz
|
|
|
|
cd $2/
|
|
if [[ $? == 0 ]]; then
|
|
rmkeep $1.sql.xz ${3:-14} # days to keep by default
|
|
fi
|