# coding=utf-8
from utils.common.exception import HCCIException
from utils.common.message import Message
from utils.common.fic_base import StepBaseInterface
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.project_condition_utils import get_project_condition_boolean
import utils.common.log as logger
from utils.common.ssh_util import Ssh as ssh


class CheckStorageNodeNICIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CheckStorageNodeNICIntf, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：执行安装前的资源预检查，该接口由execute接口调用，工具框架不会直接调用此接口。
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def execute(self, project_id, pod_id):
        try:
            self.procedure(project_id, pod_id)
            return Message(200)
        except HCCIException as e1:
            return Message(500, e1)
        except Exception as e2:
            return Message(500, HCCIException('626273', str(e2)))

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(project_id, pod_id)

    def check(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def procedure(self, project_id, pod_id):
        # 装机场景下不做检查
        if get_project_condition_boolean(project_id, '!TenantStorFB_Heterogeneous'):
            return

        storage_interface_name = "storage_data0"
        if get_project_condition_boolean(project_id, 'Type1&TenantStorFB80&(CascadedOpenStack_BMS|ExpansionPod_BMS)'):
            storage_interface_name = "fsb_data0"
        elif get_project_condition_boolean(project_id, 'TenantStorFB80&(BMS|CascadedOpenStack_BMS|ExpansionPod_BMS|ExpansionAZ_BMS)'):
            return

        bmc_lists = self.db.get_install_os_list_info(pod_id)
        manage_key_name = "manageIp"
        storage_key_name = "storageIp"
        for bmc in bmc_lists:
            manage_ip = bmc[manage_key_name]
            storage_ip = bmc[storage_key_name]

            account_passwd_list = bmc["creuser"].split(",")
            root_passwd = account_passwd_list[1]
            comm_user = account_passwd_list[2]
            comm_passwd = account_passwd_list[3]

            cmd = "ip addr show %s 2>/dev/null | grep -w %s" % (storage_interface_name, storage_ip)
            cmd_res = None
            try:
                ssh_client = ssh.ssh_create_client(manage_ip, comm_user, comm_passwd)
            except Exception as e:
                logger.error("Failed to connect host using user %s, manager_ip:%s, err:%s" % (comm_user, manage_ip, str(e)))
                raise HCCIException(626265, manage_ip)

            try:
                cmd_res = ssh.ssh_send_command(ssh_client, 'su -', 'assword:', 20)
                cmd_res = ssh.ssh_send_command(ssh_client, root_passwd, '#', 20)
                cmd_res = ssh.ssh_send_command(ssh_client, 'TMOUT=0', '#', 20)
            except Exception as e:
                if ssh_client:
                    ssh.ssh_close(ssh_client)
                logger.error("Failed to su root on host cmd_res:%s, using user %s, manager_ip:%s, err:%s" % (str(cmd_res), comm_user, manage_ip, str(e)))
                raise HCCIException(626265, manage_ip)

            try:
                cmd_res = ssh.ssh_send_command(ssh_client, cmd, "inet", 20)
                logger.info("exe cmd[%s] result:%s" % (cmd, str(cmd_res)))
            except Exception as e:
                if ssh_client:
                    ssh.ssh_close(ssh_client)
                logger.error("Failed to check storage_ip:%s, err:%s, cmd_result:%s" % (storage_ip, str(e), str(cmd_res)))
                if storage_interface_name == "storage_data0":
                    raise HCCIException(626264, storage_ip)
                else:
                    raise HCCIException(626266, storage_ip)

            logger.info('Check storage ip passed on manager_ip:%s.' % manage_ip)
            if ssh_client:
                ssh.ssh_close(ssh_client)

