#!/usr/bin/python

'''
Small script to parse /proc/bond for Nagios.
Written by Alexander Gedak

It searches for all bonding devices unter /proc/net/bonding/ and parser
their state under /sys/class/net/INTERFACE/carrier

If the state is not "1" it will exit with a warning state
'''


# Some settings
VERSION         = '0.2'
PROC_NET_BONDING       = '/proc/net/bonding/'
# Nagios Exit Codes:
STATE_OK, STATE_WARNING, STATE_CRITICAL, STATE_UNKNOWN\
                = 0, 1, 2, 3

# Import modules
from optparse import OptionParser
from sys import exit as sysexit
from os import path, listdir
from re import match

def print_and_exit(message, errorcode):
    ''' Prints message and exit with Errocode given'''
    print(message)
    sysexit(errorcode)

def get_bond_devices():
    '''
    Read all files under  /proc/net/bonding/ and put of all devices in an dictonary.
    Dictonary you get is Dict[DeviceName][Interface][Type] = Status
    Example:
            bond_devices['bond0']['eth0']['mii_status'] = 'up'
    Also read the status of /sys/class/net/INTERFACE/carrier and put it in
            bond_devices['bond0']['eth0']['carrier'] = '1'
    '''
    # Open file and read it.
    if path.isdir(PROC_NET_BONDING):
        devices = listdir(PROC_NET_BONDING)
    else:
        print_and_exit('No such directory %s.|' % (PROC_NET_BONDING), STATE_UNKNOWN)
    if devices == []:
        print_and_exit('No device found in %s.|' % (PROC_NET_BONDING), STATE_CRITICAL)
    bond_devices = {}
    for device in devices:
        bond_devices[device] = {}
        found_interface = False
        proc_file = open('%s/%s' % (PROC_NET_BONDING, device), 'r')
        lines = proc_file.read().split('\n')
        proc_file.close()
        for line in lines:
            if match('^Slave Interface:', line):
                found_interface = True
                interface_name = line.split(': ',1)[1]
                bond_devices[device][interface_name] = {}
                carrier_filename = '/sys/class/net/%s/carrier' % interface_name
                try:
                    carrier_file = open(carrier_filename, 'r')
                    carrier_state = carrier_file.readlines()[0].strip()
                    carrier_file.close()
                except:
                    carrier_state = ''
                continue
            if not found_interface:
                continue
            if match('^MII Status:.*', line):
                interface_state = line.split(': ',1)[1]
            # MII is allways the line after Slave Interface because of this we
            # can set it here.
            bond_devices[device][interface_name]['mii_status'] = interface_state
            bond_devices[device][interface_name]['name']       = interface_name
            bond_devices[device][interface_name]['carrier_state'] = carrier_state
            interface_name, interface_state, carrier_state = '', '', ''
            found_interface = False
    return bond_devices

def check_bond_device(bond_device):
    '''
    Check if the state of a given bond device is ok
    '''
    for interface in bond_device:
        carrier_state = bond_device[interface]['carrier_state']
        if carrier_state != '1':
            print_and_exit('Bonding: %s is in carrier_state "%s" expected was "1"' %(interface,  carrier_state), STATE_WARNING)

def parse_arguments():    
    '''
    Parse the arguments given from commandline.
    '''
    parser = OptionParser(\
                      version="%%prog Version %s" % (VERSION),\
                      usage='%prog [-d device_name]')
    parser.add_option('-d', \
                      '--device', \
                      action = 'append', \
                      dest='bond_name', \
                      type='str', \
                      help = 'bond devic name to check. \
                      Normaly all devices found will be checked', \
                      default = [])
    global options, args
    (options, args) = parser.parse_args()

def main():
    '''
    Here is where the pepper grows...
    '''
    # Parse arguments given
    parse_arguments()
    # First get all Devices:
    devices = get_bond_devices()
    # If we have no device given by commandline
    if options.bond_name != []:
        devices = ''
        for name in options.bond_name:
             devices += ' %s' %name
             if not devices.has_key(name):
                 print_and_exit(\
                 'No bond device "%s" found|' % (name), STATE_UNKNOWN)
             check_bond_device(devices[name])
        print_and_exit('These bonding devicese are ok:%s', STATE_OK, devices)
    else:
        for name in devices:
            check_bond_device(devices[name])
    print_and_exit('All bonding devices found are ok', STATE_OK)

main()
