MySQL定时增量备份处理脚本
在提出 MySQL主从结构灾难恢复策略机制设想 后尝试编写用于以上目的的备份脚本。
增量日志备份
每日一个全量备份,同时做binlog 的删减(只保留一个小时的日志,根据需要可以做延时),然后每小时对日志文件做增量部分的备份。
-
#!/bin/bash
-
-
PATH=/usr/local/sbin:/usr/bin:/bin
-
-
#get cur date str 2008-10-12
-
DATE=`date -I`
-
-
#set backup path info
-
DATADIR="/var/lib/mysql"
-
BASE_BAK_DIR="/backup"
-
CUR_BAK_DIR="$BASE_BAK_DIR/current"
-
-
#set mysql user name and password
-
MYSQL_USER="root"
-
MYSQL_PWD="rootpwd"
-
MYACC=" -u'$MYSQL_USER' -p'$MYSQL_PWD' "
-
-
#set backup type info
-
INTERVAL="$1"
-
-
# days, files in base_bak_path
-
# before this days will be deleted
-
RETENTION=21
-
#get host name (a part of bin log file names,
-
# if change set master bin file manual, need change this)
-
HOST=`hostname -s`
-
-
#set mysql version
-
MYVERSION="4.1"
-
-
if [ "$MYVERSION" = '4.1' ] || [ "$MYVERSION" = '5.0' ] ; then
-
#purge master logs to latest backup time (remain one hour bin log for slave replication delay)
-
PURGELOGS="mysql $MYACC -e \"PURGE MASTER LOGS BEFORE DATE_SUB( NOW(), INTERVAL 1 HOUR )\""
-
else
-
echo "not support MYSql Ver $MYVERSION"
-
exit 1
-
fi
-
-
#check param input (daily or hourly)
-
if [ ! $1 ];
-
then
-
read -p "Backup Interval? (Hourly|Daily) : " INTERVAL
-
fi
-
-
case $INTERVAL in
-
hourly | HOURLY | Hourly | H | h | 1 )
-
echo "Performing hourly level backup — `date`"
-
MYCMD="mysql $MYACC -e \"FLUSH LOGS\""
-
eval $MYCMD
-
-
if [ -d $BASE_BAK_DIR/$DATE ] && [ "$MYVERSION" = '4.1' -o "$MYVERSION" = '5.0' ] ; then
-
rsync -aub $DATADIR/$HOST-bin.?????? $BASE_BAK_DIR/$DATE
-
else
-
echo "dest dir not exists! please run daily backup first." 1>&2
-
exit 1
-
fi
-
exit 0
-
;;
-
-
daily | DAILY | Daily | D | d | 2 )
-
echo "Performing daily level backup — `date`"
-
# check dest path
-
if [ ! -d $CUR_BAK_DIR ]; then
-
echo "Creating $CUR_BAK_DIR"
-
mkdir -p $CUR_BAK_DIR
-
fi
-
-
MYCMD="mysqlhotcopy $MYACC –regexp=.* $CUR_BAK_DIR"
-
eval $MYCMD
-
chown -R mysql: $CUR_BAK_DIR/
-
mv $CUR_BAK_DIR $BASE_BAK_DIR/$DATE
-
eval $PURGELOGS
-
-
#delete files that outdate
-
find $BASE_BAK_DIR -ctime +$RETENTION -exec rm -rf '{}' \;
-
exit 0
-
;;
-
-
* )
-
echo "Invalid Selection" 1>&2
-
exit 1
-
esac
可以在脚本的前面指定好备份目录参数
DATADIR="/var/lib/mysql" BASE_BAK_DIR="/backup" CUR_BAK_DIR="$BASE_BAK_DIR/current"
以及用来连接数据库的账号的参数
#set mysql user name and password
MYSQL_USER="root"
MYSQL_PWD="rootpwd"
通过参数 RETENTION=21 来指定备份文件保留的天数,要视具体用来做备份的磁盘大小和数据库大小做综合衡量处理。
最后将脚本添加到crontab中定时运行
首先设定每天备份一次的,然后再设定每小时的备份,其中第一次的每小时备份应该是在每天备份执行之后。
数据库发生失败时的恢复在每日全量备份基础上通过日志文件快速恢复到最近时间的变化。
Popularity: 4% [?]
Related
Comments
2 Responses to “MySQL定时增量备份处理脚本”
[...] MySQL定时增量备份处理脚本备份了数据后,我们还需要做恢复操作的脚本。 [...]
我好像来过你的博客了。不过既然来了。给你留点东西吧 (*^__^*) 嘻嘻……
[Reply]