# -*- coding: utf-8 -*-
import traceback
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.common.message import Message
from utils.common.exception import HCCIException
from plugins.DistributedStorage.logic.DeployOperate import DeployOperate
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorage.logic.InstallOperate import InstallOperate


class ConfigKVMResourcePool(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None, metadata=None, **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.backend_name = self.fs_args.get('backend_name')
        self.opr = DeployOperate(self.fs_args)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.install_opr = InstallOperate(self.project_id, self.pod_id, fs_args)

    def procedure(self):
        try:
            logger.info("Start to config cinder connect fusionstoarge.")
            cps_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)
            private_key_psw = self.install_opr.upload_cert_and_get_private_key(cps_client)

            compute_ip_list = [vbs['om_ip'] for vbs in self.vbs_list]
            compute_id_list = [vbs['hostname'] for vbs in self.vbs_list]
            webui_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)

            status_code, error_code, error_des = self.opr.login(DeployConstant.DM_LOGIN_USER,
                                                                self.fs_args['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 = self.opr.query_storage_pool()
            pool_info = res_pool.get_query_data()
            if len(pool_info.get('storagePools')) == 0:
                logger.error('check pool fail...')
                raise Exception("check pool fail...")
            pool_id_list = [str(pool.get('poolId')) for pool in pool_info.get('storagePools')]
            pool_id_list = ','.join(pool_id_list)
            self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.fs_args['dm_update_pwd'])

            over_ratio = self.db.get_value_from_cloudparam(self.pod_id, "DistributedStorageBusiness",
                                                           "business_thin_alloc_rate")
            logger.info("Config cinder connect fusionstoarge.")

            az = self.db.get_user_input_cloud_param_by_key(self.project_id, "openstack_region")
            obj = ConfinCascadingKvm(webui_client)
            cluster_name = obj.get_storage_resource_cluster_name_kvm_fusionstorage(az, self.backend_name)
            if cluster_name:
                self.logger_info("The resource:%s is exist; To avoid duplication of configuration, "
                                 "need to delete first" % cluster_name)
                obj.delete_resource(cluster_name)
            # 增加FusionStorage的融合部署的动作
            MAX_VBS_NUM = 3
            if len(compute_ip_list) > MAX_VBS_NUM:
                compute_ip_list = compute_ip_list[:MAX_VBS_NUM]
            fusionstorageagent = ",".join(compute_ip_list)

            MAX_HOST_NUM = 3
            if len(compute_id_list) > MAX_HOST_NUM:
                compute_id_list = compute_id_list[:MAX_HOST_NUM]
            obj.config_cascaded_kvm(self.backend_name, self.float_ip, fusionstorageagent, pool_id_list, over_ratio,
                                    compute_id_list, az, private_key_psw)
            self.logger_info("config cinder connect fusionstoarge success.")

            return Message(200)
        except HCCIException as e:
            logger.error(traceback.format_exc())
            return Message(500, e)
        except Exception as e:
            return Message(500, HCCIException(626006, str(e)))

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