# -*- coding:utf-8 -*-
import time
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from utils.common.exception import FCUException
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.ssh_util import Ssh
from plugins.eBackup.common.util import Utils

RETRY_TIME_LIMIT = 10


class DatamoverStatusCheck(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(DatamoverStatusCheck, self).__init__(project_id,
                                                   pod_id,
                                                   regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.param_dict = Utils.init_system_params(project_id,
                                                   regionid_list[0])

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            check_results = []
            ssh = Ssh()
            hcp_password = self.param_dict["eBackup_hcp_pwd"]
            root_password = self.param_dict["eBackup_root_pwd"]
            server_ips = self.param_dict['eBackup_Datamover_nodes']
            server_ips = server_ips.replace(" ", "").replace("|", ";"). \
                split(";")
            logger.info("Begin to check nodes:" + str(server_ips))
            # 1.check service hcp status
            retry_times = 1
            check_cmd = "service hcp status>/dev/null;echo execute " \
                        "ebk_cmd result: $?"
            while retry_times < RETRY_TIME_LIMIT:
                is_all_ok = True
                for ebk_ip in server_ips:
                    result = ssh.ssh_cmds(ebk_ip, check_cmd, "hcp",
                                          hcp_password, root_password, "", "")
                    if "execute ebk_cmd result: 0" not in result:
                        logger.error("datamover node(%s) is not running." %
                                     ebk_ip)
                        is_all_ok = False

                if is_all_ok:
                    break
                time.sleep(60)
                retry_times = retry_times + 1

            if retry_times == RETRY_TIME_LIMIT:
                logger.error("Status Check failed after 10 min.")
                return Message(500, "Datamover Status Check "
                                    "failed after 10 min.")
            logger.info("StatusCheck nodes(%s) completed." % server_ips)
            return Message(200, check_results=check_results)
        except FCUException as e:
            logger.error("StatusCheck failed: " + str(e))
            return Message(500, e)

        except Exception as e:
            logger.error("Failed to exec StatusCheck ,the reason is %s" % e)
            return Message(500, error_msg_cn="状态检查出现异常，请查看日志并重试",
                           error_msg_en="Exception occurs while Status "
                                        "Checking,please check the log and"
                                        " try again.")

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        return self.execute(project_id, pod_id, regionid_list)


class WorkflowStatusCheck(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(WorkflowStatusCheck, self).__init__(project_id, pod_id,
                                                  regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.param_dict = Utils.init_system_params(project_id,
                                                   regionid_list[0])

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            check_results = []
            ssh = Ssh()
            hcp_password = self.param_dict["eBackup_hcp_pwd"]
            root_password = self.param_dict["eBackup_root_pwd"]
            server_ips = self.param_dict["eBackup_Datamover_nodes"]
            server_ips = (
                server_ips.replace(" ", "").replace("|", ";").split(";"))
            logger.info("Begin to check nodes:" + str(server_ips))
            # 1.check service hcp status
            retry_times = 1
            check_cmd = (
                "service hcp status>/dev/null;echo execute ebk_cmd result: $?")
            while retry_times < RETRY_TIME_LIMIT:
                is_all_ok = True
                for ebk_ip in server_ips:
                    result = ssh.ssh_cmds(ebk_ip, check_cmd, "hcp",
                                          hcp_password, root_password, "", "",)
                    if "execute ebk_cmd result: 0" not in result:
                        logger.error(
                            "datamover node(%s) is not running." % ebk_ip)
                        is_all_ok = False

                if is_all_ok:
                    break
                time.sleep(60)
                retry_times = retry_times + 1

            if retry_times == RETRY_TIME_LIMIT:
                logger.error("Status Check failed after 10 min.")
                return Message(
                    500, "Datamover Status Check failed after 10 min.")
            logger.info("StatusCheck nodes(%s) completed." % server_ips)
            return Message(200, check_results=check_results)
        except FCUException as e:
            logger.error("StatusCheck failed: " + str(e))
            return Message(500, e)

        except Exception as e:
            logger.error("Failed to exec StatusCheck ,the reason is %s" % e)
            return Message(
                500,
                error_msg_cn="状态检查出现异常，请查看日志并重试",
                error_msg_en="Exception occurs while Status Checking,"
                             "please check the log and try again.",)

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        return self.execute(project_id, pod_id, regionid_list)


class DriverStatusCheck(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(DriverStatusCheck, self).__init__(project_id, pod_id,
                                                regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.region_id = regionid_list[0]
        self.params_dict = Utils.init_system_params(project_id,
                                                    regionid_list[0])
        self.fsp_passwd = self.params_dict['openstack_fsp_pwd']
        self.fsp_sudo_password = self.params_dict['openstack_root_pwd']
        self.cps_user_pwd = self.params_dict['openstack_cps_admin_pwd']
        self.region_type = BaseOps().get_region_type(project_id).lower()

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            ssh = Ssh()
            reverse_proxy_ip = self.params_dict['openstack_reverse_proxy_ip']
            logger.info("reverse_proxy_ip is %s" % reverse_proxy_ip)

            set_env_cmd = "source set_env< <(echo 1;echo %s)" % \
                          self.cps_user_pwd
            ssh_client = ssh.ssh_create_client(reverse_proxy_ip, "fsp",
                                               self.fsp_passwd)
            ssh.ssh_send_command(ssh_client, 'su - root', 'Password:', 100)
            ssh.ssh_send_command(ssh_client, self.fsp_sudo_password, '#', 100)
            ssh.ssh_send_command(ssh_client, set_env_cmd, '#', 100)
            query_template_cmd = "cps template-list |grep 'cinder-backup" \
                                 "-kvm' |awk '{print $4}'"
            template_list = ssh.ssh_exec_command_return_list(
                ssh_client,
                query_template_cmd)
            logger.info("template list is %s." % str(template_list))

            retry_times = 1
            ip_str = ""
            while retry_times < RETRY_TIME_LIMIT:
                is_all_ok = True
                for sub_template in template_list:
                    check_cmd = "cps template-instance-list --service " \
                                "cinder " + sub_template + \
                                " | grep -w 'cinder-backup' | " \
                                "grep  -v active | awk '{print $10}'"
                    ip_list = ssh.ssh_exec_command_return_list(
                        ssh_client, check_cmd)
                    logger.info("result is %s." % str(ip_list))

                    if 0 != len(ip_list):
                        is_all_ok = False
                        ip_str = ",".join(ip_list)
                        logger.info("cinder-backup(%s) is not ok." % ip_str)

                if is_all_ok:
                    logger.info("ok.")
                    break
                time.sleep(60)
                retry_times = retry_times + 1

            if retry_times == RETRY_TIME_LIMIT:
                logger.error("cinder-backup-kvm(%s) is not active." % ip_str)

            check_result = []
            return Message(200, check_results=check_result)
        except FCUException as e:
            logger.error("status check driver failed: " + str(e))
            return Message(500, e)
        except Exception as e:
            logger.error("Failed to check eBackup Driver status,"
                         "the reason is %s" % e)
            return Message(500, error_msg_cn="状态检查出现异常，请查看日志并重试",
                           error_msg_en="Exception occurs while status "
                                        "checking,please check the log and "
                                        "try again.")

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        return self.execute(project_id, pod_id, regionid_list)
