#!/usr/bin/python

# -*- coding: utf-8 -*-

"""

@version:0.1

@author:gaoquan

用法:

python /usr/local/percona-xtrabackup-2.3.3-Linux-x86_64/bin//backup.py --host=192.168.31.64 --port=3306 --user=bkpuser --password=bkppassword /data/backup/

"""



import os

import time

import datetime

import sys

import commands

import getopt

import shutil



innobackupex = '/usr/local/percona-xtrabackup-2.3.3-Linux-x86_64/bin/innobackupex'


# 全备函数



def full_backup(host, port, user, password, full_backup_dir):

    os.system(innobackupex + ' --host=' + host + ' --port=' + port + ' --user=' +

              user + ' --password=' + password + ' ' + full_backup_dir + ' --no-timestamp >/tmp/backup.log 2>&1')


# 增备函数



def incr_backup(host, port, user, password, incr_backup_dir, base_backup_dir):

    os.system(innobackupex + ' --incremental ' + incr_backup_dir + ' --incremental-basedir=' +

              base_backup_dir + ' --host=' + host + ' --port=' + port + '  --user=' + user + ' --password=' + password + ' >/tmp/backup.log  2>&1')

# 主函数

if __name__ == '__main__':

    config = {

        "host": "",

        "port": "",

        "user": "",

        "password": "",

        'backup_dir': "",

    }


    opts, args = getopt.getopt(sys.argv[1:], 'a:P:u:p:b',

                               [

        'host=',

        'port=',

        'user=',

        'password=',

        'backup_dir'

    ])


    for option, value in opts:

        if option in ["-a", "--host"]:

            config["host"] = value

        elif option in ['--port', '-P']:

            config["port"] = value

        elif option in ['--user', '-u']:

            config["user"] = value

        elif option in ['--password', '-p']:

            config["password"] = value


    host=config['host']

    port=config['port']

    user=config['user']

    password=config['password']

    backup_dir = args[0]

    print "备份主目录是--------" + backup_dir

    wday = time.localtime().tm_wday

    week_of_dir = backup_dir + time.strftime("%U", time.localtime()) + "/" + port

    full_backup_dir = week_of_dir + "/" + "full"

    print "全备目录是--------" + full_backup_dir

    # 增备寻找最新的上一次备份的基准目录

    base_backup_dir = commands.getoutput(

        'find ' + week_of_dir + ' -mindepth 1 -maxdepth 1 -type d -printf "%P\n"  | sort -nr | head -1')


    # 探测mysql实例是否存活,如果存活继续下面的程序执行,如果不存活则直接退出程序

    mysql_stat = commands.getoutput(

        '/bin/netstat -anp|grep ' + port + ' |grep -v unix|wc -l')


    if mysql_stat >= 1:

        print "mysql实例存活,可进行备份操作!"

    else:

        print "mysql实例不存在,备份操作终止!"

        sys.exit()


    # 每周生成一个周备份目录,全备和增备目录都放在此目录下面

    if os.path.exists(week_of_dir):

        print "周备份目录已经生成,可进行相应的全备或者增量备份"

    else:

        print "周备份目录未产生,创建周备份目录..."

        os.makedirs(week_of_dir)


    # 判断是否周日,如果是周日,直接进行全备,如果不是周日,先检查全备是否存在,不存在则进行全备,存在则进行增备

    print "备份开始于:  " + time.strftime( "%Y-%m-%d %H:%M:%S",time.localtime())

    if wday == 6:

        full_backup(host, port, user, password, full_backup_dir)

    else:

        if os.path.exists(full_backup_dir):

            incr_backup(host, port, user, password,week_of_dir,base_backup_dir)

        else:

            full_backup(host, port, user, password, full_backup_dir)


    print "备份结束,判断备份是否成功"

    print "备份结束于:  " + time.strftime( "%Y-%m-%d %H:%M:%S",time.localtime())

    try:

        with open("/tmp/backup.log") as f:

            f.seek(-14, 2)

            backup_results = f.readline().strip()

            if backup_results == "completed OK!":

                print "备份成功"

            else:

                print "备份失败"

                shutil.rmtree(base_backup_dir)

    except Error:

        sys.exit()