#!/usr/bin/env python3
# coding: UTF-8
try:
    import sys
    import importlib
    importlib.reload(sys)
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

# master
MASTER_INSTANCE = 0
# standby
STANDBY_INSTANCE = 1


class CheckFilehandle(BaseItem):
    def __init__(self):
        super(CheckFilehandle, self).__init__(self.__class__.__name__)
        self.Threshold_Warning = None

    def preCheck(self):
        super(CheckFilehandle, self).preCheck()
        if (not self.threshold.__contains__('Threshold_Warning')):
            raise Exception("The  Threshold_Warning can not be empty.")
        if (not self.threshold['Threshold_Warning'].isdigit()):
            raise Exception("The  Threshold_Warning must be integer.")
        self.Threshold_Warning = int(self.threshold['Threshold_Warning'])

    def getFileHandle(self, dnList):
        handle = {}
        for dn in dnList:
            getpidcmd = "ps -ef| grep %s|grep -v 'grep'|awk '{print $2}'" % dn.datadir
            pid = SharedFuncs.runShellCmd(getpidcmd)
            getfilehander = "lsof | grep %s|wc -l" % pid
            filehander = SharedFuncs.runShellCmd(getfilehander)
            instanceName = "dn_%s" % (dn.instanceId)
            if(not filehander.isdigit()):
                num = filehander.splitlines()
                filehander = num[-1]
            if (not filehander.isdigit()):
                raise Exception("Failed to get file handler of process %s by use cmd %s" % (pid, getfilehander))
            handle[instanceName] = filehander
        return handle

    def doCheck(self):
        masterDNs = []
        slaveDNs = []
        masterDNhander = {}
        salveDNhander = {}
        overvalueDNs = []
        overmasterDNs = []
        flag = False
        nodeInfo = self.cluster.getDbNodeByName(self.host)
        for DnInstance in nodeInfo.datanodes:
            if (DnInstance.instanceType == MASTER_INSTANCE):
                masterDNs.append(DnInstance)
            elif(DnInstance.instanceType == STANDBY_INSTANCE):
                slaveDNs.append(DnInstance)
        masterDNhander = self.getFileHandle(masterDNs)
        salveDNhander = self.getFileHandle(slaveDNs)
        for key, value in masterDNhander.items():
            if(int(value) > self.Threshold_Warning):
                overvalueDNs.append(key)
        for key, value in salveDNhander.items():
            if(int(value) > self.Threshold_Warning):
                overvalueDNs.append(key)
        for key, value in salveDNhander.items():
            for _, mastervalue in masterDNhander.items():
                if(int(value) > int(mastervalue)):
                    overmasterDNs.append(key)
                    flag = True
        if(overvalueDNs and flag):
            self.result.val = "Some slave dn open more file hander than master dn %s;" \
                              "Some gaussdb process open file handler over %s:\n%s"\
                              % ("\n".join(overmasterDNs), self.Threshold_Warning, "\n".join(overvalueDNs))
            self.result.rst = ResultStatus.WARNING
        elif(overvalueDNs):
            self.result.val = "Some gaussdb process open file handler over %s:\n%s"\
                              % (self.Threshold_Warning, "\n".join(overvalueDNs))
            self.result.rst = ResultStatus.WARNING
        elif(flag):
            self.result.val = "There is some slave dn open more file hander than master dn %s"\
                              % "\n".join(overmasterDNs)
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.val = "File hander check pass"
            self.result.rst = ResultStatus.OK
