# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback
import utils.common.log as logger
from utils.common.message import Message
from utils.common.fic_base import TestCase
from utils.common.exception import HCCIException
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class SPDKCheck(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(SPDKCheck, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.fs_args = fs_args
        self.more_args = kwargs
        self.update_pwd = self.fs_args['dm_update_pwd']
        self.opr = DeployOperate(self.fs_args)

    def procedure(self):
        try:
            self.main()
        except HCCIException as e:
            logger.error(traceback.format_exc())
            return Message(500, e)
        except Exception as e:
            return Message(500, HCCIException(626110, str(e)))
        finally:
                self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.fs_args['dm_update_pwd'])
        return Message()

    def main(self):
        logger.info("Start to check spdk")
        status_code, error_code, error_des = self.opr.login(DeployConstant.DM_LOGIN_USER, self.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)

        osd_ip_list = [osd.get('om_ip') for osd in self.fs_args['osd_list']]
        logger.info("Checking spdk on node[%s]" % osd_ip_list)
        resp_status = self.opr.check_spdk_switch(osd_ip_list)
        check_code, detail_data = resp_status.get_spdk_check_data()
        if check_code != 0 and check_code != 401 and check_code != 404:
            logger.info("Failed to check SPDK, check code:%s, detail data:%s" % (check_code, detail_data))
            raise HCCIException(626111, osd_ip_list, detail_data)
        logger.info("SPDK check finish")
