#!/bin/bash
# R20C10偶现备份产品失败，升级前规避脚本

(
cat <<EOF
#!/usr/bin/env python3
# encoding: utf-8
"""R20C10升级R21C10 偶现备份产品失败规避"""

import os
import sys
import subprocess
import logging
import pyzenith
from deployment import containerlist
from deployment import tenants
from util import ossext

SUCCESS = 0
FAILED = 1
BACKUP_DB = "backupdb"
LOG_FILE = os.path.splitext(os.path.realpath(__file__))[0] + '.log'
logging.basicConfig(filename=LOG_FILE, level=logging.INFO,
                    format=' %(asctime)s - %(levelname)s - %(message)s')


def clear_backupdb(master_instance_dict):
    """
    R20C10升级R21C10 偶现备份产品失败规避
    :return:
    """
    print("Start to clear backupdb")
    key = ''
    for instance_key in master_instance_dict.keys():
        if "managedbsvr" in instance_key:
            key = instance_key
            break
    if not master_instance_dict.get(key):
        print("query instance name failed")
        logging.error("query instance name failed")
        return
    db_info_dict = master_instance_dict.get(key)
    connect_ip = db_info_dict.get("connect_ip")
    port = db_info_dict.get("port")
    db_info = db_info_dict.get("db_list").get(BACKUP_DB)
    if not db_info:
        log_info = "no such database: {}".format(BACKUP_DB)
        print(log_info)
        logging.error(log_info)
        return
    print(f"master:{connect_ip}")
    password = ossext.Cipher.decrypt(db_info.get("dbUserPasswd"))
    conn = pyzenith.connect(host=connect_ip, user=BACKUP_DB,
                            passwd=password, port=str(port))
    cursor = conn.cursor()
    clear_maintenance_backupdb(conn, cursor)
    cursor.close()
    conn.close()
    print("End to clear backupdb")
    return


def clear_maintenance_backupdb(conn, cursor):
    """
     修改网卡用途
    :param conn:
    :param cursor:
    :return:
    """
    try:
        exe_sql = "delete from TAL_BACKUP_TAG"
        print(exe_sql)
        cursor.execute(exe_sql)
    except pyzenith.DatabaseError:
        log_info = "execute sql failed"
        print(log_info)
        logging.debug(log_info)
        return
    conn.commit()
    return


def get_master_db_instance():
    """
    获取当前节点所有主数据库实例
    :return:
    """
    all_instance_list = containerlist.ContainerList(tenants.Tenant("manager")) \
        .getDCByTypeList("zenith")

    master_instance_dict = {}
    command = "{path}/manager/apps/DBAgent/bin/dbsvc_adm -cmd query-db-instance | " \
              "grep {cluster_name} | grep \" {ip} \" | grep Master"
    for instance in all_instance_list:
        if not instance.getClusterName():
            cluster_name = instance.getName()
        else:
            cluster_name = instance.getClusterName()
        status, _ = subprocess.getstatusoutput(command.format(
            path=os.environ['INSTALL_ROOT'], cluster_name=cluster_name, ip=instance.getIP()))
        if status == SUCCESS:
            get_db_list(all_instance_list, instance, master_instance_dict)

    return master_instance_dict


def get_db_list(all_instance_list, instance, master_instance_dict):
    """
    获取dblist信息
    """
    db_list = instance.getDBList()
    if not db_list:
        log_info = "no db_list in {}".format(instance.getName())
        print(log_info)
        logging.debug(log_info)
        for peer_instance in all_instance_list:
            if peer_instance.getName().split("-")[0] == instance.getName().split("-")[0] \
                    and peer_instance != instance:
                db_list = peer_instance.getDBList()
                log_info = "get db_list in {}".format(peer_instance.getName())
                print(log_info)
                logging.debug(log_info)
    if not db_list:
        log_info = "db_list is null,please confirm"
        print(log_info)
        logging.error(log_info)
        return
    master_instance_dict[instance.getName()] = {
        "connect_ip": instance.getIP(),
        "port": instance.getPort(),
        "db_list": db_list
    }


def main():
    """
    函数入口
    :return:
    """
    master_instance_dict = get_master_db_instance()
    if not master_instance_dict:
        log_info = "current node has no master instance,exit 0"
        print(log_info)
        logging.debug(log_info)
        return FAILED

    clear_backupdb(master_instance_dict)
    return SUCCESS


if __name__ == '__main__':
    sys.exit(main())

EOF
) > /tmp/clear_backupdb.py

chown ossadm:ossgroup /tmp/clear_backupdb.py
echo "`date "+%Y-%m-%d"`:Start to clear backupdb"
su - ossadm -c ". /opt/oss/manager/bin/engr_profile.sh;python /tmp/clear_backupdb.py" >> /tmp/clear_backupdb.sh.log
su - ossadm -c "sh /opt/oss/manager/apps/UniEPAgent/bin/updatebackupcache.sh" >> /tmp/clear_backupdb.sh.log
rm -rf /tmp/clear_backupdb.py
echo "`date "+%Y-%m-%d"`:End to clear backupdb"