# -*- 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.manageone_cmdb_util import ManageOneCmdbUtil
from utils.business.param_util import ParamUtil
from utils.common.ssh_util2 import Ssh
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.base import TestCase


SSH_TIMEOUT = 30


class EnvCheck(TestCase):
    def __init__(self, project_id, pod_id, fs_args, regionid_list):
        super(EnvCheck, self).__init__(project_id, pod_id)
        self.region_id = regionid_list[0]
        self.fsm_ip = fs_args["float_ip"]
        self.master_ip = fs_args["master_ip"]
        self.master_user_name = fs_args["master_username"]
        self.master_password = fs_args["master_password"]
        self.param_util = ParamUtil()

    def procedure(self):
        logger.info('Start environment check task.')
        try:
            self.main()
        except Exception as e:
            logger.error('Environment check failed,details:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e

    def main(self):
        db_info = self._get_cmdb_info()
        if not db_info:
            logger.error("Get cmdb info failed, the result is None.")

        manage_storage_flag = self._parse_info(db_info)
        cpu_type = self._get_cpu_type()
        if "x86_64" in cpu_type and manage_storage_flag:
            err_msg = "The x86 management storage does not support upgrade., " \
                      "check failed Node: {%s}, result: %s" % (self.fsm_ip, cpu_type)
            logger.error(err_msg)
            raise Exception(err_msg)
        logger.info("Environment check pass.")

    def _parse_info(self, info):
        """
        解析数据查看当前节点是否是管理存储节点
        """
        not_manage_fsm_ip = None
        if isinstance(info, list):
            pass
        elif isinstance(info, dict):
            info = [info]
        else:
            logger.error("Parse extendInfos failed!")
            raise Exception("Parse extendInfos failed!")

        for each in info:
            extend_list = each.get("extendInfos")
            extend_dict = dict()
            for i in extend_list:
                extend_dict.update({i.get("key"): i.get("value")})
            logger.info("Extend info dict is: %s" % str(extend_dict))

            if extend_dict.get("az_id") == "manage-az" and \
                    extend_dict.get("fsm_float_ip") == self.fsm_ip:
                return 1
        return not_manage_fsm_ip

    def _get_cmdb_info(self):
        mo_cmdb = ManageOneCmdbUtil(self.project_id)
        cmdb_info = mo_cmdb.get_cloud_service_info(self.region_id,
                                                   "FusionStorageBlock")
        logger.info("get cmdb info %s" % cmdb_info)
        return cmdb_info

    def _get_cpu_type(self):
        check_os_type = "uname -p"
        client = self._create_fsm_client()
        resp = Ssh.ssh_send_command(client, check_os_type, "$", SSH_TIMEOUT)
        return str(resp)

    def _create_fsm_client(self):
        """
        创建 SSH 连接
        :return:
        """
        try:
            client = Ssh.ssh_create_client(self.master_ip,
                                           self.master_user_name,
                                           self.master_password, status=False)
            return client
        except HCCIException as e:
            logger.error(e)
            raise e
        except Exception as ex:
            logger.error("Create SSH client failed, error msg: {}".format(ex))
            raise HCCIException(470058, self.master_ip, ex) from ex
