# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
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):
        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))

    def check_storage_node_connectivity(self):
        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))

    def procedure(self):
        logger.info("begin check storage node")
        self.check_storage_node_connectivity()
        logger.info("begin check rep node")
        self.check_rep_node_connectivity()
