# -*- coding: utf-8 -*-
from plugins.ResourceCheck.common.libs.BMCCmd import BMCCmdExc
from utils.common.fic_base import StepBaseInterface
from utils.common.fic_base import TestCase
from utils.common.message import Message
import utils.common.log as logger
from utils.common.exception import HCCIException
from utils.constant.pci_slot_mapping import pci_slot_mapping_dic
from plugins.DistributedStorage.Deploy.scripts.PreCheck.common.dataUnits import HostData


class CPUCheckIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CPUCheckIntf, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.implement = CPUCheck(project_id, pod_id)

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

    def execute(self, project_id, pod_id):
        try:
            self.implement.procedure()
            return Message(200)
        except HCCIException as e1:
            return Message(500, e1)
        except Exception as e2:
            return Message(500, HCCIException(627209, 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:
        """
        pass


class CPUCheck(TestCase):
    def __init__(self,project_id, pod_id):
        self.pod_id = pod_id
        self.project_id = project_id

    def procedure(self):

        """
        检查复制节点CPU
       """
        try:
            cmd_exe = BMCCmdExc()
            node_obj = HostData(self.project_id, self.pod_id)
            bmc_info_lists = node_obj.get_separate_compute_node_list()
            equipment_model = bmc_info_lists[0].get('equipment_model')
            cpu_arch = 'ARM'
            if equipment_model in pci_slot_mapping_dic.keys():
                equipment_info = pci_slot_mapping_dic.get(equipment_model)
                cpu_arch = equipment_info.get('project_condition')
            cpu_required = 4
            bmc_ip_list = [bmc_info["bmc_ip"] for bmc_info in bmc_info_lists]
            logger.info('start to exec cmd to bmc pxe,bmc list：%s' % str(bmc_ip_list))
            if 'ARM' in cpu_arch.upper():
                cmd = "size=$(grep -o 'processor' /proc/cpuinfo | wc -l);echo $((size))"
            else:
                cmd = "cpucore=$(awk '/cpu cores/{print $NF;exit}' /proc/cpuinfo);" \
                      "cpuslot=$(grep 'physical id' /proc/cpuinfo | sort -u | wc -l);" \
                      "echo $((cpucore*cpuslot))"
            result = cmd_exe.run(bmc_ip_list, cmd)
            logger.info("Exec cmd: %s, result: %s" % (cmd, result))
            fail_list = []
            logger.info('start to check bmc cpu')
            for bmc_info in bmc_info_lists:
                bmc_result = result[bmc_info["bmc_ip"]]['stdout']
                if result[bmc_info["bmc_ip"]]['result'] == '1':
                    logger.error('bmcip[%s] check result is %s' % (bmc_info['bmc_ip'], bmc_result))
                    fail_list.append(bmc_info['bmc_ip'])
                    continue
                logger.info('bmcip[%s] check result is %s' % (bmc_info['bmc_ip'], bmc_result))
                size = int(bmc_result.strip())
                logger.info('bmcip[%s] cpu size is %s' % (bmc_info['bmc_ip'], size))
                if int(size) >= cpu_required:
                    logger.info("cpu check success")
                else:
                    logger.error("cpu check fail")
                    fail_list.append(bmc_info['bmc_ip'])
            if fail_list:
                logger.error('all bmc list exist check fail list ,%s' % str(fail_list))
                raise HCCIException(627209, str(fail_list))
            logger.info('all bmc list exist check  success')
            return True, None
        except HCCIException as e1:
            raise e1
        except Exception as e2:
            raise e2

    def post_condition(self):
        pass

    def failure(self):
        super(CPUCheck, self).failure()
        # 环境恢复脚本
