Reformat all files with black (target=py27, line-length=160)

This commit is contained in:
Adam Cecile 2021-08-17 09:42:18 +02:00
parent 9976ceeaff
commit e0d3be643a
7 changed files with 1331 additions and 1240 deletions

View File

@ -7,33 +7,33 @@ import sys
binarypath = "/usr/sbin/tw-cli" binarypath = "/usr/sbin/tw-cli"
if len(sys.argv) > 2: if len(sys.argv) > 2:
print 'Usage: 3ware-status [--nagios]' print "Usage: 3ware-status [--nagios]"
sys.exit(1) sys.exit(1)
nagiosmode=False nagiosmode = False
nagiosoutput='' nagiosoutput = ""
nagiosgoodarray=0 nagiosgoodarray = 0
nagiosbadarray=0 nagiosbadarray = 0
nagiosgooddisk=0 nagiosgooddisk = 0
nagiosbaddisk=0 nagiosbaddisk = 0
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[1] == '--nagios': if sys.argv[1] == "--nagios":
nagiosmode=True nagiosmode = True
else: else:
print 'Usage: 3ware-status [--nagios]' print "Usage: 3ware-status [--nagios]"
sys.exit(1) sys.exit(1)
# Check binary exists (and +x), if not print an error message # Check binary exists (and +x), if not print an error message
# or return UNKNOWN nagios error code # or return UNKNOWN nagios error code
if os.path.exists(binarypath) and os.access(binarypath, os.X_OK): if os.path.exists(binarypath) and os.access(binarypath, os.X_OK):
pass pass
else: else:
if nagiosmode: if nagiosmode:
print 'UNKNOWN - Cannot find '+binarypath print "UNKNOWN - Cannot find " + binarypath
else: else:
print 'Cannot find '+binarypath+'. Please install it.' print "Cannot find " + binarypath + ". Please install it."
sys.exit(3) sys.exit(3)
# Get command output # Get command output
@ -41,45 +41,49 @@ def getOutput(cmd):
output = os.popen(cmd) output = os.popen(cmd)
lines = [] lines = []
for line in output: for line in output:
if not re.match(r'^$',line.strip()): if not re.match(r"^$", line.strip()):
lines.append(line.strip()) lines.append(line.strip())
return lines return lines
def returnControllerList(output): def returnControllerList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^c[0-9]+\s.*$',line.strip()): if re.match(r"^c[0-9]+\s.*$", line.strip()):
lines.append(line.split()[0]) lines.append(line.split()[0])
return lines return lines
def returnDiskList(output): def returnDiskList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[p][0-9]+\s.*$',line.strip()): if re.match(r"^[p][0-9]+\s.*$", line.strip()):
# Shoudl contain something like 'u0' # Shoudl contain something like 'u0'
# '-' means the drive doesn't belong to any array # '-' means the drive doesn't belong to any array
# If is NOT PRESENT too, it just means this is an empty port # If is NOT PRESENT too, it just means this is an empty port
if not line.split()[2].strip() == '-' and not line.split()[1].strip() == 'NOT-PRESENT': if not line.split()[2].strip() == "-" and not line.split()[1].strip() == "NOT-PRESENT":
lines.append(line.split()) lines.append(line.split())
if fake_failure: if fake_failure:
lines[0][1] = 'NOT PRESENT' lines[0][1] = "NOT PRESENT"
return lines return lines
def returnArrayList(output): def returnArrayList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[u][0-9]+\s.*$',line.strip()): if re.match(r"^[u][0-9]+\s.*$", line.strip()):
lines.append(line.split()) lines.append(line.split())
if fake_failure: if fake_failure:
lines[0][2] = 'DEGRADED' lines[0][2] = "DEGRADED"
return lines return lines
# A way to force a fake failure # A way to force a fake failure
fake_failure = False fake_failure = False
if os.path.exists('/root/fake_3ware_failure'): if os.path.exists("/root/fake_3ware_failure"):
fake_failure = True fake_failure = True
cmd = binarypath+' info' cmd = binarypath + " info"
output = getOutput(cmd) output = getOutput(cmd)
controllerlist = returnControllerList(output) controllerlist = returnControllerList(output)
@ -88,70 +92,74 @@ bad = False
# List available controller # List available controller
if not nagiosmode: if not nagiosmode:
print '-- Controller informations --' print "-- Controller informations --"
print '-- ID | Model' print "-- ID | Model"
for controller in controllerlist: for controller in controllerlist:
cmd = binarypath+' info '+controller+' model' cmd = binarypath + " info " + controller + " model"
# https://github.com/eLvErDe/hwraid/issues/69 # https://github.com/eLvErDe/hwraid/issues/69
try: try:
model = getOutput(cmd)[0].split(' = ')[1].strip() model = getOutput(cmd)[0].split(" = ")[1].strip()
except IndexError: except IndexError:
model = 'N/A' model = "N/A"
print controller+' | '+model print controller + " | " + model
print '' print ""
# List arrays # List arrays
if not nagiosmode: if not nagiosmode:
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID\tType\tSize\tStatus' print "-- ID\tType\tSize\tStatus"
for controller in controllerlist: for controller in controllerlist:
cmd = binarypath+' info '+controller cmd = binarypath + " info " + controller
output = getOutput(cmd) output = getOutput(cmd)
arraylist = returnArrayList(output) arraylist = returnArrayList(output)
for array in arraylist: for array in arraylist:
type = array[1].replace('-','') type = array[1].replace("-", "")
id = controller+array[0] id = controller + array[0]
size = array[6].split('.')[0]+'G' size = array[6].split(".")[0] + "G"
status = array[2] status = array[2]
if not status in ['OK','VERIFYING']: if not status in ["OK", "VERIFYING"]:
bad = True bad = True
nagiosbadarray=nagiosbadarray+1 nagiosbadarray = nagiosbadarray + 1
else: else:
nagiosgoodarray=nagiosgoodarray+1 nagiosgoodarray = nagiosgoodarray + 1
if not nagiosmode: if not nagiosmode:
print id+'\t'+type+'\t'+size+'\t'+status print id + "\t" + type + "\t" + size + "\t" + status
if not nagiosmode: if not nagiosmode:
print '' print ""
# List disks # List disks
if not nagiosmode: if not nagiosmode:
print '-- Disks informations' print "-- Disks informations"
print '-- ID\tModel\t\t\tStatus' print "-- ID\tModel\t\t\tStatus"
for controller in controllerlist: for controller in controllerlist:
cmd = binarypath+' info '+controller cmd = binarypath + " info " + controller
output = getOutput(cmd) output = getOutput(cmd)
disklist = returnDiskList(output) disklist = returnDiskList(output)
for disk in disklist: for disk in disklist:
id = controller+disk[2]+disk[0] id = controller + disk[2] + disk[0]
cmd = binarypath+' info '+controller+' '+disk[0]+' model' cmd = binarypath + " info " + controller + " " + disk[0] + " model"
model = getOutput(cmd)[0].split(' = ')[1].strip() model = getOutput(cmd)[0].split(" = ")[1].strip()
cmd = binarypath+' info '+controller+' '+disk[0]+' status' cmd = binarypath + " info " + controller + " " + disk[0] + " status"
status = getOutput(cmd)[0].split(' = ')[1].strip() status = getOutput(cmd)[0].split(" = ")[1].strip()
if not status == 'OK': if not status == "OK":
bad = True bad = True
nagiosbaddisk=nagiosbaddisk+1 nagiosbaddisk = nagiosbaddisk + 1
else: else:
nagiosgooddisk=nagiosgooddisk+1 nagiosgooddisk = nagiosgooddisk + 1
if not nagiosmode: if not nagiosmode:
print id+'\t'+model+'\t'+status print id + "\t" + model + "\t" + status
if nagiosmode: if nagiosmode:
if bad: if bad:
print 'RAID ERROR - Arrays: OK:'+str(nagiosgoodarray)+' Bad:'+str(nagiosbadarray)+' - Disks: OK:'+str(nagiosgooddisk)+' Bad:'+str(nagiosbaddisk) print "RAID ERROR - Arrays: OK:" + str(nagiosgoodarray) + " Bad:" + str(nagiosbadarray) + " - Disks: OK:" + str(nagiosgooddisk) + " Bad:" + str(
nagiosbaddisk
)
sys.exit(2) sys.exit(2)
else: else:
print 'RAID OK - Arrays: OK:'+str(nagiosgoodarray)+' Bad:'+str(nagiosbadarray)+' - Disks: OK:'+str(nagiosgooddisk)+' Bad:'+str(nagiosbaddisk) print "RAID OK - Arrays: OK:" + str(nagiosgoodarray) + " Bad:" + str(nagiosbadarray) + " - Disks: OK:" + str(nagiosgooddisk) + " Bad:" + str(
nagiosbaddisk
)
else: else:
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
sys.exit(1) sys.exit(1)

View File

@ -9,15 +9,17 @@ from argparse import ArgumentParser
# My own ArgumentParser with single-line stdout output and unknown state Nagios retcode # My own ArgumentParser with single-line stdout output and unknown state Nagios retcode
class NagiosArgumentParser(ArgumentParser): class NagiosArgumentParser(ArgumentParser):
def error(self, message): def error(self, message):
sys.stdout.write('UNKNOWN: Bad arguments (see --help): %s\n' % message) sys.stdout.write("UNKNOWN: Bad arguments (see --help): %s\n" % message)
sys.exit(3) sys.exit(3)
def parse_args(): def parse_args():
parser = NagiosArgumentParser(description='Adaptec AACRAID status script') parser = NagiosArgumentParser(description="Adaptec AACRAID status script")
parser.add_argument('-d', '--disks-only', action="store_true", help='Only disply disk statuses') parser.add_argument("-d", "--disks-only", action="store_true", help="Only disply disk statuses")
parser.add_argument('-n', '--nagios', action="store_true", help='Use Nagios-like output and return code') parser.add_argument("-n", "--nagios", action="store_true", help="Use Nagios-like output and return code")
return parser.parse_args() return parser.parse_args()
def which(program): def which(program):
fpath, fname = os.path.split(program) fpath, fname = os.path.split(program)
if fpath: if fpath:
@ -25,7 +27,7 @@ def which(program):
return program return program
else: else:
# Add some defaults # Add some defaults
os.environ["PATH"] += os.pathsep + '/usr/StorMan/arcconf' os.environ["PATH"] += os.pathsep + "/usr/StorMan/arcconf"
os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(sys.argv[0])) os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(sys.argv[0]))
for path in os.environ["PATH"].split(os.pathsep): for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"') path = path.strip('"')
@ -34,58 +36,65 @@ def which(program):
return exe_file return exe_file
return None return None
def is_exe(fpath): def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK) return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# Get command output # Get command output
def getOutput(cmd): def getOutput(cmd):
output = os.popen('%s 2>%s' % (cmd, os.devnull)) output = os.popen("%s 2>%s" % (cmd, os.devnull))
lines = [] lines = []
for line in output: for line in output:
if not re.match(r'^$',line.strip()): if not re.match(r"^$", line.strip()):
lines.append(line.strip()) lines.append(line.strip())
return lines return lines
def returnControllerNumber(output): def returnControllerNumber(output):
for line in output: for line in output:
if re.match(r'^Controllers found: [0-9]+$',line.strip()): if re.match(r"^Controllers found: [0-9]+$", line.strip()):
return int(line.split(':')[1].strip().strip('.')) return int(line.split(":")[1].strip().strip("."))
def returnControllerModel(output): def returnControllerModel(output):
for line in output: for line in output:
if re.match(r'^Controller Model.*$',line.strip()): if re.match(r"^Controller Model.*$", line.strip()):
return line.split(':')[1].strip() return line.split(":")[1].strip()
def returnControllerStatus(output): def returnControllerStatus(output):
for line in output: for line in output:
if re.match(r'^Controller Status.*$',line.strip()): if re.match(r"^Controller Status.*$", line.strip()):
return line.split(':')[1].strip() return line.split(":")[1].strip()
def returnArrayIds(output): def returnArrayIds(output):
ids = [] ids = []
for line in output: for line in output:
if re.match(r'^Logical [Dd]evice number [0-9]+$',line.strip()): if re.match(r"^Logical [Dd]evice number [0-9]+$", line.strip()):
ids.append(re.sub(r'^Logical [Dd]evice number', '', line).strip()) ids.append(re.sub(r"^Logical [Dd]evice number", "", line).strip())
return ids return ids
def returnArrayInfo(output, ctrl_id='?'):
def returnArrayInfo(output, ctrl_id="?"):
# For testing purpose # For testing purpose
#with open('/tmp/output') as f: # with open('/tmp/output') as f:
# output = f.read().splitlines() # output = f.read().splitlines()
members = [] members = []
for line in output: for line in output:
# RAID level may be either N or Simple_Volume # RAID level may be either N or Simple_Volume
# (a disk connected to the card, not hotspare, not part of any array) # (a disk connected to the card, not hotspare, not part of any array)
if re.match(r'^RAID level\s+: .+$',line.strip()): if re.match(r"^RAID level\s+: .+$", line.strip()):
type = line.split(':')[1].strip() type = line.split(":")[1].strip()
if re.match(r'^Status of [Ll]ogical [Dd]evice\s+: .*$',line.strip()): if re.match(r"^Status of [Ll]ogical [Dd]evice\s+: .*$", line.strip()):
status = line.split(':')[1].strip() status = line.split(":")[1].strip()
if re.match(r'^Size\s+: [0-9]+ MB$',line.strip()): if re.match(r"^Size\s+: [0-9]+ MB$", line.strip()):
size = str(int(line.strip('MB').split(':')[1].strip()) / 1000) size = str(int(line.strip("MB").split(":")[1].strip()) / 1000)
if re.match(r'^(Group\s[0-9]+,\s)?Segment\s[0-9]+\s+: .*$',line.strip()): if re.match(r"^(Group\s[0-9]+,\s)?Segment\s[0-9]+\s+: .*$", line.strip()):
# The line can be either (arcconf 1.x) # The line can be either (arcconf 1.x)
# Group 0, Segment 0 : Present (Controller:1,Enclosure:0,Slot:0) JPW9J0N00RWMUV # Group 0, Segment 0 : Present (Controller:1,Enclosure:0,Slot:0) JPW9J0N00RWMUV
@ -96,43 +105,44 @@ def returnArrayInfo(output, ctrl_id='?'):
# Group 0, Segment 0 : Present (953869MB, SATA, HDD, Connector:1, Device:1) JPW9K0HZ216NJL' # Group 0, Segment 0 : Present (953869MB, SATA, HDD, Connector:1, Device:1) JPW9K0HZ216NJL'
# Cut on : and re-join everything except first part # Cut on : and re-join everything except first part
line = ':'.join(line.split(':')[1:]).strip() line = ":".join(line.split(":")[1:]).strip()
# Extract everything between () # Extract everything between ()
device_state = re.search('\s+\((.*)\)\s+', line).group(1) device_state = re.search("\s+\((.*)\)\s+", line).group(1)
# Coma separated # Coma separated
device_attrs = device_state.split(',') device_attrs = device_state.split(",")
device_attrs = [ x.strip() for x in device_attrs ] device_attrs = [x.strip() for x in device_attrs]
# Some magic here... # Some magic here...
# Strip out from the list element not matching Xyz:12 # Strip out from the list element not matching Xyz:12
# Split on column: now we have and array of arrays like [['Controller', '1'], ['Connector', '1'], ['Device', '0']] # Split on column: now we have and array of arrays like [['Controller', '1'], ['Connector', '1'], ['Device', '0']]
# Casting to dict will turn Controller as key and 1 as value # Casting to dict will turn Controller as key and 1 as value
device_attrs = dict([ x.split(':') for x in device_attrs if re.match('\w+:\d+', x) ]) device_attrs = dict([x.split(":") for x in device_attrs if re.match("\w+:\d+", x)])
# Extract id for this device # Extract id for this device
if 'Controller' in device_attrs: if "Controller" in device_attrs:
controller_id = device_attrs['Controller'] controller_id = device_attrs["Controller"]
else: else:
controller_id = ctrl_id controller_id = ctrl_id
if 'Channel' in device_attrs: if "Channel" in device_attrs:
channel_id = device_attrs['Channel'] channel_id = device_attrs["Channel"]
elif 'Enclosure' in device_attrs: elif "Enclosure" in device_attrs:
channel_id = device_attrs['Enclosure'] channel_id = device_attrs["Enclosure"]
elif 'Connector' in device_attrs: elif "Connector" in device_attrs:
channel_id = device_attrs['Connector'] channel_id = device_attrs["Connector"]
else: else:
channel_id = '?' channel_id = "?"
if 'Device' in device_attrs: if "Device" in device_attrs:
device_id = device_attrs['Device'] device_id = device_attrs["Device"]
elif 'Slot' in device_attrs: elif "Slot" in device_attrs:
device_id = device_attrs['Slot'] device_id = device_attrs["Slot"]
else: else:
device_id = '?' device_id = "?"
members.append('%s,%s,%s' % (controller_id, channel_id, device_id)) members.append("%s,%s,%s" % (controller_id, channel_id, device_id))
return [type, status, size, members]
return [type,status,size,members]
def returnControllerTasks(output): def returnControllerTasks(output):
arrayid = False arrayid = False
@ -140,20 +150,21 @@ def returnControllerTasks(output):
state = False state = False
tasks = [] tasks = []
for line in output: for line in output:
if re.match(r'^Logical device\s+: [0-9]+$',line.strip()): if re.match(r"^Logical device\s+: [0-9]+$", line.strip()):
arrayid = line.split(':')[1].strip() arrayid = line.split(":")[1].strip()
if re.match(r'^Current operation\s+: .*$',line.strip()): if re.match(r"^Current operation\s+: .*$", line.strip()):
type = line.split(':')[1].strip() type = line.split(":")[1].strip()
if re.match(r'^Percentage complete\s+: [0-9]+$',line.strip()): if re.match(r"^Percentage complete\s+: [0-9]+$", line.strip()):
state = line.split(':')[1].strip() state = line.split(":")[1].strip()
if arrayid != False and type != False and state != False: if arrayid != False and type != False and state != False:
tasks.append([arrayid,type,state]) tasks.append([arrayid, type, state])
arrayid = False arrayid = False
type = False type = False
state = False state = False
return tasks return tasks
def returnDisksInfo(output,controllerid):
def returnDisksInfo(output, controllerid):
diskid = False diskid = False
vendor = False vendor = False
model = False model = False
@ -161,18 +172,18 @@ def returnDisksInfo(output,controllerid):
serial = False serial = False
disks = [] disks = []
for line in output: for line in output:
if re.match(r'^Reported Channel,Device(\(T:L\))?\s+: [0-9]+,[0-9]+(\([0-9]+:[0-9]+\))?$',line.strip()): if re.match(r"^Reported Channel,Device(\(T:L\))?\s+: [0-9]+,[0-9]+(\([0-9]+:[0-9]+\))?$", line.strip()):
diskid = re.split('\s:\s',line)[1].strip() diskid = re.split("\s:\s", line)[1].strip()
diskid = re.sub('\(.*\)','',diskid) diskid = re.sub("\(.*\)", "", diskid)
diskid = str(controllerid)+','+diskid diskid = str(controllerid) + "," + diskid
if re.match(r'^State\s+:.*$',line.strip()): if re.match(r"^State\s+:.*$", line.strip()):
state = line.split(':')[1].strip() state = line.split(":")[1].strip()
if re.match(r'^Vendor\s+:.*$',line.strip()): if re.match(r"^Vendor\s+:.*$", line.strip()):
vendor = line.split(':')[1].strip() vendor = line.split(":")[1].strip()
if re.match(r'^Model\s+:.*$',line.strip()): if re.match(r"^Model\s+:.*$", line.strip()):
model = line.split(':')[1].strip() model = line.split(":")[1].strip()
if re.match(r'^Serial number\s+:.*$',line.strip()): if re.match(r"^Serial number\s+:.*$", line.strip()):
serial = line.split(':')[1].strip() serial = line.split(":")[1].strip()
if diskid != False and vendor != False and model != False and state != False and serial != False: if diskid != False and vendor != False and model != False and state != False and serial != False:
disks.append([diskid, state, vendor, model, serial]) disks.append([diskid, state, vendor, model, serial])
diskid = False diskid = False
@ -182,6 +193,7 @@ def returnDisksInfo(output,controllerid):
serial = False serial = False
return disks return disks
config = parse_args() config = parse_args()
if config.disks_only: if config.disks_only:
printarray = False printarray = False
@ -190,7 +202,7 @@ else:
printarray = True printarray = True
printcontroller = True printcontroller = True
nagiosoutput='' nagiosoutput = ""
nagiosgoodctrl = 0 nagiosgoodctrl = 0
nagiosbadctrl = 0 nagiosbadctrl = 0
nagiosctrlbadarray = 0 nagiosctrlbadarray = 0
@ -202,20 +214,20 @@ nagiosbaddisk = 0
bad = False bad = False
# Find arcconf # Find arcconf
for arcconfbin in "arcconf","arcconf.exe": for arcconfbin in "arcconf", "arcconf.exe":
arcconfpath = which(arcconfbin) arcconfpath = which(arcconfbin)
if (arcconfpath != None): if arcconfpath != None:
break break
# Check binary exists (and +x), if not print an error message # Check binary exists (and +x), if not print an error message
if (arcconfpath != None): if arcconfpath != None:
if is_exe(arcconfpath): if is_exe(arcconfpath):
pass pass
else: else:
if config.nagios: if config.nagios:
print 'UNKNOWN - Cannot find '+arcconfpath print "UNKNOWN - Cannot find " + arcconfpath
else: else:
print 'Cannot find ' + arcconfpath + 'in your PATH. Please install it.' print "Cannot find " + arcconfpath + "in your PATH. Please install it."
sys.exit(3) sys.exit(3)
else: else:
print 'Cannot find "arcconf, "arcconf.exe" in your PATH. Please install it.' print 'Cannot find "arcconf, "arcconf.exe" in your PATH. Please install it.'
@ -232,31 +244,31 @@ if not controllernumber:
# List controllers # List controllers
if printcontroller: if printcontroller:
if not config.nagios: if not config.nagios:
print '-- Controller informations --' print "-- Controller informations --"
print '-- ID | Model | Status' print "-- ID | Model | Status"
controllerid = 1 controllerid = 1
while controllerid <= controllernumber: while controllerid <= controllernumber:
cmd = '"%s" GETCONFIG %d' % (arcconfpath, controllerid) cmd = '"%s" GETCONFIG %d' % (arcconfpath, controllerid)
output = getOutput(cmd) output = getOutput(cmd)
controllermodel = returnControllerModel(output) controllermodel = returnControllerModel(output)
controllerstatus = returnControllerStatus(output) controllerstatus = returnControllerStatus(output)
if controllerstatus != 'Optimal': if controllerstatus != "Optimal":
bad = True bad = True
nagiosbadctrl += 1 nagiosbadctrl += 1
else: else:
nagiosgoodctrl += 1 nagiosgoodctrl += 1
if not config.nagios: if not config.nagios:
print 'c'+str(controllerid-1)+' | '+controllermodel+' | '+controllerstatus print "c" + str(controllerid - 1) + " | " + controllermodel + " | " + controllerstatus
controllerid += 1 controllerid += 1
if not config.nagios: if not config.nagios:
print '' print ""
# List arrays # List arrays
if printarray: if printarray:
controllerid = 1 controllerid = 1
if not config.nagios: if not config.nagios:
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID | Type | Size | Status | Task | Progress' print "-- ID | Type | Size | Status | Task | Progress"
while controllerid <= controllernumber: while controllerid <= controllernumber:
arrayid = 0 arrayid = 0
cmd = '"%s" GETCONFIG %s' % (arcconfpath, controllerid) cmd = '"%s" GETCONFIG %s' % (arcconfpath, controllerid)
@ -266,7 +278,7 @@ if printarray:
cmd = '"%s" GETCONFIG %s LD %s' % (arcconfpath, controllerid, arrayid) cmd = '"%s" GETCONFIG %s LD %s' % (arcconfpath, controllerid, arrayid)
output = getOutput(cmd) output = getOutput(cmd)
arrayinfo = returnArrayInfo(output, ctrl_id=controllerid) arrayinfo = returnArrayInfo(output, ctrl_id=controllerid)
if arrayinfo[1] != 'Optimal': if arrayinfo[1] != "Optimal":
nagiosbadarray += 1 nagiosbadarray += 1
bad = True bad = True
else: else:
@ -278,43 +290,44 @@ if printarray:
# Usually it should return either [0-9] or Simple_Volume but... # Usually it should return either [0-9] or Simple_Volume but...
# It can also return "6 Reed-Solomon" so we need to handle this too... # It can also return "6 Reed-Solomon" so we need to handle this too...
# So let's match [0-9] followed by a space or EOL. # So let's match [0-9] followed by a space or EOL.
if re.match('^[0-9]+(\s|$)',arrayinfo[0]): if re.match("^[0-9]+(\s|$)", arrayinfo[0]):
raidtype = re.sub('^','RAID',arrayinfo[0]) raidtype = re.sub("^", "RAID", arrayinfo[0])
else: else:
raidtype = arrayinfo[0] raidtype = arrayinfo[0]
for tasks in tasksinfo: for tasks in tasksinfo:
if int(tasks[0]) == int(arrayid): if int(tasks[0]) == int(arrayid):
if not config.nagios: if not config.nagios:
print 'c'+str(controllerid-1)+'u'+str(arrayid)+' | '+raidtype+' | '+arrayinfo[2]+'G | '+arrayinfo[1]+' | '+tasks[1]+' | '+tasks[2]+'%' print "c" + str(controllerid - 1) + "u" + str(arrayid) + " | " + raidtype + " | " + arrayinfo[2] + "G | " + arrayinfo[
1
] + " | " + tasks[1] + " | " + tasks[2] + "%"
done = True done = True
break break
if done == False: if done == False:
if not config.nagios: if not config.nagios:
print 'c'+str(controllerid-1)+'u'+str(arrayid)+' | '+raidtype+' | '+arrayinfo[2]+'G | '+arrayinfo[1] print "c" + str(controllerid - 1) + "u" + str(arrayid) + " | " + raidtype + " | " + arrayinfo[2] + "G | " + arrayinfo[1]
controllerid += 1 controllerid += 1
if not config.nagios: if not config.nagios:
print '' print ""
# List disks # List disks
controllerid = 1 controllerid = 1
if not config.nagios: if not config.nagios:
print '-- Disks informations' print "-- Disks informations"
print '-- ID | Model | Status' print "-- ID | Model | Status"
while controllerid <= controllernumber: while controllerid <= controllernumber:
arrayid = 0 arrayid = 0
cmd = '"%s" GETCONFIG %s' % (arcconfpath, controllerid) cmd = '"%s" GETCONFIG %s' % (arcconfpath, controllerid)
output = getOutput(cmd) output = getOutput(cmd)
arrayids = returnArrayIds(output) arrayids = returnArrayIds(output)
cmd = '"%s" GETCONFIG %d PD' % (arcconfpath, controllerid) cmd = '"%s" GETCONFIG %d PD' % (arcconfpath, controllerid)
output = getOutput(cmd) output = getOutput(cmd)
diskinfo = returnDisksInfo(output,controllerid) diskinfo = returnDisksInfo(output, controllerid)
no_array_disk_id = 0 no_array_disk_id = 0
for disk in diskinfo: for disk in diskinfo:
# Generic verification no matter is the disk is member of an array or not # Generic verification no matter is the disk is member of an array or not
if disk[1] not in [ 'Online', 'Online (JBOD)', 'Hot Spare', 'Ready', 'Global Hot-Spare', 'Dedicated Hot-Spare' ]: if disk[1] not in ["Online", "Online (JBOD)", "Hot Spare", "Ready", "Global Hot-Spare", "Dedicated Hot-Spare"]:
bad = True bad = True
nagiosbaddisk += 1 nagiosbaddisk += 1
else: else:
@ -333,26 +346,34 @@ while controllerid <= controllernumber:
# Matched in members of this array # Matched in members of this array
if disk[0] == member: if disk[0] == member:
if not config.nagios: if not config.nagios:
print 'c'+str(controllerid-1)+'u'+str(arrayid)+'d'+str(memberid)+' | '+disk[2]+' '+disk[3]+' '+disk[4]+' | '+disk[1] print "c" + str(controllerid - 1) + "u" + str(arrayid) + "d" + str(memberid) + " | " + disk[2] + " " + disk[3] + " " + disk[
4
] + " | " + disk[1]
array_member = True array_member = True
memberid += 1 memberid += 1
# Some disks may not be attached to any array (ie: global hot spare) # Some disks may not be attached to any array (ie: global hot spare)
if not array_member: if not array_member:
if not config.nagios: if not config.nagios:
print 'c'+str(controllerid-1)+'uX'+'d'+str(no_array_disk_id)+' | '+disk[2]+' '+disk[3]+' '+disk[4]+' | '+disk[1] print "c" + str(controllerid - 1) + "uX" + "d" + str(no_array_disk_id) + " | " + disk[2] + " " + disk[3] + " " + disk[4] + " | " + disk[1]
no_array_disk_id += 1 no_array_disk_id += 1
controllerid += 1 controllerid += 1
if config.nagios: if config.nagios:
if bad: if bad:
print('RAID ERROR - Controllers OK:%d Bad:%d - Arrays OK:%d Bad:%d - Disks OK:%d Bad:%d' % (nagiosgoodctrl, nagiosbadctrl, nagiosgoodarray, nagiosbadarray, nagiosgooddisk, nagiosbaddisk)) print (
"RAID ERROR - Controllers OK:%d Bad:%d - Arrays OK:%d Bad:%d - Disks OK:%d Bad:%d"
% (nagiosgoodctrl, nagiosbadctrl, nagiosgoodarray, nagiosbadarray, nagiosgooddisk, nagiosbaddisk)
)
sys.exit(2) sys.exit(2)
else: else:
print('RAID OK - Controllers OK:%d Bad:%d - Arrays OK:%d Bad:%d - Disks OK:%d Bad:%d' % (nagiosgoodctrl, nagiosbadctrl, nagiosgoodarray, nagiosbadarray, nagiosgooddisk, nagiosbaddisk)) print (
"RAID OK - Controllers OK:%d Bad:%d - Arrays OK:%d Bad:%d - Disks OK:%d Bad:%d"
% (nagiosgoodctrl, nagiosbadctrl, nagiosgoodarray, nagiosbadarray, nagiosgooddisk, nagiosbaddisk)
)
else: else:
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
print '\nUse "arcconf GETCONFIG [1-9]" to get details.' print '\nUse "arcconf GETCONFIG [1-9]" to get details.'
sys.exit(1) sys.exit(1)

File diff suppressed because it is too large Load Diff

View File

@ -5,46 +5,50 @@ import re
import sys import sys
if len(sys.argv) > 2: if len(sys.argv) > 2:
print 'Usage: megaide-status [-d]' print "Usage: megaide-status [-d]"
sys.exit(1) sys.exit(1)
printarray = True printarray = True
printcontroller = True printcontroller = True
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[1] == '-d': if sys.argv[1] == "-d":
printarray = False printarray = False
printcontroller = False printcontroller = False
else: else:
print 'Usage: megaide-status [-d]' print "Usage: megaide-status [-d]"
sys.exit(1) sys.exit(1)
def returnControllerNumber(): def returnControllerNumber():
for dir in os.listdir('/proc/megaide/'): for dir in os.listdir("/proc/megaide/"):
# We don't really care about how many entries are # We don't really care about how many entries are
# First is 0, last one is number # First is 0, last one is number
number=dir number = dir
return int(number) return int(number)
def returnArrayNumber(controllerid): def returnArrayNumber(controllerid):
list() list()
for array in os.listdir('/proc/megaide/'+str(controllerid)+'/logicaldrives/'): for array in os.listdir("/proc/megaide/" + str(controllerid) + "/logicaldrives/"):
absopath='/proc/megaide/'+str(controllerid)+'/logicaldrives/'+array absopath = "/proc/megaide/" + str(controllerid) + "/logicaldrives/" + array
if os.system('grep -q "This logical drive is not present" '+absopath): if os.system('grep -q "This logical drive is not present" ' + absopath):
return int(array.strip('_info').strip('log_drv_')) return int(array.strip("_info").strip("log_drv_"))
def returnArrayInfo(controllerid,arrayid):
id = 'c'+str(controllerid)+'u'+str(arrayid) def returnArrayInfo(controllerid, arrayid):
f = open('/proc/megaide/'+str(controllerid)+'/logicaldrives/'+'log_drv_'+str(arrayid)+'_info') id = "c" + str(controllerid) + "u" + str(arrayid)
f = open("/proc/megaide/" + str(controllerid) + "/logicaldrives/" + "log_drv_" + str(arrayid) + "_info")
for line in f: for line in f:
if re.match(r'^RAID Level :.*$',line.strip()): if re.match(r"^RAID Level :.*$", line.strip()):
type = 'RAID'+line.split('Status')[0].strip().split()[4] type = "RAID" + line.split("Status")[0].strip().split()[4]
if re.match(r'^Sectors :.*$',line.strip()): if re.match(r"^Sectors :.*$", line.strip()):
size = line.split('Stripe Size')[0].split(':')[1].strip() size = line.split("Stripe Size")[0].split(":")[1].strip()
size = str(int(round(float(size) * 512 / 1000 / 1000 / 1000)))+'G' size = str(int(round(float(size) * 512 / 1000 / 1000 / 1000))) + "G"
if re.match(r'^.*Status :.*$',line.strip()): if re.match(r"^.*Status :.*$", line.strip()):
state = line.split('Status')[1].split(':')[1].strip() state = line.split("Status")[1].split(":")[1].strip()
f.close() f.close()
return [id,type,size,state] return [id, type, size, state]
def returnDiskInfo(): def returnDiskInfo():
# Megaide module report all available port, even there's no disk on it # Megaide module report all available port, even there's no disk on it
@ -55,60 +59,61 @@ def returnDiskInfo():
# c0u0d0 # c0u0d0
# c0u0d2 # c0u0d2
# If logical drive 0 uses disk 0 and disk 2 (chan0 disk0, chan1 disk 0) # If logical drive 0 uses disk 0 and disk 2 (chan0 disk0, chan1 disk 0)
f = open('/etc/megaide-status.conf') f = open("/etc/megaide-status.conf")
table = [] table = []
for line in f: for line in f:
if re.match('^c[0-9]+u[0-9]+p[0-9]+$',line.strip()): if re.match("^c[0-9]+u[0-9]+p[0-9]+$", line.strip()):
# Valid disk entry # Valid disk entry
controllerid=line.split('u')[0].strip().strip('c') controllerid = line.split("u")[0].strip().strip("c")
diskid=line.split('p')[1].strip() diskid = line.split("p")[1].strip()
id=line.strip() id = line.strip()
f2 = open('/proc/megaide/'+controllerid+'/physicaldrives/phy_drv_'+diskid+'_info') f2 = open("/proc/megaide/" + controllerid + "/physicaldrives/phy_drv_" + diskid + "_info")
for line in f2: for line in f2:
if re.match('^Model No :.*$',line.strip()): if re.match("^Model No :.*$", line.strip()):
model=line.split(':')[1].strip() model = line.split(":")[1].strip()
if re.match('^Status :.*$',line.strip()): if re.match("^Status :.*$", line.strip()):
state=line.split()[2].strip() state = line.split()[2].strip()
if re.match('^Drive is Not Present.*$',line.strip()): if re.match("^Drive is Not Present.*$", line.strip()):
model='Unknown' model = "Unknown"
state='OFFLINE' state = "OFFLINE"
f2.close() f2.close()
table.append([id, state, model]) table.append([id, state, model])
f.close() f.close()
return table return table
controllernumber = returnControllerNumber() controllernumber = returnControllerNumber()
bad = False bad = False
if printarray: if printarray:
controllerid = 0 controllerid = 0
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID | Type | Size | Status' print "-- ID | Type | Size | Status"
while controllerid <= controllernumber: while controllerid <= controllernumber:
arrayid = 0 arrayid = 0
arraynumber = returnArrayNumber(controllerid) arraynumber = returnArrayNumber(controllerid)
while arrayid <= arraynumber: while arrayid <= arraynumber:
arrayinfo = returnArrayInfo(controllerid,arrayid) arrayinfo = returnArrayInfo(controllerid, arrayid)
print arrayinfo[0]+' | '+arrayinfo[1]+' | '+arrayinfo[2]+' | '+arrayinfo[3] print arrayinfo[0] + " | " + arrayinfo[1] + " | " + arrayinfo[2] + " | " + arrayinfo[3]
arrayid += 1 arrayid += 1
if not arrayinfo[3] == 'ONLINE': if not arrayinfo[3] == "ONLINE":
bad=True bad = True
controllerid += 1 controllerid += 1
print '' print ""
print '-- Disks informations' print "-- Disks informations"
print '-- ID | Model | Status' print "-- ID | Model | Status"
controllerid = 0 controllerid = 0
while controllerid <= controllernumber: while controllerid <= controllernumber:
diskinfo = returnDiskInfo() diskinfo = returnDiskInfo()
for disk in diskinfo: for disk in diskinfo:
print disk[0]+' | '+disk[2]+' | '+disk[1] print disk[0] + " | " + disk[2] + " | " + disk[1]
if not disk[1] == 'ONLINE': if not disk[1] == "ONLINE":
bad=True bad = True
controllerid += 1 controllerid += 1
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
sys.exit(1) sys.exit(1)

View File

@ -7,99 +7,102 @@ import sys
binarypath = "/usr/sbin/megactl" binarypath = "/usr/sbin/megactl"
if len(sys.argv) > 2: if len(sys.argv) > 2:
print 'Usage: megaraid-status [-d]' print "Usage: megaraid-status [-d]"
sys.exit(1) sys.exit(1)
printarray = True printarray = True
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[1] == '-d': if sys.argv[1] == "-d":
printarray = False printarray = False
else: else:
print 'Usage: megaraid-status [-d]' print "Usage: megaraid-status [-d]"
sys.exit(1) sys.exit(1)
# Check binary exists (and +x), if not print an error message # Check binary exists (and +x), if not print an error message
if os.path.exists(binarypath) and os.access(binarypath, os.X_OK): if os.path.exists(binarypath) and os.access(binarypath, os.X_OK):
pass pass
else: else:
sys.exit(3) sys.exit(3)
# Get command output # Get command output
def getOutput(cmd): def getOutput(cmd):
output = os.popen(cmd) output = os.popen(cmd)
lines = [] lines = []
for line in output: for line in output:
if not re.match(r'^$',line.strip()): if not re.match(r"^$", line.strip()):
lines.append(line.strip()) lines.append(line.strip())
return lines return lines
def returnDiskList(output): def returnDiskList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[a-z][0-9]+[a-z][0-9\*]+[a-z][0-9]+\s.*$',line.strip()): if re.match(r"^[a-z][0-9]+[a-z][0-9\*]+[a-z][0-9]+\s.*$", line.strip()):
list = line.split() list = line.split()
# Let's hack... Some disk may report smart error after status # Let's hack... Some disk may report smart error after status
# Get theses errors, join them into one list item and place it # Get theses errors, join them into one list item and place it
# before status # before status
errindex = False errindex = False
try: try:
errindex = list.index('errs:') errindex = list.index("errs:")
except ValueError: except ValueError:
pass pass
if errindex: if errindex:
list.insert(errindex-1, ' '.join(list[errindex:])) list.insert(errindex - 1, " ".join(list[errindex:]))
list = list[:errindex+1] list = list[: errindex + 1]
lines.append(list) lines.append(list)
if fake_failure: if fake_failure:
lines[0][-1] = 'BAD' lines[0][-1] = "BAD"
return lines return lines
def returnArrayList(output): def returnArrayList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[a-z][0-9]+[a-z][0-9]+\s.*$',line.strip()): if re.match(r"^[a-z][0-9]+[a-z][0-9]+\s.*$", line.strip()):
lines.append(line.split()) lines.append(line.split())
if fake_failure: if fake_failure:
lines[0][-1] = 'DEGRADED' lines[0][-1] = "DEGRADED"
return lines return lines
# A way to force a fake failure # A way to force a fake failure
fake_failure = False fake_failure = False
if os.path.exists('/root/fake_megaraid_failure'): if os.path.exists("/root/fake_megaraid_failure"):
fake_failure = True fake_failure = True
cmd = binarypath+' -v' cmd = binarypath + " -v"
output = getOutput(cmd) output = getOutput(cmd)
disklist = returnDiskList(output) disklist = returnDiskList(output)
arraylist = returnArrayList(output) arraylist = returnArrayList(output)
if printarray: if printarray:
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID | Type | Size | Status' print "-- ID | Type | Size | Status"
for array in arraylist: for array in arraylist:
print array[0]+' | '+array[2]+' '+array[3]+' | '+array[1]+' | '+array[-1] print array[0] + " | " + array[2] + " " + array[3] + " | " + array[1] + " | " + array[-1]
print '' print ""
print '-- Disks informations' print "-- Disks informations"
print '-- ID | Model | Status | Warnings' print "-- ID | Model | Status | Warnings"
for disk in disklist: for disk in disklist:
# Check if there's some smart non critical warnings # Check if there's some smart non critical warnings
if re.match(r'^errs:.*$', disk[-2]): if re.match(r"^errs:.*$", disk[-2]):
# Some disk may have vendor or model containing spaces # Some disk may have vendor or model containing spaces
print disk[0]+' | '+' '.join(disk[1:-3])+' | '+disk[-1]+' | '+disk[-2] print disk[0] + " | " + " ".join(disk[1:-3]) + " | " + disk[-1] + " | " + disk[-2]
else: else:
print disk[0]+' | '+' '.join(disk[1:-2])+' | '+disk[-1] print disk[0] + " | " + " ".join(disk[1:-2]) + " | " + disk[-1]
# Check if there's a bad disk # Check if there's a bad disk
bad = False bad = False
for array in arraylist: for array in arraylist:
if not array[-1] == 'optimal': if not array[-1] == "optimal":
bad = True bad = True
for disk in disklist: for disk in disklist:
if disk[-1] not in [ 'online', 'hotspare', 'ready' ]: if disk[-1] not in ["online", "hotspare", "ready"]:
bad = True bad = True
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
sys.exit(1) sys.exit(1)

View File

@ -7,99 +7,102 @@ import sys
binarypath = "/usr/sbin/megasasctl" binarypath = "/usr/sbin/megasasctl"
if len(sys.argv) > 2: if len(sys.argv) > 2:
print 'Usage: megaraidsas-status [-d]' print "Usage: megaraidsas-status [-d]"
sys.exit(1) sys.exit(1)
printarray = True printarray = True
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[1] == '-d': if sys.argv[1] == "-d":
printarray = False printarray = False
else: else:
print 'Usage: megaraidsas-status [-d]' print "Usage: megaraidsas-status [-d]"
sys.exit(1) sys.exit(1)
# Check binary exists (and +x), if not print an error message # Check binary exists (and +x), if not print an error message
if os.path.exists(binarypath) and os.access(binarypath, os.X_OK): if os.path.exists(binarypath) and os.access(binarypath, os.X_OK):
pass pass
else: else:
sys.exit(3) sys.exit(3)
# Get command output # Get command output
def getOutput(cmd): def getOutput(cmd):
output = os.popen(cmd) output = os.popen(cmd)
lines = [] lines = []
for line in output: for line in output:
if not re.match(r'^$',line.strip()): if not re.match(r"^$", line.strip()):
lines.append(line.strip()) lines.append(line.strip())
return lines return lines
def returnDiskList(output): def returnDiskList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[a-z][0-9]+[a-z][0-9\*]+[a-z][0-9]+\s.*$',line.strip()): if re.match(r"^[a-z][0-9]+[a-z][0-9\*]+[a-z][0-9]+\s.*$", line.strip()):
list = line.split() list = line.split()
# Let's hack... Some disk may report smart error after status # Let's hack... Some disk may report smart error after status
# Get theses errors, join them into one list item and place it # Get theses errors, join them into one list item and place it
# before status # before status
errindex = False errindex = False
try: try:
errindex = list.index('errs:') errindex = list.index("errs:")
except ValueError: except ValueError:
pass pass
if errindex: if errindex:
list.insert(errindex-1, ' '.join(list[errindex:])) list.insert(errindex - 1, " ".join(list[errindex:]))
list = list[:errindex+1] list = list[: errindex + 1]
lines.append(list) lines.append(list)
if fake_failure: if fake_failure:
lines[0][-1] = 'BAD' lines[0][-1] = "BAD"
return lines return lines
def returnArrayList(output): def returnArrayList(output):
lines = [] lines = []
for line in output: for line in output:
if re.match(r'^[a-z][0-9]+[a-z][0-9]+\s.*$',line.strip()): if re.match(r"^[a-z][0-9]+[a-z][0-9]+\s.*$", line.strip()):
lines.append(line.split()) lines.append(line.split())
if fake_failure: if fake_failure:
lines[0][-1] = 'DEGRADED' lines[0][-1] = "DEGRADED"
return lines return lines
# A way to force a fake failure # A way to force a fake failure
fake_failure = False fake_failure = False
if os.path.exists('/root/fake_megaraid_failure'): if os.path.exists("/root/fake_megaraid_failure"):
fake_failure = True fake_failure = True
cmd = binarypath+' -v' cmd = binarypath + " -v"
output = getOutput(cmd) output = getOutput(cmd)
disklist = returnDiskList(output) disklist = returnDiskList(output)
arraylist = returnArrayList(output) arraylist = returnArrayList(output)
if printarray: if printarray:
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID | Type | Size | Status' print "-- ID | Type | Size | Status"
for array in arraylist: for array in arraylist:
print array[0]+' | '+array[2]+' '+array[3]+' | '+array[1]+' | '+array[-1] print array[0] + " | " + array[2] + " " + array[3] + " | " + array[1] + " | " + array[-1]
print '' print ""
print '-- Disks informations' print "-- Disks informations"
print '-- ID | Model | Status | Warnings' print "-- ID | Model | Status | Warnings"
for disk in disklist: for disk in disklist:
# Check if there's some smart non critical warnings # Check if there's some smart non critical warnings
if re.match(r'^errs:.*$', disk[-2]): if re.match(r"^errs:.*$", disk[-2]):
# Some disk may have vendor or model containing spaces # Some disk may have vendor or model containing spaces
print disk[0]+' | '+' '.join(disk[1:-3])+' | '+disk[-1]+' | '+disk[-2] print disk[0] + " | " + " ".join(disk[1:-3]) + " | " + disk[-1] + " | " + disk[-2]
else: else:
print disk[0]+' | '+' '.join(disk[1:-2])+' | '+disk[-1] print disk[0] + " | " + " ".join(disk[1:-2]) + " | " + disk[-1]
# Check if there's a bad disk # Check if there's a bad disk
bad = False bad = False
for array in arraylist: for array in arraylist:
if not array[-1] == 'optimal': if not array[-1] == "optimal":
bad = True bad = True
for disk in disklist: for disk in disklist:
if disk[-1] not in [ 'online', 'hotspare', 'ready' ]: if disk[-1] not in ["online", "hotspare", "ready"]:
bad = True bad = True
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
sys.exit(1) sys.exit(1)

View File

@ -6,174 +6,186 @@ import sys
binarypath = "/usr/sbin/sas2ircu" binarypath = "/usr/sbin/sas2ircu"
if not os.path.isfile(binarypath): if not os.path.isfile(binarypath):
print 'sas2ircu is not available in expected location: {}'.format(binarypath) print "sas2ircu is not available in expected location: {}".format(binarypath)
sys.exit(1)
if len(sys.argv) > 2:
print 'Usage: sas2ircu-status [--nagios]'
sys.exit(1)
nagiosmode=False
nagiosoutput=''
nagiosgoodarray=0
nagiosbadarray=0
nagiosgooddisk=0
nagiosbaddisk=0
if len(sys.argv) > 1:
if sys.argv[1] == '--nagios':
nagiosmode=True
else:
print 'Usage: sas2ircu-status [--nagios]'
sys.exit(1) sys.exit(1)
bad=False if len(sys.argv) > 2:
print "Usage: sas2ircu-status [--nagios]"
sys.exit(1)
nagiosmode = False
nagiosoutput = ""
nagiosgoodarray = 0
nagiosbadarray = 0
nagiosgooddisk = 0
nagiosbaddisk = 0
if len(sys.argv) > 1:
if sys.argv[1] == "--nagios":
nagiosmode = True
else:
print "Usage: sas2ircu-status [--nagios]"
sys.exit(1)
bad = False
# Get command output # Get command output
def getOutput(cmd): def getOutput(cmd):
output=os.popen(cmd+' 2>/dev/null') output = os.popen(cmd + " 2>/dev/null")
lines=[] lines = []
for line in output: for line in output:
if not re.match(r'^$',line.strip()): if not re.match(r"^$", line.strip()):
lines.append(line.strip()) lines.append(line.strip())
return lines return lines
def getCtrlList(): def getCtrlList():
cmd=binarypath+' LIST' cmd = binarypath + " LIST"
res=getOutput(cmd) res = getOutput(cmd)
list = [] list = []
for line in res: for line in res:
if re.match('^[0-9]+.*$',line): if re.match("^[0-9]+.*$", line):
ctrlnmbr,ctrlname=int(line.split()[0]),line.split()[1] ctrlnmbr, ctrlname = int(line.split()[0]), line.split()[1]
# Check if it's a RAID controller and a volume exists # Check if it's a RAID controller and a volume exists
cmd=binarypath+' '+str(ctrlnmbr)+' DISPLAY' cmd = binarypath + " " + str(ctrlnmbr) + " DISPLAY"
res=getOutput(cmd) res = getOutput(cmd)
raid=False raid = False
validarray=False validarray = False
for line in res: for line in res:
if re.match('^RAID Support\s+:\s+Yes$',line): if re.match("^RAID Support\s+:\s+Yes$", line):
raid=True raid = True
if re.match('^IR volume [0-9]+.*$',line): if re.match("^IR volume [0-9]+.*$", line):
validarray=True validarray = True
if raid and validarray: if raid and validarray:
list.append([ctrlnmbr,ctrlname]) list.append([ctrlnmbr, ctrlname])
# ie: [['0', 'SAS2008']] # ie: [['0', 'SAS2008']]
return list return list
def getArrayList(ctrlnmbr): def getArrayList(ctrlnmbr):
cmd=binarypath+' '+str(ctrlnmbr)+' DISPLAY' cmd = binarypath + " " + str(ctrlnmbr) + " DISPLAY"
res=getOutput(cmd) res = getOutput(cmd)
list=[] list = []
disklist=[] disklist = []
arrayid=-1 arrayid = -1
arraystatus='' arraystatus = ""
raidlevel='' raidlevel = ""
size='' size = ""
for line in res: for line in res:
if re.match('^IR volume [0-9]+.*$',line): if re.match("^IR volume [0-9]+.*$", line):
if arrayid == -1: if arrayid == -1:
arrayid=arrayid+1 arrayid = arrayid + 1
else: else:
list.append([arrayid,raidlevel,size,arraystatus,disklist]) list.append([arrayid, raidlevel, size, arraystatus, disklist])
arrayid=arrayid+1 arrayid = arrayid + 1
disklist=[] disklist = []
if re.match('Status of volume.*$',line): if re.match("Status of volume.*$", line):
arraystatus=line.split(':')[1].strip() arraystatus = line.split(":")[1].strip()
if re.match('RAID level.*$',line): if re.match("RAID level.*$", line):
raidlevel=line.split(':')[1].strip() raidlevel = line.split(":")[1].strip()
if re.match('Size \(in MB\)\s+.*$',line): if re.match("Size \(in MB\)\s+.*$", line):
size=line.split(':')[1].strip() size = line.split(":")[1].strip()
size=str(int(round((float(size) / 1000))))+'G' size = str(int(round((float(size) / 1000)))) + "G"
if re.match('^PHY\[[0-9]+\] Enclosure#/Slot#.*$',line): if re.match("^PHY\[[0-9]+\] Enclosure#/Slot#.*$", line):
disksid=':'.join(line.split(':')[1:]).strip() disksid = ":".join(line.split(":")[1:]).strip()
disksid=disksid.split(':') disksid = disksid.split(":")
disklist.append(disksid) disklist.append(disksid)
list.append([arrayid,raidlevel,size,arraystatus,disklist]) list.append([arrayid, raidlevel, size, arraystatus, disklist])
# ie: [0, 'Okay (OKY)', 'RAID1', '1800G', [['1', '0'], ['1', '1']]] # ie: [0, 'Okay (OKY)', 'RAID1', '1800G', [['1', '0'], ['1', '1']]]
return list return list
def getDiskList(ctrlnmbr): def getDiskList(ctrlnmbr):
cmd=binarypath+' '+str(ctrlnmbr)+' DISPLAY' cmd = binarypath + " " + str(ctrlnmbr) + " DISPLAY"
res=getOutput(cmd) res = getOutput(cmd)
list=[] list = []
diskid=-1 diskid = -1
diskstatus='' diskstatus = ""
diskmodel='' diskmodel = ""
diskserial='' diskserial = ""
enclid='' enclid = ""
slotid='' slotid = ""
realid=['',''] realid = ["", ""]
for line in res: for line in res:
if re.match('^Device is a Hard disk.*$',line) or re.match('^Device is a Enclosure services device.*$',line) or re.match('^Device is a unknown device.*$',line): if (
if diskid == -1: re.match("^Device is a Hard disk.*$", line)
diskid=diskid+1 or re.match("^Device is a Enclosure services device.*$", line)
else: or re.match("^Device is a unknown device.*$", line)
list.append([diskid,diskstatus,diskmodel,diskserial,realid]) ):
diskid=diskid+1 if diskid == -1:
if re.match('Enclosure #.*$',line): diskid = diskid + 1
enclid=line.split(':')[1].strip() else:
if re.match('Slot #.*$',line): list.append([diskid, diskstatus, diskmodel, diskserial, realid])
slotid=line.split(':')[1].strip() diskid = diskid + 1
realid=[enclid,slotid] if re.match("Enclosure #.*$", line):
if re.match('^State.*$',line): enclid = line.split(":")[1].strip()
diskstatus=line.split(':')[1].strip() if re.match("Slot #.*$", line):
if re.match('^Model Number.*$',line): slotid = line.split(":")[1].strip()
diskmodel=line.split(':')[1].strip() realid = [enclid, slotid]
if re.match('^Serial No.*$',line): if re.match("^State.*$", line):
diskserial=line.split(':')[1].strip() diskstatus = line.split(":")[1].strip()
# ie: [[0, 'Optimal (OPT)', 'Hitachi HUA72202', 'JK1151YAHUYAZZ', ['1', '0']], [1, 'Optimal (OPT)', 'Hitachi HUA72202', 'JK1151YAHUW1DZ', ['1', '1']]] if re.match("^Model Number.*$", line):
list.append([diskid,diskstatus,diskmodel,diskserial,realid]) diskmodel = line.split(":")[1].strip()
return list if re.match("^Serial No.*$", line):
diskserial = line.split(":")[1].strip()
# ie: [[0, 'Optimal (OPT)', 'Hitachi HUA72202', 'JK1151YAHUYAZZ', ['1', '0']], [1, 'Optimal (OPT)', 'Hitachi HUA72202', 'JK1151YAHUW1DZ', ['1', '1']]]
list.append([diskid, diskstatus, diskmodel, diskserial, realid])
return list
ctrls=getCtrlList()
arraymap={} ctrls = getCtrlList()
arraymap = {}
if not nagiosmode: if not nagiosmode:
print '-- Controller informations --' print "-- Controller informations --"
print '-- ID | Model' print "-- ID | Model"
for ctrl in ctrls: for ctrl in ctrls:
print 'c'+str(ctrl[0])+' | '+ctrl[1] print "c" + str(ctrl[0]) + " | " + ctrl[1]
print '' print ""
if not nagiosmode: if not nagiosmode:
print '-- Arrays informations --' print "-- Arrays informations --"
print '-- ID | Type | Size | Status' print "-- ID | Type | Size | Status"
for ctrl in ctrls: for ctrl in ctrls:
for array in getArrayList(ctrl[0]): for array in getArrayList(ctrl[0]):
arraymap[ctrl[0]]=array arraymap[ctrl[0]] = array
if not array[3] in ['Okay (OKY)', 'Inactive, Okay (OKY)']: if not array[3] in ["Okay (OKY)", "Inactive, Okay (OKY)"]:
bad=True bad = True
nagiosbadarray=nagiosbadarray+1 nagiosbadarray = nagiosbadarray + 1
else: else:
nagiosgoodarray=nagiosgoodarray+1 nagiosgoodarray = nagiosgoodarray + 1
if not nagiosmode: if not nagiosmode:
print 'c'+str(ctrl[0])+'u'+str(array[0])+' | '+array[1]+' | '+array[2]+' | '+array[3] print "c" + str(ctrl[0]) + "u" + str(array[0]) + " | " + array[1] + " | " + array[2] + " | " + array[3]
if not nagiosmode: if not nagiosmode:
print '' print ""
if not nagiosmode: if not nagiosmode:
print '-- Disks informations' print "-- Disks informations"
print '-- ID | Model | Status' print "-- ID | Model | Status"
for ctrl in ctrls: for ctrl in ctrls:
for disk in getDiskList(ctrl[0]): for disk in getDiskList(ctrl[0]):
# Compare disk enc/slot to array's ones # Compare disk enc/slot to array's ones
for array in [arraymap.get(ctrl[0])]: for array in [arraymap.get(ctrl[0])]:
for arraydisk in array[4]: for arraydisk in array[4]:
if arraydisk == disk[4]: if arraydisk == disk[4]:
if not disk[1] == 'Optimal (OPT)': if not disk[1] == "Optimal (OPT)":
bad=True bad = True
nagiosbaddisk=nagiosbaddisk+1 nagiosbaddisk = nagiosbaddisk + 1
else: else:
nagiosgooddisk=nagiosgooddisk+1 nagiosgooddisk = nagiosgooddisk + 1
if not nagiosmode: if not nagiosmode:
print 'c'+str(ctrl[0])+'u'+str(array[0])+'p'+str(disk[0])+' | '+disk[2]+' ('+disk[3]+') | '+disk[1] print "c" + str(ctrl[0]) + "u" + str(array[0]) + "p" + str(disk[0]) + " | " + disk[2] + " (" + disk[3] + ") | " + disk[1]
if nagiosmode: if nagiosmode:
if bad: if bad:
print 'RAID ERROR - Arrays: OK:'+str(nagiosgoodarray)+' Bad:'+str(nagiosbadarray)+' - Disks: OK:'+str(nagiosgooddisk)+' Bad:'+str(nagiosbaddisk) print "RAID ERROR - Arrays: OK:" + str(nagiosgoodarray) + " Bad:" + str(nagiosbadarray) + " - Disks: OK:" + str(nagiosgooddisk) + " Bad:" + str(
sys.exit(2) nagiosbaddisk
else: )
print 'RAID OK - Arrays: OK:'+str(nagiosgoodarray)+' Bad:'+str(nagiosbadarray)+' - Disks: OK:'+str(nagiosgooddisk)+' Bad:'+str(nagiosbaddisk) sys.exit(2)
else:
print "RAID OK - Arrays: OK:" + str(nagiosgoodarray) + " Bad:" + str(nagiosbadarray) + " - Disks: OK:" + str(nagiosgooddisk) + " Bad:" + str(
nagiosbaddisk
)
else: else:
if bad: if bad:
print '\nThere is at least one disk/array in a NOT OPTIMAL state.' print "\nThere is at least one disk/array in a NOT OPTIMAL state."
sys.exit(1) sys.exit(1)