# -*- coding:utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import secrets
from tenacity import retry, stop_after_attempt, wait_fixed

import utils.common.log as logger
from utils.common.fic_base import TestCase
from platforms.project.ProjectUtils import get_project_condition_boolean
from plugins.DistributedStorageReplication.scripts.common_utils.config_params import Params
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorageReplication.scripts.common_utils.rest_operate import RestOperate
from plugins.DistributedStorage.scripts.logic.InstallOperate import InstallOperate


class CreateQuorumServerOne(TestCase):
    def __init__(self, project_id, pod_id):
        super(CreateQuorumServerOne, self).__init__(project_id, pod_id, step_id=None, metadata=None)
        self.service_name = "FusionStorageBlockReplication"
        self.install_operate = InstallOperate(project_id, pod_id)
        self.config_license_switch_condition = get_project_condition_boolean(
            self.project_id, '!(ExpansionAdCloudService|ExpansionServiceStorage&CSHAStorage_TFB)')
        parameters = Params(self.project_id, self.pod_id, self.service_name)
        lld_dict = parameters.get_params_dict()
        self.address_ip_list = lld_dict.get("ip_pool")
        self.fsa_ip_list = lld_dict.get("replication_cluster")
        self.fsm_float_ip = lld_dict.get("local_storage_fsm_ip")
        self.control_ip_list = lld_dict.get("replication_controller_cluster")

        # 远端的浮动ip
        self.az_fsm_float_ip = lld_dict.get("remote_storage_fsm_ip")
        self.remote_dsware_password = lld_dict.get("remote_storage_fsm_dsware_password")
        self.remote_cmd_password = lld_dict.get("produce_admin_password")

        self.username = "dsware"
        self.password = lld_dict.get("local_storage_fsm_dsware_password")
        self.cmd_password = lld_dict.get('local_admin_password')
        self.passwd = lld_dict.get("local_storage_fsm_dsware_password")
        self.root_passwd = lld_dict.get("local_storage_fsm_root_password")

        self.quorumserverip = lld_dict.get("storage_arbitration_ip")

        # 远端控制集群id
        self.remote_cluster_id = '0'
        self.control_cluster_id = None
        self.remote_opr = RestOperate(self.az_fsm_float_ip)
        self.opr = RestOperate(self.fsm_float_ip)

    @staticmethod
    def generate_random_str(randomlength=24):
        """仲裁服务器的名字"""
        random_str = ''
        base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
        length = len(base_str) - 1
        for _ in range(randomlength):
            random_str += base_str[secrets.choice(list(range(0, length)))]
        return random_str

    def procedure(self):
        try:
            # 本端
            logger.info("[FSBR] Start to login fsm. ")
            self.opr.login(DeployConstant.DM_LOGIN_USER, self.cmd_password)
            # 远端
            logger.info("[FSBR] Start to login remote fsm. ")
            self.remote_opr.login(DeployConstant.DM_LOGIN_USER, self.remote_cmd_password)
            if self.config_license_switch_condition:
                self.install_operate.config_license_switch(self.fsm_float_ip, self.username, self.passwd,
                                                           self.root_passwd)
            logger.info("[FSBR]add quorunServer white_list success ")
            # 7、创建仲裁服务器
            # 本端
            self.query_control_cluster_id()
            quorum_server_ip_port = self.quorumserverip + ":30002"
            self.create_local_quorum_server(quorum_server_ip_port)

            if self.config_license_switch_condition:
                # 关闭远端FSM节点沙箱
                self.install_operate.disable_fsm_sandbox(self.remote_opr, self.root_passwd, self.remote_cmd_password)
                self.install_operate.config_license_switch(self.az_fsm_float_ip, self.username,
                                                           self.remote_dsware_password, self.root_passwd)

            self.create_remote_quorum_server(quorum_server_ip_port)
            logger.info("[FSBR]createQuorumServer successfully")

            self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.cmd_password)
            self.remote_opr.login_out(DeployConstant.DM_LOGIN_USER, self.remote_cmd_password)
        finally:
            self.install_operate.config_license_switch(
                self.fsm_float_ip, self.username, self.passwd, self.root_passwd, delete=True)
            self.install_operate.config_license_switch(
                self.az_fsm_float_ip, self.username, self.remote_dsware_password, self.root_passwd, delete=True)
            if self.config_license_switch_condition:
                # 开启远端FSM节点沙箱
                self.install_operate.enable_fsm_sandbox(self.remote_opr)

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(20), reraise=True)
    def create_local_quorum_server(self, quorum_server_ip_port):
        local_quorm_name = self.generate_random_str()
        result = self.opr.create_quorum_server(local_quorm_name, quorum_server_ip_port, self.control_cluster_id)
        ret_value = result.query_dr_cmd_result()
        if 0 != ret_value:
            msg = "[FSBR] Failed to create local quorum server. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR]local  createQuorumServer success ")

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(20), reraise=True)
    def create_remote_quorum_server(self, quorum_server_ip_port):
        remote_quorm_name = self.generate_random_str()
        result = self.remote_opr.create_quorum_server(remote_quorm_name, quorum_server_ip_port,
                                                      self.remote_cluster_id)
        ret_value = result.query_dr_cmd_result()
        if 0 != ret_value:
            msg = "[FSBR] Failed to create remote quorum server. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)

    def query_control_cluster_id(self):
        result = self.opr.query_control_cluster()
        self.control_cluster_id = result.get_control_cluster_id()
        if not self.control_cluster_id:
            msg = "[FSBR] Failed to create quorum server, not found control cluster id. " \
                  "detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR] query control cluster id success ")
