# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback

import utils.common.log as logger
from utils.business.project_condition_utils import get_project_condition_boolean
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
from plugins.ResourceCheck.common.libs.BMCCmd import BMCCmdExc


class DoCheckMemory(TestCase):
    def __init__(self, *args):
        self.project_id = args[0]
        self.pod_id = args[1]
        self.cmd_exe = BMCCmdExc()
        self.db = BaseOps()

    def procedure(self):
        """检查存储节点的内存"""
        # 查询storage node 的IP、用户名、密码
        is_rep = get_project_condition_boolean(self.project_id,
                                               "(CSHAStorage_TFB|CSDRStorage_TFB)&!DRStorage_TFB_Sep")
        odk_test_memory_min = 82 if is_rep 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:
            bmc_ip = bmc_info.get('bmc_ip')
            logger.info("bmc_ip:%s Mem check" % bmc_ip)
            bmc_result = result.get(bmc_ip)
            if bmc_result.get("result") == '0':
                memory_required = float(odk_test_memory_min)
                display_memory_required = float(odk_test_memory_min)
                try:
                    mem_size = (int(bmc_result.get("stdout").strip()) / 1024 / 1024)
                except ZeroDivisionError as e:
                    logger.error(traceback.format_exc())
                    raise e
                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.get("equipment_model"), display_memory_required, bmc_ip)
            else:
                logger.info("Mem_Size check is Failed,%s!", bmc_result.get("stderr"))
                raise HCCIException("625301", bmc_result.get("stderr"))


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()
        except HCCIException as e1:
            logger.error('check memory error:{}'.format(traceback.format_exc()))
            return Message(500, e1)
        except Exception as e2:
            logger.error('check memory error:{}'.format(traceback.format_exc()))
            return Message(500, HCCIException('625301', str(e2)))
        return Message(200)

    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)
