# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import utils.common.log as logger
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.base import TestCase
from plugins.DistributedStorage.common.upgrade_operate import UpgradeOperate


class ServersCheck(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(ServersCheck, self).__init__(project_id, pod_id)
        self.more_args = kwargs
        self.opr = UpgradeOperate(fs_args)
        self.user_name = fs_args["user_name"]
        self.password = fs_args["password"]

    def procedure(self):
        logger.info('Start server check task.')
        fail_results = []
        status_code, error_code, error_des = self.opr.try_login(
            self.user_name, self.password)
        if status_code != 200 or error_code != 0:
            err_msg = "login failed, Detail:[status:%s,code:%s]%s" \
                      % (status_code, error_code, error_des)
            logger.error(err_msg)
            raise Exception(err_msg)

        logger.info('server check.')
        ret_result, ret_data = self.opr.get_servers()
        if ret_result["code"] != 0:
            err_msg = "get servers failed, Detail:[result:%s, data:%s]" \
                      % (ret_result, ret_data)
            logger.error(err_msg)
            raise Exception(err_msg)
        for node_info in ret_data:
            node_status = node_info["status"]
            if node_status != 0:
                err_msg = "server(%s) status(%s) is not normal"\
                          % (node_info["management_ip"], str(node_status))
                fail_results.append(err_msg)
        if fail_results:
            raise HCCIException(621005, str(fail_results))
