#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import time
    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))


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

    def doCheck(self):
        tcpSend = "cat /proc/net/snmp | grep Tcp | grep -v CurrEsta | awk '{print $12}'"
        tcpResend = "cat /proc/net/snmp|grep Tcp|grep -v CurrEsta|awk '{print $13}'"
        send1 = SharedFuncs.runShellCmd(tcpSend)
        resend1 = SharedFuncs.runShellCmd(tcpResend)
        time.sleep(1)
        send2 = SharedFuncs.runShellCmd(tcpSend)
        resend2 = SharedFuncs.runShellCmd(tcpResend)
        try:
            retransRate = (float(resend2) - float(resend1)) / (float(send2) - float(send1))
        except Exception as e:
            self.result.rst = ResultStatus.NG
            self.result.val = "Failed to get TCP retransmission rate.Error: %s" % e
            return
        if retransRate > 0.001:
            self.result.rst = ResultStatus.WARNING
            self.result.val = "TCP retransmission rate is %f more than 0.001." % retransRate
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "TCP retransmission rate is %f." % retransRate
