# -*- coding: utf-8 -*-
import traceback

import utils.common.log as logger
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.exception import HCCIException
from utils.business.vm_util import can_vm_pinged_to


class StorageNodeBmcIpConnectionCheck(object):
    """
    存储节点BMC IP连通性检查
    """

    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()

    def check_rep_node_connectivity(self):
        try:
            logger.info("begin check rep node")
            component = "rep"
            node_info = self.db.get_install_os_list_info(self.pod_id, component=component)
            node_bmc_ip_list = [x["bmc_ip"] for x in node_info if component in x["deploy_component"]]
            if len(node_bmc_ip_list) == 0:
                logger.error("no rep node to check")
            else:
                logger.info("rep node info:{}".format(node_bmc_ip_list))
                for temp in node_bmc_ip_list:
                    if not can_vm_pinged_to(temp):
                        raise HCCIException("113008", str(temp))
        except HCCIException as e1:
            logger.error(traceback.format_exc())
            raise e1
        except Exception as e2:
            logger.error(traceback.format_exc())
            raise e2
        return True, None

    def check_storage_node_connectivity(self):
        try:
            logger.info("begin check storage node")
            component = "osd"
            node_info = self.db.get_install_os_list_info(self.pod_id, component=component)
            node_bmc_ip_list = [x["bmc_ip"] for x in node_info]
            if len(node_bmc_ip_list) == 0:
                logger.error("no osd node to check")
            else:
                logger.info("osd node info:{}".format(node_bmc_ip_list))
                for temp in node_bmc_ip_list:
                    if not can_vm_pinged_to(temp):
                        raise HCCIException("113008", str(temp))
        except HCCIException as e1:
            logger.error(traceback.format_exc())
            raise e1
        except Exception as e2:
            logger.error(traceback.format_exc())
            raise e2
        return True, None

    def procedure(self):
        try:
            self.check_storage_node_connectivity()
            self.check_rep_node_connectivity()
        except HCCIException as e1:
            logger.error(traceback.format_exc())
            raise e1
        except Exception as e2:
            logger.error(traceback.format_exc())
            raise e2
        return True, None
