#!/usr/bin/env python3
# -*- coding:utf-8 -*-

try:
    import sys
    import importlib

    importlib.reload(sys)
    import os
    import time
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.os.gsplatform import g_Platform
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

IFCONFIG_CMD = "export PATH=/bin:/usr/local/bin:/usr/bin:/sbin:/usr/sbin:$PATH && ifconfig"


class CheckNetWorkDrop(BaseItem):
    def __init__(self):
        super(CheckNetWorkDrop, self).__init__(self.__class__.__name__)

    def getPackage(self, sshIp, NetWorkNum):
        if (g_Platform.isPlatFormEulerOSOrRHEL7X()):
            if (os.getuid() == 0):
                packageCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH; 
                ssh %s \\"%s %s|grep packets|grep RX\\" """ % (
                    sshIp, IFCONFIG_CMD, NetWorkNum)
            else:
                packageCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH; 
                ssh %s "%s %s|grep packets|grep RX" """ % (
                    sshIp, IFCONFIG_CMD, NetWorkNum)
        else:
            if (os.getuid() == 0):
                packageCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                ssh %s \\"%s %s|grep dropped|grep RX\\" """ % (
                    sshIp, IFCONFIG_CMD, NetWorkNum)
            else:
                packageCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                ssh %s "%s %s|grep dropped|grep RX" """ % (
                    sshIp, IFCONFIG_CMD, NetWorkNum)
        output = SharedFuncs.runShellCmd(packageCmd1, self.user)
        if (g_Platform.isPlatFormEulerOSOrRHEL7X()):
            package = output.split('\n')[-1].strip().split()[2]
        else:
            package = output.split('\n')[-1].split(":")[1].strip().split()[0]

        if (os.getuid() == 0):
            dropCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;ssh %s \\"%s %s|grep dropped|grep RX\\" """ % (
                sshIp, IFCONFIG_CMD, NetWorkNum)
        else:
            dropCmd1 = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH; ssh %s "%s %s|grep dropped|grep RX" """ % (
                sshIp, IFCONFIG_CMD, NetWorkNum)
        output = SharedFuncs.runShellCmd(dropCmd1, self.user)
        if (g_Platform.isPlatFormEulerOSOrRHEL7X()):
            drop = output.split('\n')[-1].strip().split()[4]
        else:
            drop = output.split('\n')[-1].split(":")[3].strip().split()[0]
        return (package, drop)

    def doCheck(self):
        """
        function: Check NetWork care package drop rate in 1 minute
        """
        ipMap = {}
        netWorkInfo = {}
        for nodeInfo in self.cluster.dbNodes:
            ipMap[nodeInfo.sshIps[0]] = nodeInfo.backIps[0]
        for sshIp in ipMap.keys():
            backIp = ipMap[sshIp]
            # get remote IP network care number
            if (g_Platform.isPlatFormEulerOSOrRHEL7X()):
                if (os.getuid() == 0):
                    cmd = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                    ssh %s \\"%s\\"|grep -B 5 \\"%s\\"|grep \\"RUNNING\\" """ % (sshIp, IFCONFIG_CMD, backIp)
                else:
                    cmd = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                    ssh %s "%s"|grep -B 5 "%s"|grep "RUNNING" """ % (sshIp, IFCONFIG_CMD, backIp)
            else:
                if (os.getuid() == 0):
                    cmd = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                    ssh %s \\"%s\\"|grep -B 5 \\"%s\\"|grep \\"Link encap\\" """ \
                          % (sshIp, IFCONFIG_CMD, backIp)
                else:
                    cmd = """export LD_LIBRARY_PATH=/lib64:$LD_LIBRARY_PATH;
                    ssh %s "%s"|grep -B 5 "%s"|grep "Link encap" """ % (sshIp, IFCONFIG_CMD, backIp)
            output = SharedFuncs.runShellCmd(cmd, self.user)
            if (g_Platform.isPlatFormEulerOSOrRHEL7X()):
                NetWorkNum = output.split('\n')[-1].split()[0].split(':')[0]
            else:
                NetWorkNum = output.split('\n')[-1].strip().split()[0]
            package_begin, drop_begin = self.getPackage(sshIp, NetWorkNum)
            netWorkInfo[backIp] = [NetWorkNum, package_begin, drop_begin, "", ""]
        time.sleep(60)

        for sshIp in ipMap.keys():
            backIp = ipMap[sshIp]
            package_end, drop_end = self.getPackage(sshIp, netWorkInfo[backIp][0])
            netWorkInfo[backIp][3] = package_end
            netWorkInfo[backIp][4] = drop_end

        flag = True
        self.result.raw = ""
        resultStr = ""
        for ip in netWorkInfo.keys():
            packageSum = int(netWorkInfo[ip][3]) - int(netWorkInfo[ip][1])
            dropSum = int(netWorkInfo[ip][4]) - int(netWorkInfo[ip][2])
            if packageSum != 0:
                dropRate = float(dropSum) / packageSum
                if dropRate > 0.01:
                    flag = False
                    resultStr = "%s\nAddress %s %s communication packet loss rate of %.2f%%, more than 1%%." \
                                % (resultStr, ip, netWorkInfo[ip][0], dropRate * 100)
                    self.result.raw = "%s\n %s %s %s %s %.2f%%" % (self.result.raw, ip, netWorkInfo[ip][0], dropSum,
                                                                   packageSum, dropRate * 100)
            else:
                flag = False
                resultStr = "Can not divide by zero."
        if flag:
            self.result.rst = ResultStatus.OK
            self.result.val = "All IP communications are stable."
        else:
            self.result.rst = ResultStatus.NG
            self.result.val = resultStr
