#!/usr/bin/env python

#-*-coding:utf8-*-

"""

   FUN: Monitor Raid Stat

"""



import os ,time ,sys, traceback,commands,subprocess




def oper_log(log_name,item,info):

   path  = '/tmp/'

   stime = time.strftime('%Y-%m-%d %H:%M:%S')

   formats= '[%s] %s:: %s \n' % (stime,item,info)

   if not os.path.exists(path):

       os.mkdir(path)

   try:

       if log_name.split('.')[1] == 'log':

           fp = open(path + log_name,'a')

       elif log_name.split('.')[1] == 'info':

           fp = open(path + log_name,'w')

       else:

           fp = open(path + log_name,'a')

       fp.write(formats)

       fp.close()

   except Exception,e:

       pass


def _exec(cmds):

   try:

       sps = subprocess.Popen(cmds, stdin = subprocess.PIPE,

                                   stdout = subprocess.PIPE,

                                   stderr = subprocess.PIPE,

                                   shell = True)

       sps.wait()

       return sps.stdout.read().strip()

   except:

       oper_log('raid_monitor.log','_exec',traceback.format_exc())

       return ''




def disk_online():

   ''' Getting raid online stat '''

   try:

       cmds = 'megacli  -PDList -aALL | grep Online | wc -l'

       return  _exec(cmds)

   except:

       oper_log('raid_monitor.log','disk_online',traceback.format_exc())

       return ''


def disk_failed():

   try:

       cmds = "megacli -AdpAllInfo -a0 |grep 'Failed Disks'|awk '{print $4}'"

       res = _exec(cmds)

       return res

   except:

       print traceback.format_exc()

       #oper_log('raid_monitor.log','disk_failed',traceback.format_exc())

       return ''


def disk_badSectors():

   turl_num = []

   fail_num = []

   try:

       cmds = "megacli  -PDList -aALL|grep Other|awk '{print $4}'"

       res =  _exec(cmds).split('\n')

       for  i in res:

           i = int(i)

           if i != 0:

               fail_num.append(i)

           else:

               turl_num.append(i)

       return len(fail_num)

   except:

       oper_log('raid_monitor.log','disk_badSectors',traceback.format_exc())

       return ''


def work():


   try:

       if sys.argv[1] == 'disk_online':

           print disk_online()

       elif sys.argv[1] == 'disk_failed':

           print disk_failed()

       elif sys.argv[1] == 'disk_badSectors':


           print disk_badSectors()

       elif sys.argv[1] == 'all':

           print disk_online(),disk_failed(),disk_badSectors()

       else:

           print "Please enter the correct parameters, thank you!"

   except IndexError,e:

       print "Please enter the correct parameters, thank you: --- --- --- "




if __name__ == "__main__":

   st = work()