# -*- coding: utf-8 -*-
import utils.common.log as logger
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.ResourceCheck.common.libs.BMCCmd import BMCCmdExc
from utils.DBAdapter.DBConnector import BaseOps
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


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

    def procedure(self):

        """
        检查存储节点的内存
       """
        try:
            # 查询storage node 的IP、用户名、密码
            self.cmd_exe = BMCCmdExc()
            self.db = BaseOps()
            odk_test_memory_min = 82 if get_project_condition_boolean(self.project_id, "(CSHAStorage_TFB|CSDRStorage_TFB)&!DRStorage_TFB_Sep") else 64
            bmc_info_lists = self.db.get_install_os_list_info(self.pod_id)

            bmc_ip_list = [bmc_info["bmc_ip"] for bmc_info in bmc_info_lists]
            cmd = "awk '/MemTotal:/{print $2}' /proc/meminfo"
            result = self.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(odk_test_memory_min)
                    display_memory_required = float(odk_test_memory_min)
                    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("625302", bmc_info["equipment_model"],
                                           display_memory_required,
                                           bmc_info['bmc_ip'])
                else:
                    logger.info("Mem_Size check is Failed,%s!", bmc_result["stderr"])
                    raise HCCIException("625301", 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(DoCheckMemory, self).failure()
        # 环境恢复脚本


class CheckMemory(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CheckMemory, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.implement = DoCheckMemory(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:
            return Message(500, e1)
        except Exception as e2:
            return Message(500, HCCIException('625301', 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)
