#!/usr/bin/python DESCRIPTION='''check disk usage, stand alone command line tool and module for monitoring framework''' USAGE='no command line options at this time, just execute it and watch the output' SENSOR_SHELL_COMMAND='df' ALERT_CRITERIA=85 #minimum this % usage -> alert import re,os,sys def main(HOST='',TARGETS=[]): #output to stdout/stderr, use exit status to indicate problem EXITSTATUS=0 for report in sensor(HOST,TARGETS): #call sensor from another python app print report['logmessage'] if report['alert']: EXITSTATUS=1 if report.has_key('alertmessage'): sys.stderr.write( report['alertmessage'] + '\n' ) sys.exit(EXITSTATUS) def sensor(HOST='',TARGETS=[]): #call this from another python app to get list of dictionaries disks=[] for disk in getdisks(HOST): if not TARGETS: if re.search('^/', disk['device']): #simple assumption: lines starting with / are local disks disks.append( evaluate_disk(disk) ) elif disk['device'] in TARGETS or disk['mountpoint'] in TARGETS: disks.append( evaluate_disk(disk) ) return disks def evaluate_disk(disk): disk['logmessage']= logmessage( disk['device'],disk['mountpoint'],disk['usage'] ) percentusage= int( re.sub('%','', disk['usage']) ) if percentusage < ALERT_CRITERIA: disk['alert']=0 else: disk['alert']=1 disk['alertmessage']= alertmessage( disk['device'],disk['mountpoint'],disk['usage'] ) return disk def getdisks(HOST=''): disks=[] if not HOST: DF_STD_OUT=os.popen(SENSOR_SHELL_COMMAND).read().strip() else: DF_STD_OUT='' #TODO remote exec through module for dfline in DF_STD_OUT.split('\n')[1:]: #[1:] means throw away first element (first line in this case) disk={} dfline=dfline.strip() dfline=re.sub('\t',' ',dfline) #no tabs as whitespace dfline=re.sub(' *',' ',dfline) #not more than one space as separator disk['device']= dfline.split(' ')[0] disk['mountpoint']= dfline.split(' ')[-1] disk['usage']= dfline.split(' ')[-2] disks.append( disk ) return disks def alertmessage(SRC,DST,USAGE): return 'disk nearly full ('+USAGE+'): '+DST+' ('+SRC+')' def logmessage(SRC,DST,USAGE): return USAGE+' usage on '+DST+' ('+SRC+')' if __name__ == "__main__": main()