# -*- coding: utf-8 -*-
import os
os.environ["HTTPGUARD_SETTINGS"] = "/opt/httpguard/master/conf/config.py"
import app
import time
import subprocess
import requests
import json
import re
import ntpath
import shutil
import platform
from requests.adapters import HTTPAdapter

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
upgrade_success = False
upgrade_ignore = False

log_file = "/tmp/master_upgrade_log_file.log"

class log(object):
    def __init__(self, arg):
        super(log, self).__init__()
        self.arg = arg
    
    @staticmethod
    def error(info):
        print info
        with open(log_file,"a") as fp:
            fp.write(u"[ERROR] " + info+"\n")

    @staticmethod
    def info(info):
        print info
        with open(log_file,"a") as fp:
            fp.write(u"[INFO] " + info+"\n")

    @staticmethod
    def warning(info):
        print info
        with open(log_file,"a") as fp:
            fp.write(u"[WARNING] " + info+"\n")


def heartbeat(name):
    heartbeat_file = os.path.join("/tmp",name + ".heartbeat")
    with open(heartbeat_file,"w") as fp:
        fp.write("")

def main():
    global upgrade_success
    global upgrade_ignore

    upgrade = app.Config.query.filter_by(name="upgrade").first()
    current_ver = app.app.config["VERSION_NUM"]
    current_ver_name = app.app.config["VERSION_NAME"].strip()
    if upgrade is None:
        app.db.session.close()
        return

    with open(log_file,"w") as fp:
        fp.write("")

    log.info(u"开始升级...")    
    url = app.app.config["LATEST_VERSION_URL"] + "?version=" + str(current_ver)

    try:
        log.info(u"请求版本接口..")
        r = requests.get(url ,timeout=20)
        status_code = r.status_code
        if status_code != 200:
            log.error("{url} return {status_code}".format(url=url,status_code=status_code))
            return

        content = r.content
        content = json.loads(content)
        state = content["state"]
        upgrade_msg = content["msg"]
        if state == "failed":
            info = u"请求url: {url}失败，原因：{upgrade_msg}".format(url=url, upgrade_msg=upgrade_msg)
            log.error(info)
            return

        if len(upgrade_msg) == 0:
            info = u"版本接口返回为空,当前已经是最新版本"
            log.warning(info)
            app.Config.query.filter_by(name="upgrade").delete()
            app.db.session.commit()
            app.db.session.close()
            upgrade_ignore = True            
            return                

        last_record = upgrade_msg[len(upgrade_msg) - 1]
        latest_version = last_record["version_num"]
        version_name = last_record["version_name"]
        if current_ver == latest_version:
            info = u"当前已经是最新版本 {version_name}".format(version_name=version_name)
            log.warning(info)
            app.Config.query.filter_by(name="upgrade").delete()
            app.db.session.commit()
            app.db.session.close() 
            upgrade_ignore = True
            return 

        # 获取操作系统版本
        sys_ver = platform.platform()
        sys_ver = re.sub(r'.*-with-(.*)-.*',"\g<1>",sys_ver)
        if sys_ver.startswith("centos-7"):
            sys_ver = "centos-7"

        if sys_ver.startswith("centos-6"):    
            sys_ver = "centos-6"

        for i in range(len(upgrade_msg)):
            master_script_url = upgrade_msg[i]['master_script_url']
            version_num = upgrade_msg[i]['version_num']
            code_url = upgrade_msg[i]['code_url'] + "-" + sys_ver + ".tar.gz"
            version_name = upgrade_msg[i]['version_name']
            version_dir = "/opt/httpguard-{version_name}".format(version_name=version_name)
            file_path = "/opt/httpguard-{version_name}.tar.gz".format(version_name=version_name)


            # 下载文件
            log.info(u"下载{version_name}软件包...".format(version_name=version_name))
            if os.path.exists(version_dir):
                info = u"{version_dir}目录已经存在，不需要重新下载".format(version_dir=version_dir)
                log.warning(info)

            else: 
                try:
                    subprocess.check_output(["wget",code_url,"-t","2","--timeout=60","-O",file_path],stderr=subprocess.STDOUT)
                    info = u"下载文件{file_path}成功".format(file_path=file_path)
                    log.info(info)

                except subprocess.CalledProcessError as e:
                    info = u"下载文件失败,url: {code_url},原因：{reason}".format(code_url=code_url, reason=e.output)
                    log.error(info)
                    return

                # 解压文件
                log.info(u"解压{version_name}软件包...".format(version_name=version_name))
                try:
                    subprocess.check_output(["tar","xf",file_path,"-C","/opt"],stderr=subprocess.STDOUT)
                    info = u"解压文件{file_path}成功".format(file_path=file_path)
                    log.info(info)

                except subprocess.CalledProcessError as e:
                    info = u"解压文件失败,原因：{reason}".format(reason=e.output)
                    log.error(info)
                    return


            # 下载升级脚本
            script_file_name = "master_{version_num}.py".format(version_num=version_num)

            try:
                log.info(u"下载升级脚本{script_file_name}...".format(script_file_name=script_file_name))
                subprocess.check_output(["wget",master_script_url,"-t","2","--timeout=60","-O","/tmp/"+script_file_name],stderr=subprocess.STDOUT)
                info = u"成功下载升级脚本{script_file_name}".format(script_file_name=script_file_name)
                log.info(info)

            except subprocess.CalledProcessError as e:
                info = u"下载文件失败,url: {master_script_url},原因：{reason}".format(master_script_url=master_script_url, reason=e.output)
                log.error(info)
                return

            # 执行脚本升级
            script_file_path = "/tmp/{script_file_name}".format(script_file_name=script_file_name)
            done_file = "{script_file_path}.done".format(script_file_path=script_file_path)
            if i == 0:
                last_version_dir = "/opt/httpguard"
            else:    
                last_version_name = upgrade_msg[i-1]['version_name']
                last_version_dir = "/opt/httpguard-{version_name}".format(version_name=last_version_name)

            log.info(u"执行升级脚本{script_file_path}...".format(script_file_path=script_file_path))
            try:
                if os.path.exists(done_file):
                    info = "已经执行过脚本{script_file_path},忽略.".format(script_file_path=script_file_path)
                    log.warning(info)
                    continue

                subprocess.check_output(["python",script_file_path,version_dir,last_version_dir],stderr=subprocess.STDOUT)
                info = u"成功执行升级脚本{script_file_path}".format(script_file_path=script_file_path)
                log.info(info)

                with open(done_file, "w") as f:
                    f.write("")

            except subprocess.CalledProcessError as e:
                info = u"执行脚本{script_file_path}失败,原因：{reason}".format(script_file_path=script_file_path, reason=e.output)
                log.error(info)
                return

        # 发送指令控制升级agent
        nodes = app.Node.query.filter_by(enable=True).all()
        for node in nodes:
            ip = node.ip
            port = node.port
            name = node.name

            url = "http://{ip}:{port}/v1/mark-upgrade".format(ip=ip,port=port)
            log.info(u"向agent {name}发送升级指令 {url}...".format(name=name, url=url))
            try:
                r = requests.post(url, data=None, timeout=5)

            except requests.exceptions.Timeout:
                info = u"连接超时,重试 url: {url}".format(url=url)
                log.warning(info)
                time.sleep(5)
                r = requests.post(url, data=None, timeout=5)

            except requests.exceptions.ConnectionError:
                info = u"连接错误,重试 url: {url}".format(url=url)
                log.warning(info)
                time.sleep(5)
                r = requests.post(url, data=None, timeout=5)

            status_code = r.status_code
            if status_code != 200:
                log.error("{url} return {status_code}".format(url=url,status_code=status_code))
                return

            content = r.content
            content = json.loads(content)
            state = content["state"]
            msg = content["msg"]
            if state == "failed":
                info = u"请求url {url}失败，原因:{msg}".format(url=url, msg=msg)
                log.error(info)
                return

            info = u"成功对{name}节点发送升级指令".format(name=name)
            log.info(info)


        # 检查是否升级成功
        nodes_tmp = nodes
        timeout = 300
        start = time.time()
        while len(nodes_tmp) != 0:
            for i, node in enumerate(nodes_tmp):
                ip = node.ip
                port = node.port
                name = node.name

                url = "http://{ip}:{port}/v1/agent-version".format(ip=ip,port=port)
                log.info(u"检查agent {name}是否升级成功...".format(name=name))
                try:
                    r = requests.get(url, timeout=5)

                except requests.exceptions.Timeout:
                    info = u"连接超时,重试 url: {url}".format(url=url)
                    log.warning(info)
                    time.sleep(5)
                    r = requests.get(url, timeout=5)

                except requests.exceptions.ConnectionError:
                    info = u"连接错误,重试 url: {url}".format(url=url)
                    log.warning(info)
                    time.sleep(5)
                    r = requests.get(url, timeout=5)           

                status_code = r.status_code
                if status_code != 200:
                    log.error("{url} return {status_code}".format(url=url,status_code=status_code))
                    return

                content = r.content
                content = json.loads(content)
                state = content["state"]
                msg = content["msg"]
                if state == "failed":
                    info = u"请求url {url}失败，原因:{msg}".format(url=url, msg=msg)
                    log.error(info)
                    return

                if msg == latest_version:
                    del nodes_tmp[i]
                    info = u"agent {name}升级成功".format(name=name)
                    log.info(info)

            time.sleep(3)
            if (time.time() - start) > timeout:
                failed_node = " ".join( [str(node.name) for node in nodes_tmp])
                info = u"升级超时的节点有{failed_node},请打开节点的/tmp/agent_upgrade_log_file.log查看失败原因".format(failed_node=failed_node)
                log.error(info)
                return

        # 复制supervisord.conf
        old_path = '/opt/httpguard-'+current_ver_name+'/master/conf/supervisord.conf'
        new_path = version_dir + '/master/conf/supervisord.conf'
        if os.path.exists(new_path):
            os.remove(new_path)

        if os.path.exists(old_path):
            shutil.copyfile(old_path,new_path)

        old_path = '/opt/httpguard-'+current_ver_name+'/agent/supervisord.conf'
        new_path = version_dir + '/agent/supervisord.conf'
        if os.path.exists(new_path):
            os.remove(new_path)

        if os.path.exists(old_path):
            shutil.copyfile(old_path,new_path)

        # 替换新版本
        log.info(u"替换为新版本...")
        os.remove("/opt/httpguard")
        try:
            subprocess.check_output(["ln","-s",version_dir,"/opt/httpguard"],stderr=subprocess.STDOUT)
            info = u"成功替换新版本为{version_dir}".format(version_dir=version_dir)
            log.info(info)

        except subprocess.CalledProcessError as e:
            info = u"替换新版本{version_dir}失败,原因：{reason}".format(version_dir=version_dir, reason=e.output)
            log.error(info)
            return

        # 执行升级完成后的脚本
        for i in upgrade_msg:
            master_script_url_done = i['master_script_url_done']
            version_num = i['version_num']
            code_url = i['code_url']
            version_name = i['version_name']

            if master_script_url_done == "":
                continue
                
            # 下载升级脚本
            script_file_name_done = "master_{version_num}_done.py".format(version_num=version_num)

            try:
                log.info(u"下载升级脚本{script_file_name_done}...".format(script_file_name_done=script_file_name_done))
                subprocess.check_output(["wget",master_script_url_done,"-t","2","--timeout=60","-O","/tmp/"+script_file_name_done],stderr=subprocess.STDOUT)
                info = u"成功下载升级脚本{script_file_name_done}".format(script_file_name_done=script_file_name_done)
                log.info(info)

            except subprocess.CalledProcessError as e:
                info = u"下载文件失败,url: {master_script_url_done},原因：{reason}".format(master_script_url_done=master_script_url_done, reason=e.output)
                log.error(info)
                return

            # 执行脚本升级
            script_file_path = "/tmp/{script_file_name_done}".format(script_file_name_done=script_file_name_done)
            done_file = "{script_file_path}.done".format(script_file_path=script_file_path)
            log.info(u"执行升级脚本{script_file_path}...".format(script_file_path=script_file_path))
            try:
                if os.path.exists(done_file):
                    info = "已经执行过脚本{script_file_path},忽略.".format(script_file_path=script_file_path)
                    log.warning(info)
                    continue

                subprocess.check_output(["python",script_file_path],stderr=subprocess.STDOUT)
                info = u"成功执行升级脚本{script_file_path}".format(script_file_path=script_file_path)
                log.info(info)

                with open(done_file, "w") as f:
                    f.write("")

            except subprocess.CalledProcessError as e:
                info = u"执行脚本{script_file_path}失败,原因：{reason}".format(script_file_path=script_file_path, reason=e.output)
                log.error(info)
                return            

        # 重启master
        master_supervisor_conf = "/opt/httpguard/master/conf/supervisor_master.conf"
        program_list = []
        with open(master_supervisor_conf, "r") as fp:
            for line in fp:
                m = re.match(r"\[program:(.*)\]",line)
                if m:
                    program_name = m.group(1)
                    program_list.append(program_name)

        for i in program_list:
            if i == "master_upgrade":
                continue

            try:
                log.info(u"重启{i}...".format(i=i))
                subprocess.check_output(["supervisorctl", "-c","/opt/httpguard/master/conf/supervisord.conf","update",i],stderr=subprocess.STDOUT)
                subprocess.check_output(["supervisorctl", "-c","/opt/httpguard/master/conf/supervisord.conf","restart",i],stderr=subprocess.STDOUT)
                info = u"成功重启{i}".format(i=i)
                log.info(info)

            except subprocess.CalledProcessError as e:
                info = u"重启{i}失败,原因：{reason}".format(i=i, reason=e.output)
                log.error(info)
                return

        upgrade_success = True
        log.info(u"HttpGuard升级成功")
        return

    except ValueError:
        info = u"返回的内容不为json,content: {content} url:{url}".format(content=content,url=url)
        log.error(info)

    except requests.exceptions.Timeout:
        info = u"连接超时 url: {url}".format(url=url)
        log.error(info)

    except requests.exceptions.ConnectionError:
        info = u"连接错误 url: {url}".format(url=url)
        log.error(info)

    finally:
        if upgrade_ignore:
            return

        if not upgrade_success:
            log.error(u"升级失败,异常退出,请查看/var/log/httpguard/日志")

        log.info(u"升级结束")
        try:
            os.remove(file_path)
        except:
            log.warning(u"删除文件压缩文件出错,可能不存在")

        app.Config.query.filter_by(name="upgrade").delete()
        app.db.session.commit()
        app.db.session.close()
        

if __name__ == '__main__':
    main()