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


class MemoryCheckIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(MemoryCheckIntf, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.implement = MemoryCheck(project_id, pod_id)

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

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


class MemoryCheck(TestCase):
    def pre_condition(self):
        return Message(200)

    def procedure(self):

        """
        检查存储节点的内存
       """
        try:
            cmd_exe = BMCCmdExc()
            node_obj = HostData(self.project_id, self.pod_id)
            bmc_info_lists = node_obj.get_separate_compute_node_list()
            min_memory_req = 8

            bmc_ip_list = [bmc_info["bmc_ip"] for bmc_info in bmc_info_lists]
            cmd = "awk '/MemTotal:/{print $2}' /proc/meminfo"
            result = cmd_exe.run(bmc_ip_list, cmd)
            logger.info("Exec cmd: %s, result: %s" % (cmd, result))
            for bmc_info in bmc_info_lists:
                logger.info("bmc_ip:%s Mem check" % bmc_info['bmc_ip'])
                bmc_result = result[bmc_info["bmc_ip"]]
                if bmc_result["result"] == '0':
                    memory_required = float(min_memory_req)
                    mem_size = (int(bmc_result["stdout"].strip()) / 1024 / 1024)
                    logger.info("Mem_size is %s" % mem_size)
                    if int(mem_size) >= memory_required:
                        logger.info("Mem_Size check is ok !")
                    else:
                        logger.info("Mem_Size check is Failed! ")
                        raise HCCIException("627202", bmc_info["equipment_model"],
                                           memory_required,
                                           bmc_info['bmc_ip'])
                else:
                    logger.info("Mem_Size check is Failed,%s!", bmc_result["stderr"])
                    raise HCCIException("627207", bmc_result["stderr"])

            return True, None
        except HCCIException as e1:
            raise e1
        except Exception as e2:
            raise e2

    def post_condition(self):
        return Message(200)

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