PEP8 cleanup

This commit is contained in:
Pall Sigurdsson 2013-09-02 15:14:07 +00:00
parent 39f2413957
commit 9907356c39
1 changed files with 257 additions and 209 deletions

View File

@ -16,50 +16,45 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# About this script # About this script
# #
# This script will check the status of all EVA arrays via the sssu binary. # This script will check the status of all EVA arrays via the sssu binary.
# You will need the sssu binary in path (/usr/bin/sssu is a good place) # You will need the sssu binary in path (/usr/bin/sssu is a good place)
# If you do not have sssu, check your commandview CD, it should have both # If you do not have sssu, check your commandview CD, it should have both
# binaries for Windows and Linux # binaries for Windows and Linux
# Some Defaults # Some Defaults
show_perfdata = True show_perfdata = True
show_longserviceoutput = True show_longserviceoutput = True
debugging = False debugging = False
# check_eva defaults # check_eva defaults
hostname="localhost" hostname = "localhost"
username="eva" username = "eva"
password="eva1234" password = "eva1234"
mode="check_systems" mode = "check_systems"
path='' path = ''
nagios_server = "94.142.154.10" nagios_server = "94.142.154.10"
nagios_port = 80 nagios_port = 80
nagios_myhostname = None nagios_myhostname = None
do_phone_home = False do_phone_home = False
escape_newlines = False escape_newlines = False
check_system = None # By default check all systems check_system = None # By default check all systems
proxyserver = None proxyserver = None
server_side_troubleshooting = False # set to true, if you do not have sssu binary handy # set to true, if you do not have sssu binary handy
server_side_troubleshooting = False
# No real need to change anything below here # No real need to change anything below here
version="1.0" version = "1.0"
ok=0 ok = 0
warning=1 warning = 1
critical=2 critical = 2
unknown=3 unknown = 3
not_present = -1 not_present = -1
state = {} state = {}
state[not_present] = "Not Present" state[not_present] = "Not Present"
state[ok] = "OK" state[ok] = "OK"
@ -67,18 +62,20 @@ state[warning] = "Warning"
state[critical] = "Critical" state[critical] = "Critical"
state[unknown] = "Unknown" state[unknown] = "Unknown"
longserviceoutput="\n" longserviceoutput = "\n"
perfdata="" perfdata = ""
valid_modes = ( "check_systems", "check_controllers", "check_diskgroups","check_disks", "check_diskshelfs", "check_diskshelves") valid_modes = ("check_systems", "check_controllers", "check_diskgroups",
"check_disks", "check_diskshelfs", "check_diskshelves")
from sys import exit from sys import exit
from sys import argv from sys import argv
from os import getenv,putenv,environ from os import getenv, putenv, environ
import subprocess import subprocess
import xmlrpclib,httplib import xmlrpclib
import httplib
import socket import socket
socket.setdefaulttimeout(5) socket.setdefaulttimeout(5)
def print_help(): def print_help():
@ -87,18 +84,18 @@ def print_help():
print "" print ""
print "Usage: %s [OPTIONS]" % argv[0] print "Usage: %s [OPTIONS]" % argv[0]
print "OPTIONS:" print "OPTIONS:"
print " [--host <host>]" print " [--host <host>]"
print " [--username <user>]" print " [--username <user>]"
print " [--password <password]" print " [--password <password]"
print " [--path </path/to/sssu>]" print " [--path </path/to/sssu>]"
print " [--mode <mode>] " print " [--mode <mode>] "
print " [--test]" print " [--test]"
print " [--debug]" print " [--debug]"
print " [--help]" print " [--help]"
print "" print ""
print " Valid modes are: %s" % ', '.join(valid_modes) print " Valid modes are: %s" % ', '.join(valid_modes)
print "" print ""
print "Example: %s --host commandview.example.net --username eva --password myPassword --mode check_systems" % (argv[0]) print "Example: %s --host commandview.example.net --username eva --password myPassword --mode check_systems" % (argv[0])
def error(errortext): def error(errortext):
@ -107,34 +104,35 @@ def error(errortext):
print "* Error: %s" % errortext print "* Error: %s" % errortext
exit(unknown) exit(unknown)
def debug( debugtext ):
def debug(debugtext):
global debugging global debugging
if debugging: if debugging:
print debugtext print debugtext
# parse arguments # parse arguments
arguments=argv[1:] arguments = argv[1:]
while len(arguments) > 0: while len(arguments) > 0:
arg=arguments.pop(0) arg = arguments.pop(0)
if arg == 'invalid': if arg == 'invalid':
pass pass
elif arg == '-H' or arg == '--host': elif arg == '-H' or arg == '--host':
hostname=arguments.pop(0) hostname = arguments.pop(0)
elif arg == '-U' or arg == '--username': elif arg == '-U' or arg == '--username':
username=arguments.pop(0) username = arguments.pop(0)
elif arg == '-P' or arg == '--password': elif arg == '-P' or arg == '--password':
password = arguments.pop(0) password = arguments.pop(0)
elif arg == '-T' or arg == '--test': elif arg == '-T' or arg == '--test':
testmode=1 testmode = 1
elif arg == '--path': elif arg == '--path':
path = arguments.pop(0) + '/' path = arguments.pop(0) + '/'
elif arg == '-M' or arg == '--mode': elif arg == '-M' or arg == '--mode':
mode=arguments.pop(0) mode = arguments.pop(0)
if mode not in valid_modes: if mode not in valid_modes:
error("Invalid --mode %s" % arg) error("Invalid --mode %s" % arg)
elif arg == '-d' or arg == '--debug': elif arg == '-d' or arg == '--debug':
debugging=True debugging = True
elif arg == '--longserviceoutput': elif arg == '--longserviceoutput':
show_longserviceoutput = True show_longserviceoutput = True
elif arg == '--no-longserviceoutput': elif arg == '--no-longserviceoutput':
@ -161,9 +159,7 @@ while len(arguments) > 0:
print_help() print_help()
exit(ok) exit(ok)
else: else:
error( "Invalid argument %s"% arg) error("Invalid argument %s" % arg)
subitems = {} subitems = {}
@ -177,29 +173,29 @@ subitems['bus'] = 'communicationbuses'
subitems['port'] = 'fibrechannelports' subitems['port'] = 'fibrechannelports'
def runCommand(command): def runCommand(command):
""" runCommand: Runs command from the shell prompt. Exit Nagios style if unsuccessful """ """ runCommand: Runs command from the shell prompt. Exit Nagios style if unsuccessful """
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE,) proc = subprocess.Popen(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)
stdout, stderr = proc.communicate('through stdin to stdout') stdout, stderr = proc.communicate('through stdin to stdout')
if proc.returncode > 0: if proc.returncode > 0:
print "Error %s: %s\n command was: '%s'" % (proc.returncode,stderr.strip(),command) print "Error %s: %s\n command was: '%s'" % (proc.returncode, stderr.strip(), command)
if proc.returncode == 127 or proc.returncode == 1: # File not found, lets print path # File not found, lets print path
path=getenv("PATH") if proc.returncode == 127 or proc.returncode == 1:
path = getenv("PATH")
print "Current Path: %s" % path print "Current Path: %s" % path
exit(unknown) exit(unknown)
else: else:
return stdout return stdout
def run_sssu(system=None, command="ls system full"): def run_sssu(system=None, command="ls system full"):
"""Runs the sssu command. This one is responsible for error checking from sssu""" """Runs the sssu command. This one is responsible for error checking from sssu"""
commands = [] commands = []
continue_on_error="set option on_error=continue" continue_on_error = "set option on_error=continue"
login="select manager %s USERNAME=%s PASSWORD=%s"%(hostname,username,password) login = "select manager %s USERNAME=%s PASSWORD=%s" % (
hostname, username, password)
commands.append(continue_on_error) commands.append(continue_on_error)
commands.append(login) commands.append(login)
@ -214,29 +210,36 @@ def run_sssu(system=None, command="ls system full"):
if server_side_troubleshooting == True: if server_side_troubleshooting == True:
commandstring = 'cat "debug/%s"' % command commandstring = 'cat "debug/%s"' % command
#print mystring # print mystring
#if command == "ls system full": # if command == "ls system full":
# output = runCommand("cat sssu.out") # output = runCommand("cat sssu.out")
#elif command == "ls disk_groups full": # elif command == "ls disk_groups full":
# output = runCommand("cat ls_disk*") # output = runCommand("cat ls_disk*")
#elif command == "ls controller full": # elif command == "ls controller full":
# output = runCommand("cat ls_controller") # output = runCommand("cat ls_controller")
#else: # else:
# print "What command is this?", command # print "What command is this?", command
# exit(unknown) # exit(unknown)
output = runCommand(commandstring) output = runCommand(commandstring)
debug( commandstring ) debug(commandstring)
output = output.split('\n') output = output.split('\n')
# Lets process the top few results from the sssu command. Make sure the results make sense # Lets process the top few results from the sssu command. Make sure the
# results make sense
error = 0 error = 0
if output.pop(0).strip() != '': error = 1 if output.pop(0).strip() != '':
if output.pop(0).strip() != '': error = 1 error = 1
if output.pop(0).strip() != 'SSSU for HP StorageWorks Command View EVA': error = 1 if output.pop(0).strip() != '':
if output.pop(0).strip().find('Version:') != 0: error=1 error = 1
if output.pop(0).strip().find('Build:') != 0: error=1 if output.pop(0).strip() != 'SSSU for HP StorageWorks Command View EVA':
if output.pop(0).strip().find('NoSystemSelected> ') != 0: error=1 error = 1
if output.pop(0).strip().find('Version:') != 0:
error = 1
if output.pop(0).strip().find('Build:') != 0:
error = 1
if output.pop(0).strip().find('NoSystemSelected> ') != 0:
error = 1
#if output.pop(0).strip() != '': error = 1 #if output.pop(0).strip() != '': error = 1
#if output.pop(0).strip().find('NoSystemSelected> ') != 0: error=1 #if output.pop(0).strip().find('NoSystemSelected> ') != 0: error=1
#if output.pop(0).strip() != '': error = 1 #if output.pop(0).strip() != '': error = 1
@ -246,7 +249,8 @@ def run_sssu(system=None, command="ls system full"):
if i.find('Error') > -1: if i.find('Error') > -1:
print "This is the command i was trying to execute: %s" % i print "This is the command i was trying to execute: %s" % i
error = 1 error = 1
if i.find('information:') > 0: break if i.find('information:') > 0:
break
if error > 0: if error > 0:
print "Error running the sssu command" print "Error running the sssu command"
print commandstring print commandstring
@ -261,11 +265,13 @@ def run_sssu(system=None, command="ls system full"):
tmp = line.split() tmp = line.split()
if len(tmp) == 0: if len(tmp) == 0:
if current_object: if current_object:
if not current_object['master'] in objects: objects.append( current_object['master'] ) if not current_object['master'] in objects:
objects.append(current_object['master'])
current_object = None current_object = None
continue continue
key = tmp[0].strip() key = tmp[0].strip()
if current_object and not current_object['master'] in objects: objects.append( current_object['master'] ) if current_object and not current_object['master'] in objects:
objects.append(current_object['master'])
if key == 'object': if key == 'object':
current_object = {} current_object = {}
current_object['master'] = current_object current_object['master'] = current_object
@ -273,7 +279,7 @@ def run_sssu(system=None, command="ls system full"):
current_object = current_object['master'] current_object = current_object['master']
if key == 'iomodules': if key == 'iomodules':
key = 'modules' key = 'modules'
#if key in subitems.values(): # if key in subitems.values():
# object['master'][key] = [] # object['master'][key] = []
if key in subitems.keys(): if key in subitems.keys():
mastergroup = subitems[key] mastergroup = subitems[key]
@ -285,13 +291,11 @@ def run_sssu(system=None, command="ls system full"):
current_object['master'][mastergroup] = [] current_object['master'][mastergroup] = []
current_object['master'][mastergroup].append(current_object) current_object['master'][mastergroup].append(current_object)
if line.find('.:') > 0: if line.find('.:') > 0:
# We work on first come, first serve basis, so if # We work on first come, first serve basis, so if
# we accidentally see same key again, we will ignore # we accidentally see same key again, we will ignore
if not current_object.has_key(key): if not current_object.has_key(key):
value = ' '.join( tmp[2:] ).strip() value = ' '.join(tmp[2:]).strip()
current_object[key] = value current_object[key] = value
# Check if we were instructed to check only one eva system # Check if we were instructed to check only one eva system
global check_system global check_system
@ -299,11 +303,12 @@ def run_sssu(system=None, command="ls system full"):
tmp_objects = [] tmp_objects = []
for i in objects: for i in objects:
if i['objectname'] == check_system: if i['objectname'] == check_system:
tmp_objects.append( i ) tmp_objects.append(i)
objects = tmp_objects objects = tmp_objects
return objects return objects
def end(summary,perfdata,longserviceoutput,nagios_state):
def end(summary, perfdata, longserviceoutput, nagios_state):
global show_longserviceoutput global show_longserviceoutput
global show_perfdata global show_perfdata
global nagios_server global nagios_server
@ -315,21 +320,21 @@ def end(summary,perfdata,longserviceoutput,nagios_state):
global escape_newlines global escape_newlines
global check_system global check_system
message = "%s - %s" % ( state[nagios_state], summary) message = "%s - %s" % (state[nagios_state], summary)
if show_perfdata: if show_perfdata:
message = "%s | %s" % ( message, perfdata) message = "%s | %s" % (message, perfdata)
if show_longserviceoutput: if show_longserviceoutput:
message = "%s\n%s" % ( message, longserviceoutput.strip()) message = "%s\n%s" % (message, longserviceoutput.strip())
if escape_newlines == True: if escape_newlines == True:
lines = message.split('\n') lines = message.split('\n')
message = '\\n'.join(lines) message = '\\n'.join(lines)
debug( "do_phone_home = %s" % do_phone_home) debug("do_phone_home = %s" % do_phone_home)
if do_phone_home == True: if do_phone_home == True:
try: try:
if nagios_myhostname is None: if nagios_myhostname is None:
if environ.has_key( 'HOSTNAME' ): if environ.has_key('HOSTNAME'):
nagios_myhostname = environ['HOSTNAME'] nagios_myhostname = environ['HOSTNAME']
elif environ.has_key( 'COMPUTERNAME' ): elif environ.has_key('COMPUTERNAME'):
nagios_myhostname = environ['COMPUTERNAME'] nagios_myhostname = environ['COMPUTERNAME']
else: else:
nagios_myhostname = hostname nagios_myhostname = hostname
@ -341,7 +346,7 @@ def end(summary,perfdata,longserviceoutput,nagios_state):
hostname=nagios_myhostname, hostname=nagios_myhostname,
servicename=mode, servicename=mode,
system=check_system system=check_system
) )
except Exception: except Exception:
pass pass
@ -349,41 +354,47 @@ def end(summary,perfdata,longserviceoutput,nagios_state):
raise raise
print message print message
exit(nagios_state) exit(nagios_state)
class ProxiedTransport(xmlrpclib.Transport): class ProxiedTransport(xmlrpclib.Transport):
def set_proxy(self, proxy): def set_proxy(self, proxy):
self.proxy = proxy self.proxy = proxy
def make_connection(self, host): def make_connection(self, host):
self.realhost = host self.realhost = host
h = httplib.HTTP(self.proxy) h = httplib.HTTP(self.proxy)
return h return h
def send_request(self, connection, handler, request_body): def send_request(self, connection, handler, request_body):
connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
def send_host(self, connection, host): def send_host(self, connection, host):
connection.putheader('Host', self.realhost) connection.putheader('Host', self.realhost)
def phone_home(nagios_server, nagios_port, status, message, hostname=None, servicename=None, system=None):
def phone_home(nagios_server,nagios_port, status, message, hostname=None, servicename=None,system=None):
"""phone_home: Sends results to remote nagios server via python xml-rpc""" """phone_home: Sends results to remote nagios server via python xml-rpc"""
debug("phoning home: %s" % servicename) debug("phoning home: %s" % servicename)
if system is not None: if system is not None:
servicename = str(servicename) + str(system) servicename = str(servicename) + str(system)
uri = "http://%s:%s" % (nagios_server,nagios_port) uri = "http://%s:%s" % (nagios_server, nagios_port)
global proxyserver global proxyserver
if proxyserver is not None: if proxyserver is not None:
p = ProxiedTransport() p = ProxiedTransport()
p.set_proxy(proxyserver) p.set_proxy(proxyserver)
s = xmlrpclib.Server( uri, transport=p ) s = xmlrpclib.Server(uri, transport=p)
else: else:
s = xmlrpclib.ServerProxy( uri ) s = xmlrpclib.ServerProxy(uri)
s.nagiosupdate(hostname, servicename, status, message) s.nagiosupdate(hostname, servicename, status, message)
return 0 return 0
def check_systems(): def check_systems():
summary="" summary = ""
perfdata="" perfdata = ""
#longserviceoutput="\n" # longserviceoutput="\n"
nagios_state = ok nagios_state = ok
objects = run_sssu() objects = run_sssu()
for i in objects: for i in objects:
@ -396,56 +407,66 @@ def check_systems():
summary += " %s=%s " % (name, operationalstate) summary += " %s=%s " % (name, operationalstate)
# Collect the performance data # Collect the performance data
interesting_perfdata = 'totalstoragespace|usedstoragespace|availablestoragespace' interesting_perfdata = 'totalstoragespace|usedstoragespace|availablestoragespace'
perfdata += get_perfdata(i, interesting_perfdata.split('|'), identifier="%s_" % name) perfdata += get_perfdata(
i, interesting_perfdata.split('|'), identifier="%s_" % name)
# Collect extra info for longserviceoutput # Collect extra info for longserviceoutput
longoutput("%s = %s (%s)\n" % ( i['objectname'], i['operationalstate'], i['operationalstatedetail']) ) longoutput("%s = %s (%s)\n" %
(i['objectname'], i['operationalstate'], i['operationalstatedetail']))
interesting_fields = 'licensestate|systemtype|firmwareversion|nscfwversion|totalstoragespace|usedstoragespace|availablestoragespace' interesting_fields = 'licensestate|systemtype|firmwareversion|nscfwversion|totalstoragespace|usedstoragespace|availablestoragespace'
for x in interesting_fields.split('|'): for x in interesting_fields.split('|'):
longoutput( "- %s = %s \n" %(x, i[x]) ) longoutput("- %s = %s \n" % (x, i[x]))
longoutput("\n") longoutput("\n")
end(summary,perfdata,longserviceoutput,nagios_state) end(summary, perfdata, longserviceoutput, nagios_state)
def get_perfdata(my_object, interesting_fields, identifier=""): def get_perfdata(my_object, interesting_fields, identifier=""):
perfdata = "" perfdata = ""
for i in interesting_fields: for i in interesting_fields:
if i == '': continue if i == '':
continue
perfdata += "'%s%s'=%s " % (identifier, i, my_object[i]) perfdata += "'%s%s'=%s " % (identifier, i, my_object[i])
return perfdata return perfdata
def add_perfdata(text): def add_perfdata(text):
global perfdata global perfdata
text = text.strip() text = text.strip()
perfdata += " %s " % text perfdata += " %s " % text
def longoutput(text): def longoutput(text):
global longserviceoutput global longserviceoutput
longserviceoutput = longserviceoutput + text longserviceoutput = longserviceoutput + text
def get_longserviceoutput(my_object, interesting_fields): def get_longserviceoutput(my_object, interesting_fields):
longserviceoutput = "" longserviceoutput = ""
for i in interesting_fields: for i in interesting_fields:
longserviceoutput += "%s = %s \n" % (i, my_object[i]) longserviceoutput += "%s = %s \n" % (i, my_object[i])
return longserviceoutput return longserviceoutput
def check_operationalstate(my_object, print_failed_objects=False,namefield='objectname',detailfield='operationalstatedetail',statefield='operationalstate',valid_states=None):
def check_operationalstate(my_object, print_failed_objects=False, namefield='objectname', detailfield='operationalstatedetail', statefield='operationalstate', valid_states=None):
if not valid_states: if not valid_states:
valid_states=['good'] valid_states = ['good']
if not my_object.has_key(detailfield): detailfield = statefield if not my_object.has_key(detailfield):
detailfield = statefield
if not my_object.has_key(statefield): if not my_object.has_key(statefield):
if print_failed_objects: if print_failed_objects:
longoutput("- Warning, %s does not have any '%s'" % ( my_object[namefield], statefield ) ) longoutput("- Warning, %s does not have any '%s'" %
(my_object[namefield], statefield))
return warning return warning
if my_object[statefield] not in valid_states: if my_object[statefield] not in valid_states:
if print_failed_objects: if print_failed_objects:
longoutput("- Warning, %s=%s (%s)\n" % ( my_object[namefield], my_object['operationalstate'], my_object[detailfield] )) longoutput("- Warning, %s=%s (%s)\n" %
(my_object[namefield], my_object['operationalstate'], my_object[detailfield]))
return warning return warning
debug( "OK, %s=%s (%s)\n" % ( my_object[namefield], my_object['operationalstate'], my_object[detailfield] ) ) debug("OK, %s=%s (%s)\n" %
(my_object[namefield], my_object['operationalstate'], my_object[detailfield]))
return ok return ok
def check_generic(command="ls disk full", namefield="objectname", perfdata_fields=None, longserviceoutputfields=None, detailedsummary=False):
def check_generic(command="ls disk full",namefield="objectname", perfdata_fields=None, longserviceoutputfields=None, detailedsummary=False):
if not perfdata_fields: if not perfdata_fields:
perfdata_fields = [] perfdata_fields = []
if not longserviceoutputfields: if not longserviceoutputfields:
@ -456,118 +477,132 @@ def check_generic(command="ls disk full",namefield="objectname", perfdata_fields
objects = [] objects = []
if command == 'ls system full': if command == 'ls system full':
objects = systems objects = systems
for i in systems: i['systemname'] = '' #i['objectname'] for i in systems:
i['systemname'] = '' # i['objectname']
else: else:
for i in systems: for i in systems:
result = run_sssu(system=i['objectname'], command=command) result = run_sssu(system=i['objectname'], command=command)
for x in result: for x in result:
x['systemname'] = i['objectname'] x['systemname'] = i['objectname']
objects.append( x ) objects.append(x)
summary = "%s objects found " % len(objects) summary = "%s objects found " % len(objects)
usedstoragespacegb=0 usedstoragespacegb = 0
occupancyalarmlvel=0 occupancyalarmlvel = 0
warninggb=0 warninggb = 0
for i in objects: for i in objects:
systemname = i['systemname'] systemname = i['systemname']
# Some versions of commandview use "objectname" instead of namefield # Some versions of commandview use "objectname" instead of namefield
if i.has_key( namefield ): if i.has_key(namefield):
objectname = i[namefield] objectname = i[namefield]
else: else:
objectname = i['objectname'] objectname = i['objectname']
# Some versions of CV also return garbage objects, luckily it is easy to find these # Some versions of CV also return garbage objects, luckily it is easy
# to find these
if i.has_key('objecttype') and i['objecttype'] == 'typenotset': if i.has_key('objecttype') and i['objecttype'] == 'typenotset':
longoutput("Object %s was skipped because objecttype == typenotset\n" % objectname ) longoutput(
"Object %s was skipped because objecttype == typenotset\n" % objectname)
continue continue
# Lets see if this object is working # Lets see if this object is working
nagios_state = max( check_operationalstate(i), nagios_state ) nagios_state = max(check_operationalstate(i), nagios_state)
# Lets add to the summary # Lets add to the summary
if i['operationalstate'] != 'good' or detailedsummary == True: if i['operationalstate'] != 'good' or detailedsummary == True:
summary += " %s/%s=%s " % (systemname, objectname, i['operationalstate']) summary += " %s/%s=%s " % (
systemname, objectname, i['operationalstate'])
# Lets get some perfdata # Lets get some perfdata
identifier = "%s/%s_" % (systemname,objectname) identifier = "%s/%s_" % (systemname, objectname)
i['identifier'] = identifier i['identifier'] = identifier
for field in perfdata_fields: for field in perfdata_fields:
if field == '': continue if field == '':
print perfdata_fields continue
add_perfdata( "'%s%s'=%s " % (identifier, field, i.get(field,None) )) add_perfdata("'%s%s'=%s " %
(identifier, field, i.get(field, None)))
# Disk group gets a special perfdata treatment # Disk group gets a special perfdata treatment
if command == "ls disk_group full": if command == "ls disk_group full":
totalstoragespacegb = float( i['totalstoragespacegb'] ) totalstoragespacegb = float(i['totalstoragespacegb'])
usedstoragespacegb = float ( i['usedstoragespacegb'] ) usedstoragespacegb = float(i['usedstoragespacegb'])
occupancyalarmlvel = float( i['occupancyalarmlevel'] ) occupancyalarmlvel = float(i['occupancyalarmlevel'])
warninggb = totalstoragespacegb * occupancyalarmlvel / 100 warninggb = totalstoragespacegb * occupancyalarmlvel / 100
add_perfdata( " '%sdiskusage'=%s;%s;%s "% (identifier, usedstoragespacegb,warninggb,totalstoragespacegb) ) add_perfdata(" '%sdiskusage'=%s;%s;%s " %
(identifier, usedstoragespacegb, warninggb, totalstoragespacegb))
# Long Serviceoutput # Long Serviceoutput
# There are usually to many disks for nagios to display. Skip. # There are usually to many disks for nagios to display. Skip.
if command != "ls disk full": if command != "ls disk full":
longoutput( "\n%s/%s = %s (%s)\n"%(systemname,objectname,i['operationalstate'], i['operationalstatedetail']) ) longoutput("\n%s/%s = %s (%s)\n" %
(systemname, objectname, i['operationalstate'], i['operationalstatedetail']))
# If diskgroup has a problem because it is over allocated. Lets inform about that # If diskgroup has a problem because it is over allocated. Lets inform
# about that
if command == "ls disk_group full" and usedstoragespacegb > warninggb: if command == "ls disk_group full" and usedstoragespacegb > warninggb:
longoutput("- %s - diskgroup usage is over %s%% threshold !\n" % (state[warning], occupancyalarmlvel) ) longoutput(
"- %s - diskgroup usage is over %s%% threshold !\n" %
(state[warning], occupancyalarmlvel))
# If a disk has a problem, lets display some extra info on it # If a disk has a problem, lets display some extra info on it
elif command == "ls disk full" and i['operationalstate'] != 'good': elif command == "ls disk full" and i['operationalstate'] != 'good':
longoutput( "Warning - %s=%s (%s)\n" % (i['diskname'], i['operationalstate'], i['operationalstatedetail'] )) longoutput("Warning - %s=%s (%s)\n" %
fields="modelnumber firmwareversion serialnumber failurepredicted diskdrivetype".split() (i['diskname'], i['operationalstate'], i['operationalstatedetail']))
fields = "modelnumber firmwareversion serialnumber failurepredicted diskdrivetype".split(
)
for field in fields: for field in fields:
longoutput( "- %s = %s\n" % (field, i[field]) ) longoutput("- %s = %s\n" % (field, i[field]))
nagios_state = max(nagios_state, check_multiple_objects(i, 'sensors')) nagios_state = max(nagios_state, check_multiple_objects(i, 'sensors'))
nagios_state = max(nagios_state, check_multiple_objects(i, 'fans')) nagios_state = max(nagios_state, check_multiple_objects(i, 'fans'))
nagios_state = max(nagios_state, check_multiple_objects(i, 'powersupplies')) nagios_state = max(
nagios_state = max(nagios_state, check_multiple_objects(i, 'communicationbuses')) nagios_state, check_multiple_objects(i, 'powersupplies'))
nagios_state = max(nagios_state, check_multiple_objects(i, 'fibrechannelports')) nagios_state = max(
nagios_state, check_multiple_objects(i, 'communicationbuses'))
nagios_state = max(
nagios_state, check_multiple_objects(i, 'fibrechannelports'))
nagios_state = max(nagios_state, check_multiple_objects(i, 'modules')) nagios_state = max(nagios_state, check_multiple_objects(i, 'modules'))
for x in longserviceoutputfields: for x in longserviceoutputfields:
if i.has_key( x ): if i.has_key(x):
longoutput( "- %s = %s\n" % (x, i[x])) longoutput("- %s = %s\n" % (x, i[x]))
end(summary, perfdata, longserviceoutput, nagios_state)
end(summary,perfdata,longserviceoutput,nagios_state)
def check_multiple_objects(my_object, name): def check_multiple_objects(my_object, name):
item_status = not_present item_status = not_present
if my_object.has_key(name): if my_object.has_key(name):
item_status = not_present item_status = not_present
valid_states=['good'] valid_states = ['good']
namefield="name" namefield = "name"
detailfield = 'operationalstatedetail' detailfield = 'operationalstatedetail'
if name == 'fans' or name == 'sensors': if name == 'fans' or name == 'sensors':
valid_states = ['good','notavailable','unsupported','notinstalled'] valid_states = [
'good', 'notavailable', 'unsupported', 'notinstalled']
elif name == 'fibrechannelports': elif name == 'fibrechannelports':
valid_states.append( 'notinstalled' ) valid_states.append('notinstalled')
num_items = len(my_object[name]) num_items = len(my_object[name])
for item in my_object[name]: for item in my_object[name]:
stat = check_operationalstate( item,print_failed_objects=True, namefield=namefield, valid_states=valid_states,detailfield=detailfield) stat = check_operationalstate(
item_status = max( stat, item_status ) item, print_failed_objects=True, namefield=namefield, valid_states=valid_states, detailfield=detailfield)
longoutput('- %s on %s (%s detected)\n'% (state[item_status], name, num_items) ) item_status = max(stat, item_status)
add_perfdata( " '%s%s'=%s" % (my_object['identifier'],name, num_items) ) longoutput('- %s on %s (%s detected)\n' %
(state[item_status], name, num_items))
add_perfdata(" '%s%s'=%s" %
(my_object['identifier'], name, num_items))
return item_status return item_status
def check_controllers(): def check_controllers():
perfdata="" perfdata = ""
#longserviceoutput="\n" # longserviceoutput="\n"
nagios_state = ok nagios_state = ok
systems = run_sssu() systems = run_sssu()
controllers =[] controllers = []
for i in systems: for i in systems:
result = run_sssu(system=i['objectname'], command="ls controller full") result = run_sssu(system=i['objectname'], command="ls controller full")
for controller in result: for controller in result:
controller['systemname'] = i['objectname'] controller['systemname'] = i['objectname']
controllers.append( controller ) controllers.append(controller)
summary = "%s objects found " % len(controllers) summary = "%s objects found " % len(controllers)
for i in controllers: for i in controllers:
systemname = i['systemname'] systemname = i['systemname']
@ -576,28 +611,30 @@ def check_controllers():
else: else:
controllername = i['objectname'] controllername = i['objectname']
# Lets see if this controller is working # Lets see if this controller is working
nagios_state = max( check_operationalstate(i), nagios_state ) nagios_state = max(check_operationalstate(i), nagios_state)
# Lets add to the summary # Lets add to the summary
if not i.has_key('operationalstate'): if not i.has_key('operationalstate'):
summary += " %s does not have any operationalstate " % controllername summary += " %s does not have any operationalstate " % controllername
nagios_state = max( unknown, nagios_state ) nagios_state = max(unknown, nagios_state)
continue continue
elif i['operationalstate'] != 'good': elif i['operationalstate'] != 'good':
summary += " %s/%s=%s " % (systemname, controllername, i['operationalstate']) summary += " %s/%s=%s " % (
systemname, controllername, i['operationalstate'])
# Lets get some perfdata # Lets get some perfdata
interesting_fields = "controllermainmemory" interesting_fields = "controllermainmemory"
identifier = "%s/%s_" % (systemname,controllername) identifier = "%s/%s_" % (systemname, controllername)
perfdata += get_perfdata(i, interesting_fields.split('|'), identifier=identifier) perfdata += get_perfdata(
i, interesting_fields.split('|'), identifier=identifier)
# Long Serviceoutput # Long Serviceoutput
#longserviceoutput = longserviceoutput + get_longserviceoutput(i, interesting_fields.split('|') ) #longserviceoutput = longserviceoutput + get_longserviceoutput(i, interesting_fields.split('|') )
#longserviceoutput = longserviceoutput + "\n%s/%s\n"%(systemname,controllername) #longserviceoutput = longserviceoutput + "\n%s/%s\n"%(systemname,controllername)
longoutput( "\n%s/%s = %s (%s)\n"%(systemname,controllername,i['operationalstate'], i['operationalstatedetail']) ) longoutput("\n%s/%s = %s (%s)\n" %
longoutput( "- firmwareversion = %s \n" %(i['firmwareversion'])) (systemname, controllername, i['operationalstate'], i['operationalstatedetail']))
longoutput( "- serialnumber = %s \n" %(i['serialnumber'])) longoutput("- firmwareversion = %s \n" % (i['firmwareversion']))
longoutput("- serialnumber = %s \n" % (i['serialnumber']))
controllertemper1aturestatus = not_present controllertemper1aturestatus = not_present
fanstate = not_present fanstate = not_present
@ -619,86 +656,97 @@ def check_controllers():
else: else:
controllertemperaturestatus = warning controllertemperaturestatus = warning
# Process the subsensors # Process the subsensors
for hostport in i['hostports']: for hostport in i['hostports']:
#long(" %s = %s\n" % (hostport['portname'], hostport['operationalstate'])) #long(" %s = %s\n" % (hostport['portname'], hostport['operationalstate']))
hostportstate = max(hostportstate,ok) hostportstate = max(hostportstate, ok)
if hostport['operationalstate'] != 'good': if hostport['operationalstate'] != 'good':
hostportstate = max(warning,hostport_state) hostportstate = max(warning, hostport_state)
message = "Hostport %s state = %s\n" % (hostport['portname'], hostport['operationalstate']) message = "Hostport %s state = %s\n" % (
hostport['portname'], hostport['operationalstate'])
longoutput(message) longoutput(message)
if i.has_key('fans'): if i.has_key('fans'):
for fan in i['fans']: for fan in i['fans']:
fanstate = max(fanstate,ok) fanstate = max(fanstate, ok)
#long(" %s = %s\n" % (fan['fanname'], fan['status'])) #long(" %s = %s\n" % (fan['fanname'], fan['status']))
if fan.has_key('status'): status = fan['status'] if fan.has_key('status'):
elif fan.has_key('installstatus'): status = fan['installstatus'] status = fan['status']
elif fan.has_key('installstatus'):
status = fan['installstatus']
if status != 'normal' and status != 'yes': if status != 'normal' and status != 'yes':
fanstate = max(warning,fanstate) fanstate = max(warning, fanstate)
longoutput("Fan %s status = %s\n" % (fan['fanname'],status)) longoutput("Fan %s status = %s\n" %
(fan['fanname'], status))
if i.has_key('powersources'): if i.has_key('powersources'):
for source in i['powersources']: for source in i['powersources']:
source_state = max(source_state,ok) source_state = max(source_state, ok)
if not source.has_key('status'): continue if not source.has_key('status'):
continue
if source['state'] != 'good': if source['state'] != 'good':
source_state = max(warning,source_state) source_state = max(warning, source_state)
longoutput("Powersource %s status = %s\n" % (source['type'],source['state'])) longoutput("Powersource %s status = %s\n" %
(source['type'], source['state']))
if i.has_key('modules'): if i.has_key('modules'):
for module in i['modules']: for module in i['modules']:
module_state = max(module_state,ok) module_state = max(module_state, ok)
if module['operationalstate'] not in ('good','not_present'): if module['operationalstate'] not in ('good', 'not_present'):
module_state = max(warning,module_state) module_state = max(warning, module_state)
longoutput("Battery Module %s status = %s\n" % (module['name'],module['operationalstate'])) longoutput("Battery Module %s status = %s\n" %
(module['name'], module['operationalstate']))
for i in (fanstate, hostportstate, sensorstate, source_state, module_state, cache_state, controllertemperaturestatus):
for i in (fanstate,hostportstate,sensorstate,source_state,module_state,cache_state,controllertemperaturestatus):
nagios_state = max(nagios_state, i) nagios_state = max(nagios_state, i)
longoutput("- %s on fans\n"%( state[fanstate] ) ) longoutput("- %s on fans\n" % (state[fanstate]))
longoutput("- %s on cachememory\n"%( state[cache_state] ) ) longoutput("- %s on cachememory\n" % (state[cache_state]))
longoutput("- %s on temperature\n"%( state[controllertemperaturestatus] ) ) longoutput("- %s on temperature\n" %
longoutput("- %s on hostports\n"%( state[hostportstate] ) ) (state[controllertemperaturestatus]))
longoutput("- %s on sensors\n"%( state[sensorstate] ) ) longoutput("- %s on hostports\n" % (state[hostportstate]))
longoutput("- %s on powersupplies\n"%( state[source_state] ) ) longoutput("- %s on sensors\n" % (state[sensorstate]))
longoutput("- %s on batterymodules\n"%( state[module_state] ) ) longoutput("- %s on powersupplies\n" % (state[source_state]))
longoutput("- %s on batterymodules\n" % (state[module_state]))
longoutput('\n') longoutput('\n')
end(summary,perfdata,longserviceoutput,nagios_state) end(summary, perfdata, longserviceoutput, nagios_state)
def set_path(): def set_path():
global path global path
current_path = getenv('PATH') current_path = getenv('PATH')
if path == '': if path == '':
if current_path.find('C:\\') > -1: # We are on this platform if current_path.find('C:\\') > -1: # We are on this platform
path = ";C:\\Program Files\\Hewlett-Packard\\Sanworks\\Element Manager for StorageWorks HSV" path = ";C:\\Program Files\\Hewlett-Packard\\Sanworks\\Element Manager for StorageWorks HSV"
else: else:
path = ":/usr/local/bin" path = ":/usr/local/bin"
current_path = "%s%s" % (current_path,path) current_path = "%s%s" % (current_path, path)
environ['PATH'] = current_path environ['PATH'] = current_path
set_path() set_path()
if mode == 'check_systems': if mode == 'check_systems':
perfdata_fields = 'totalstoragespace usedstoragespace availablestoragespace'.split() perfdata_fields = 'totalstoragespace usedstoragespace availablestoragespace'.split(
longserviceoutputfields = 'licensestate systemtype firmwareversion nscfwversion totalstoragespace usedstoragespace availablestoragespace'.split() )
longserviceoutputfields = 'licensestate systemtype firmwareversion nscfwversion totalstoragespace usedstoragespace availablestoragespace'.split(
)
command = "ls system full" command = "ls system full"
namefield="objectname" namefield = "objectname"
check_generic(command=command,namefield=namefield,longserviceoutputfields=longserviceoutputfields, perfdata_fields=perfdata_fields) check_generic(command=command, namefield=namefield,
longserviceoutputfields=longserviceoutputfields, perfdata_fields=perfdata_fields)
elif mode == 'check_controllers': elif mode == 'check_controllers':
check_controllers() check_controllers()
elif mode == 'check_diskgroups': elif mode == 'check_diskgroups':
command = "ls disk_group full" command = "ls disk_group full"
namefield='diskgroupname' namefield = 'diskgroupname'
longserviceoutputfields = "totaldisks levelingstate levelingprogress totalstoragespacegb usedstoragespacegb occupancyalarmlevel".split() longserviceoutputfields = "totaldisks levelingstate levelingprogress totalstoragespacegb usedstoragespacegb occupancyalarmlevel".split(
perfdata_fields="totaldisks".split() )
check_generic(command=command,namefield=namefield,longserviceoutputfields=longserviceoutputfields, perfdata_fields=perfdata_fields) perfdata_fields = "totaldisks".split()
check_generic(command=command, namefield=namefield,
longserviceoutputfields=longserviceoutputfields, perfdata_fields=perfdata_fields)
elif mode == 'check_disks': elif mode == 'check_disks':
check_generic(command="ls disk full",namefield="objectname") check_generic(command="ls disk full", namefield="objectname")
elif mode == 'check_diskshelfs' or mode == 'check_diskshelves': elif mode == 'check_diskshelfs' or mode == 'check_diskshelves':
check_generic(command="ls diskshelf full", namefield="diskshelfname", longserviceoutputfields=[], perfdata_fields=[]) check_generic(command="ls diskshelf full", namefield="diskshelfname",
longserviceoutputfields=[], perfdata_fields=[])
else: else:
print "* Error: Mode %s not found" % mode print "* Error: Mode %s not found" % mode
print_help() print_help()