最近一直在思考如何增量备份二进制日志,这样一来我们就可以用mysqldump +二进制全备或者利用xtrabackup+二进制备份

思想:利用mysql-bin.index,如果是第一次备份,就将mysql-bin.index中的所有文件都复制到备份目录下,然后保存备份后二进制日志的序号到一个文件中backbinlogpostion
        增量备份时(非第一备份),就用backbinlogpostion存的序号与当前mysql_bin.index中的比较,如果序号小于mysql-bin.index的序号,则复制该二进制文件到备份目录

#!/bin/bash
#################################################################
#name:incrementalbackdb
#function:incremental-backup for mysql everyday
#finish-time:2015-04-02 by yzx@tianqu.com.cn
#################################################################
BinDir=/usr/local/mysql/data
BackupDir=/usr/backupyzx
BinLogFile=/usr/local/mysql/data/mysql-bin.index
BackLogPostion=0
BackupLog=${BackupDir}/backup.log
printN=
BinLogPostion=$(wc -l $BinLogFile|awk '{print $1}')
#get Binnary log sequ
LastSeqBinLog=$(basename $(tail -n 1 $BinLogFile))
LastBinLogPostion=${LastSeqBinLog##*0}
#before you backup,you should flush logs
/usr/local/mysql/bin/mysqladmin -uroot -p'tianqu' flush-logs
echo "begin increment-backup,time is:" $(date +'%Y-%m-%d %H:%M:%S') >>$BackupLog
if [ -e ${BackupDir}/backbinlogpostion  ];then
#取出backbinlogpostion中二进制的序号,例如mysql-bin.000002,保存的序号就是2
    BackLogPostion=$(cat ${BackupDir}/backbinlogpostion)
#如果当前二进制的序号与备份的二进制序号相同
    if [ ${LastBinLogPostion} -eq $BackLogPostion ];then
        echo "backup skiped,backup success!" >>${BackupLog}
    else
#取出序号的之间的差值
        printN=$((${LastBinLogPostion}-${BackLogPostion}))
        echo $printN
        q=$((${BackLogPostion}+1))
        for file in $(tail -n ${printN} ${BinLogFile});do
            basefile=$(basename ${file})
            if [ $q -ge ${LastBinLogPostion} ];then
            break;
            fi
            cp -pd ${BinDir}/${basefile} ${BackupDir}
            echo ${basefile}" is copying...">>${BackupLog}
            ((q++))
        done
    echo ${LastBinLogPostion} >${BackupDir}/backbinlogpostion
    fi
else
#如果是第一次备份,则创建backbinlogpostion,记录当前已经复制二进制的日志,方便第二次备份时,只备份新增的部分
    touch ${BackupDir}/backbinlogpostion
    i=1
    for file in $(cat ${BinLogFile});do
        basefile=$(basename ${file})
        if [ $i -eq ${BinLogPostion} ];then
        echo ${basefile##0} >${BackupDir}/backbinlogpostion
        fi
        if [ $i -eq $((${BinLogPostion}+1)) ];then
        break;
        fi
        cp -pd ${BinDir}/${basefile} ${BackupDir}
        echo ${basefile}" is copying...">>${BackupLog}
        ((i++))
    done
fi
echo "increment-backup finished,time is :" $(date +'%Y-%m-%d %H:%M:%S')>>$BackupLog
#Delete old file
#将当前备份的文件转移到远程机器,然后删除本地的存档
#find ${BackupDir} -type f -mtime +15 -exec rm -rf {} \;
#/usr/bin/rsync -vzrtopg --progress ${BackupDir} rsyncusr@192.168.1.201::backup/backdb/ --password-file=/usr/local/etc/rsyncd.sec