#!/usr/bin/env python

# Script to check if the MLAG-peer is up
# Written by <tjerkjan.vonk@eu.equinix.com>, (c) 2015

from optparse import OptionParser
from jsonrpclib import Server
import sys

parser = OptionParser()
parser.add_option("-H", "--hostname", dest="hostname")
parser.add_option("-u", "--username", dest="username")
parser.add_option("-p", "--password", dest="password")
(options, args) = parser.parse_args()

if (not options.hostname or not options.username or not options.password):
    parser.print_usage()
    sys.exit(3)


status = {}

try:
    switch = Server( 'https://%s:%s@%s/command-api' %
		   ( options.username, options.password, options.hostname ) )
    response = switch.runCmds( 1, [ 'show mlag' ] )

    if response[0]['state'] == 'active':
	status['code'] = 0
	status['message'] = "domain %s connected with %s, with %s ports Active-full" % (response[0]['domainId'], response[0]['peerAddress'], response[0]['mlagPorts']['Active-full'])
    else:
        status['code'] = 2
        status['message'] = "MLAG state is: %s" % response[0]['state']
        raise Exception
    
    if response[0]['mlagPorts']['Active-partial'] != 0:
	interfaces = switch.runCmds( 1, [ 'show mlag interfaces' ] )
	
	fault = []
	for interface in interfaces[0]['interfaces']:
	    iface = interfaces[0]['interfaces'][interface]
 	    if iface['status'] != 'active-full':
		fault.append("%s is %s (local %s, remote %s)" % (interface, iface['status'], iface['localInterfaceStatus'], iface['peerInterfaceStatus']))
        status['code'] = 2
        status['message'] = "Faulty mlags: %s" % ", ".join(fault)
        raise Exception

    if response[0]['mlagPorts']['Disabled'] != 0:
	status['code'] = 1
	status['message'] = "Some mlag-interfaces are in Disabled state"
	raise Exception

    if response[0]['mlagPorts']['Inactive'] != 0:
	status['code'] = 1
	status['message'] = "Some mlag-interfaces are in Inactive state"
	raise Exception

    if response[0]['mlagPorts']['Configured'] != 0:
	status['code'] = 1
	status['message'] = "Some mlag-interfaces are in Configured state"
	raise Exception
    
except Exception, e:
    if not status:
        status['code'] = 1
        status['message'] = 'Unknown exception: %s' % e

if status['code'] == 0:
    print "OK",
elif status['code'] == 1:
    print "WARN",
elif status['code'] == 2:
    print "CRIT",
else:
    status['code'] = 2
    print "Something went horribly wrong"
    sys.exit(2)
print " %s" % status['message']
sys.exit(status['code'])
    

