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


try:
    import sys
    import importlib

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


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

    def doCheck(self):
        flag = "Normal"
        resultStr = ""
        pathList = []
        diskList = []
        if not self.cluster:
            self.result.rst = ResultStatus.NG
            self.result.val = "The datanode information is none."
            return

        for inst in self.cluster.getDbNodeByName(self.host).datanodes:
            pathList.append(inst.datadir)
        cnInstList = self.cluster.getDbNodeByName(self.host).coordinators
        if cnInstList:
            pathList.append(cnInstList[0].datadir)
            tblspcDir = os.path.join(cnInstList[0].datadir, 'pg_tblspc')
            tblspcList = os.listdir(tblspcDir)
            if tblspcList:
                for tblspc in tblspcList:
                    tblspcPath = os.path.join(tblspcDir, tblspc)
                    if os.path.islink(tblspcPath):
                        pathList.append(os.path.realpath(tblspcPath))

        for path in pathList:
            diskName = g_disk.getMountPathByDataDir(path)
            if diskName in diskList:
                continue
            rateNum = round(g_disk.getDiskSpaceUsage(path), 2)
            self.result.raw = "%s[%s] space usage: %s%%\n" % (self.result.raw, path, rateNum)
            diskList.append(diskName)
            if rateNum > int(self.thresholdDn):
                resultStr = "%sPath(%s) space usage(%d%%)     " \
                             "Abnormal reason: The usage of the device disk space cannot be greater than %s%%.\n" \
                             % (resultStr, path, rateNum, self.thresholdDn)
                flag = "Error"
            # Check inode usage
            status, result = SharedFuncs.checkDiskInde(path, self.thresholdDn)
            if not status:
                flag = "Error"
                resultStr += result
        self.result.val = resultStr
        if flag == "Normal":
            self.result.rst = ResultStatus.OK
            self.result.val = "All disk space are sufficient.\n"
        else:
            self.result.rst = ResultStatus.NG
