# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
from utils.common.fic_base import TestCase
from utils.Driver.CloudDC.OpenStack.config_cascading_kvm import ConfinCascadingKvm
from utils.client.FSPAuthClient import FSPAuthClient
import utils.common.log as logger
from utils.Driver.CloudDC.OpenStack.get_host_info import GetHostInfo
from utils.business.project_util import ProjectApi
from utils.constant.constant import BMCROLE
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorage.scripts.logic.DeployOperate import DeployOperate
from plugins.DistributedStorage.scripts.logic.InstallOperate import InstallOperate


class ConfigKVMResourcePool(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(ConfigKVMResourcePool, self).__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.float_ip = self.fs_args.get('float_ip')
        self.vbs_list = self.fs_args.get('vbs_list')
        self.ha_backend_name = self.fs_args.get('ha_backend_name')
        self.more_args = kwargs
        self.project_ha_dr_status_dict = ProjectApi().get_project_ha_dr_status(self.project_id)
        self.obj = None
        self.webui_client = None
        self.private_key_psw = None
        self.install_opr = InstallOperate(self.project_id, self.pod_id, fs_args)

    def procedure(self):
        cps_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)
        self.private_key_psw = self.install_opr.upload_cert_and_get_private_key(cps_client)
        # 管理面容斋改造场景ProjectModifactionRegionConHA
        control_id_list, control_ip_list = self.get_control_info(dc00x='dc002')
        ha_fs_float_ip = self.db.get_value_from_cloudparam(self.pod_id, "DistributedStorageManage",
                                                           "HAFSMOMFloatingIP")
        self.config_resource_pool(control_ip_list, ha_fs_float_ip, control_id_list, "dc002")
        logger.info("config cinder connect fusionstoarge success.")

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

    def get_pool_id_list(self, fs_args):
        """
        获取存储池ID
        :param fs_args: 管理存储参数
        :return:
        """
        operate = DeployOperate(fs_args)
        status_code, error_code, error_des = operate.login(DeployConstant.DM_LOGIN_USER, fs_args.get('dm_update_pwd'))
        if status_code != 200 or error_code != 0:
            err_msg = "Failed to login deploy manager, Detail:[status:%s,code:%s]%s" % (status_code, error_code,
                                                                                        error_des)
            logger.error(err_msg)
            raise Exception(err_msg)
        logger.info("Query storage pool data.")
        res_pool = operate.query_storage_pool()
        pool_info = res_pool.get_query_data()
        if len(pool_info.get('storagePools')) == 0:
            err_msg = "Failed to query storage pool information"
            logger.error(err_msg)
            raise Exception(err_msg)
        pool_id_list = [str(pool.get('poolId')) for pool in pool_info.get('storagePools')]
        return pool_id_list

    def get_control_info(self, dc00x=None):
        """
        获取控制节点信息
        :param dc00x: dc002表示
        :return:
        """
        self.webui_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)
        self.obj = ConfinCascadingKvm(self.webui_client)
        ret_params_list = self.db.get_bmc_info_by_site_and_bmc_role(dc00x, pod_id=self.pod_id)
        bmc_ip_list = []
        for ret_param in ret_params_list:
            if ret_param["bmc_role"] == BMCROLE.CONTROLLER_NODE or ret_param["bmc_role"] == \
                    BMCROLE.CLOUD_SERVICE_NODE or ret_param["bmc_role"] == BMCROLE.FIRST_NODE:
                bmc_ip_list.append(ret_param['bmc_ip'])
        bmc_ip_list = bmc_ip_list[:3]
        host_info = GetHostInfo(self.webui_client)
        control_id_list, control_ip_list = host_info.get_host_info(bmc_ip_list)
        return control_id_list, control_ip_list

    def config_resource_pool(self, host_ip_list, float_ip, host_id_list, dc00x=None):
        """
        配置资源池
        :param host_ip_list: 计算节点ip
        :param float_ip: 管理存储浮动ip
        :param host_id_list: 计算节点id
        :param private_key_psw: 证书私钥
        :param dc00x: 默认值为None表示非CSHA或者dc001,dc002表示为管理高可用容灾场景2或者管理面容灾改造场景
        :return:
        """
        pool_id_list = self.get_pool_id_list(self.fs_args)
        az = 'dr-manage-az'
        enabled_backend = self.ha_backend_name
        over_ratio = self.db.get_value_from_cloudparam(
                self.pod_id, "DistributedStorageManage", "manage_ha_thin_alloc_rate")
        logger.info("begin to config cinder connect fusionstoarge.")
        cluster_name = self.obj.get_storage_resource_cluster_name_kvm_fusionstorage(az, enabled_backend)
        if cluster_name:
            logger.info("The resource:%s is exist; To avoid duplication of configuration,"
                        " need to delete first" % cluster_name)
            self.obj.delete_resource(cluster_name)
        fsa = ",".join(host_ip_list)
        self.obj.config_cascaded_kvm(enabled_backend, float_ip, fsa, pool_id_list, over_ratio,
                                     host_id_list, az, self.private_key_psw)
