def table_grep(table, search_string):
    for entry in table:
        for mibO,value in entry:
            if value == search_string:
                print 'OK - string: ' + search_string + ' found at: ' + str(mibO)
                huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
                exit(huji_cs_nagios.exit_code)
    print 'Critical - string: ' + search_string + ' not found!'
    huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    exit(huji_cs_nagios.exit_code) 
def table_grep(table, search_string):
    for entry in table:
        for mibO, value in entry:
            if value == search_string:
                print 'OK - string: ' + search_string + ' found at: ' + str(
                    mibO)
                huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
                exit(huji_cs_nagios.exit_code)
    print 'Critical - string: ' + search_string + ' not found!'
    huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    exit(huji_cs_nagios.exit_code)
def cpuCheck():
    try:
        result = snmpGetter(oid_cpu)
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return

    thresholdCheck(result[0][1])
        
    huji_cs_nagios.string_results += ['CPU usage on {}: {}'.format(snmp_host, 
                                                                   result[0][1])]

    pData = {'cur': result[0][1], 'w': xstr(args.warn), 'c': xstr(args.crit)}
    huji_cs_nagios.string_perfdata += ['cpu={cur};{w};{c};0;100'.format(**pData)]
def nfsiopsCheck():
    '''Check NFS IOops/second

    Function reads 2 samples about one second apart of iocount + timestamp and 
    calculates NFS IOops/second
    '''
    oids = [oid_uptime, oid_nfsops]
    samples = []
    try:
        samples.append(snmpGetter(*oids))
        time.sleep(1)
        samples.append(snmpGetter(*oids))
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return

    nfsops = []
    timestamps = []

    for sample in samples:
        for name, val in sample:
            if str(name) == oid_nfsops:
                nfsops.append(val)
            else:
                timestamps.append(val)

    nfsops = ((nfsops[1] - nfsops[0]) /
              (int(timestamps[1] - timestamps[0]) / 100))

    thresholdCheck(nfsops)

    huji_cs_nagios.string_results += [
        'NfsOps/Sec on {} is: {}'.format(snmp_host, nfsops)
    ]

    perfdata = {
        'type': 'nfsops/sec',
        'val': nfsops,
        'w': xstr(args.warn),
        'c': xstr(args.crit),
        'min': 0,
        'max': ''
    }

    huji_cs_nagios.string_perfdata += [
        '{type}={val};{w};{c};{min};{max}'.format(**perfdata)
    ]
def cpuCheck():
    try:
        result = snmpGetter(oid_cpu)
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return

    thresholdCheck(result[0][1])

    huji_cs_nagios.string_results += [
        'CPU usage on {}: {}'.format(snmp_host, result[0][1])
    ]

    pData = {'cur': result[0][1], 'w': xstr(args.warn), 'c': xstr(args.crit)}
    huji_cs_nagios.string_perfdata += [
        'cpu={cur};{w};{c};0;100'.format(**pData)
    ]
def nfsiopsCheck():
    '''Check NFS IOops/second

    Function reads 2 samples about one second apart of iocount + timestamp and 
    calculates NFS IOops/second
    '''
    oids = [
        oid_uptime,
        oid_nfsops
    ]
    samples = []
    try:
        samples.append(snmpGetter(*oids))
        time.sleep(1)
        samples.append(snmpGetter(*oids))
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return        

    nfsops = []
    timestamps = []

    for sample in samples:
        for name, val in sample:
            if str(name) == oid_nfsops:
                nfsops.append(val)
            else:
                timestamps.append(val)
        
    nfsops = ((nfsops[1] - nfsops[0]) / 
               (int(timestamps[1] - timestamps[0]) / 100))

    thresholdCheck(nfsops)
    
    huji_cs_nagios.string_results += ['NfsOps/Sec on {} is: {}'.format(snmp_host,
                                                                       nfsops)]

    perfdata = {'type': 'nfsops/sec', 'val': nfsops, 'w': xstr(args.warn), 
                'c': xstr(args.crit), 'min': 0, 'max': '' }

    huji_cs_nagios.string_perfdata += ['{type}={val};{w};{c};{min};{max}'.format(
        **perfdata)]
def check_procs(host):
    process_list = ["nfs", "mountd", "portmapper", "nlockmgr"]

    rpcinfo_output = check_output(["rpcinfo", "-p", host])

    for process in process_list:
        if(rpcinfo_output.find(process) == -1):
            huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
            huji_cs_nagios.string_results += ['{}: {} not found in RPC'.format(
                'process', process
            )]

    for process in process_list:
        print process
        call(["rpcinfo", "-u", host, process])
        print "tcp"
        call(["rpcinfo", "-t", host, process])

    huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
    if(huji_cs_nagios.exit_code == huji_cs_nagios.exit_codes['ok']):
        huji_cs_nagios.string_results += ['All processes required for NFS found']
def verify_levels(level, warn, crit):
    if level >= crit:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    elif level >= warn:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['warning'])
    else:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
def check_procs(host):
    process_list = ["nfs", "mountd", "portmapper", "nlockmgr"]

    rpcinfo_output = check_output(["rpcinfo", "-p", host])

    for process in process_list:
        if (rpcinfo_output.find(process) == -1):
            huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
            huji_cs_nagios.string_results += [
                '{}: {} not found in RPC'.format('process', process)
            ]

    for process in process_list:
        print process
        call(["rpcinfo", "-u", host, process])
        print "tcp"
        call(["rpcinfo", "-t", host, process])

    huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
    if (huji_cs_nagios.exit_code == huji_cs_nagios.exit_codes['ok']):
        huji_cs_nagios.string_results += [
            'All processes required for NFS found'
        ]
def psuCheck():
    try:
        result = snmpGetter(oid_failed_psu)
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return

    huji_cs_nagios.string_results += ['Failed PSUs: {}'.format(result[0][1])]
    if result[0][1] > 0:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    else:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
def psuCheck():
    try:
        result = snmpGetter(oid_failed_psu)
    except Exception as e:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        print e
        return

    huji_cs_nagios.string_results += ['Failed PSUs: {}'.format(result[0][1])]
    if result[0][1] > 0:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    else:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
def thresholdCheck(var):
    """Check whether provided value is within threshold

    Currently this function only check that the value doesn't exceed a 
    threshold, to be truely handling thresholds the way nagios likes it it
    should be checking being inside a range.
    """
    global args
    if args.crit != None and var >= args.crit:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    elif args.warn != None and var >= args.warn:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['warning'])
    else:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
def thresholdCheck(var):
    """Check whether provided value is within threshold

    Currently this function only check that the value doesn't exceed a 
    threshold, to be truely handling thresholds the way nagios likes it it
    should be checking being inside a range.
    """
    global args
    if args.crit != None and var >= args.crit:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['critical'])
    elif args.warn != None and var >= args.warn:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['warning'])
    else:
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['ok'])
if __name__ == "__main__":
    parser = argparse.ArgumentParser(__file__)

    parser.add_argument('-H', '--host', help = 'Hostname or IP address, if no ' +
                        'other arguments are specified all available info ' +
                        'will be printed', dest = 'snmp_host', required = True)
    parser.add_argument('-p', '--port', dest = 'snmp_port', default = 161,
                        help = 'SNMP Port, default 161')
    parser.add_argument('-C', help='SNMP community read string', 
                        default='public', dest='snmp_comm')
    parser.add_argument('-v', dest = 'snmp_vers', default = '2c',
                        help = 'SNMP version')
    parser.add_argument('-s', '--string',  help = 'Process name or string that '+
                        'needs to be present in the queried SNMP table.',
                        dest = 'search_string', required = True)
    parser.add_argument('-O', '--table-oid', dest = 'oids', nargs = '+',
                        help = 'List of OIDs of different tables to be searched.',
                        required = True)
    args = parser.parse_args()

    try:
        res = snmpWalk(args.snmp_host, args.snmp_port, 
                       snmpCreateAuthData(args.snmp_vers, args.snmp_comm), 
                       *args.oids)
    except Exception as e:
        print "UNKNOWN: " + str(e)
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        exit(huji_cs_nagios.exit_code)

    table_grep(res, args.search_string)
                        dest='snmp_comm')
    parser.add_argument('-v',
                        dest='snmp_vers',
                        default='2c',
                        help='SNMP version')
    parser.add_argument('-s',
                        '--string',
                        help='Process name or string that ' +
                        'needs to be present in the queried SNMP table.',
                        dest='search_string',
                        required=True)
    parser.add_argument(
        '-O',
        '--table-oid',
        dest='oids',
        nargs='+',
        help='List of OIDs of different tables to be searched.',
        required=True)
    args = parser.parse_args()

    try:
        res = snmpWalk(args.snmp_host, args.snmp_port,
                       snmpCreateAuthData(args.snmp_vers, args.snmp_comm),
                       *args.oids)
    except Exception as e:
        print "UNKNOWN: " + str(e)
        huji_cs_nagios.set_exit(huji_cs_nagios.exit_codes['unknown'])
        exit(huji_cs_nagios.exit_code)

    table_grep(res, args.search_string)