#!/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 Exception as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


class CheckSlowDisk(BaseItem):
    def __init__(self):
        super(CheckSlowDisk, self).__init__(self.__class__.__name__)
        self.max = None
        self.high = None

    def preCheck(self):
        # check the threshold was set correctly
        if (not self.threshold.__contains__('max')
                or not self.threshold.__contains__('high')):
            raise Exception("threshold can not be empty")
        if (not self.threshold['max'].isdigit() or not self.threshold['high'].isdigit()):
            raise Exception("The threshold max and high must be integer.")
        self.max = float(self.threshold['max'])
        self.high = float(self.threshold['high'])

    def doCheck(self):
        #Perform 60-pass disk data collection
        dic = {}
        slowDiskList = []
        cmd = """for varible1 in {1..30};
         do iostat -d -x -k 1 1 | grep -E -v "Linux|Device"|awk 'NF'|awk '{print $1,$(NF-1)}'; sleep 1;
         done"""
        output = SharedFuncs.runShellCmd(cmd)
        for line in output.splitlines():
            diskname = line.split()[0]
            svctmValue = line.split()[1]
            if(diskname in dic.keys()):
                diskList = dic[diskname]
                diskList.append(float(svctmValue))
                dic[diskname] = diskList
            else:
                dic[diskname] = [float(svctmValue)]
        for diskname, svctmValues in dic.items():
            diskList = sorted(svctmValues)
            if(diskList[-1] > self.max and diskList[-10] > self.high):
                slowDiskList.append(diskname)
        if(slowDiskList):
            self.result.rst = ResultStatus.NG
            self.result.val = "Slow Disk Found:\n%s" % ("\n".join(slowDiskList))
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "No Slow Disk Found"
