#!/usr/bin/python
# -*- coding:utf-8 -*-
from optparse import OptionParser
import subprocess,sys
from datetime import datetime
"""
Nagios plugin to report the mysql QPS
by jastme
"""
try:
f=open('/tmp/qps.txt')
except IOError:
f=open('/tmp/qps.txt','w')
print 'wait next check,initialize the date qps.txt'
finally:
f.close()
try:
f1=open('/tmp/time.txt')
except IOError:
f1=open('/tmp/time.txt','w')
print 'wait next check,initialize the date time.txt'
finally:
f1.close()
parser = OptionParser(usage="%prog -w -c [ -h ]\n\nBefore use the script,please execute 'grant usage on *.* to monitor@'127.0.0.1' identified by 'monitor';\nflush privileges;\non your mysql database",version="%prog ")
parser.add_option("-w", "--warning",action="store", type="string", dest="warn_threshold", help="Warning threshold in percentage")
parser.add_option("-c", "--critical",action="store", type="string", dest="crit_threshold", help="Critical threshold in percentage")
(options, args) = parser.parse_args()
def QPS():
'''mysql qps'''
d=time_delay()
fff=open('/tmp/qps.txt','r')
qpsbefore=fff.read()
fff.close()
now=subprocess.Popen('''mysql -umonitor -pmonitor -h 127.0.0.1 -e "show global status like 'Questions'" | awk 'NR==2{print $2}' ''',shell=True,stdout=subprocess.PIPE)
qpsnow=municate()[0][:-1]
if qpsbefore=='':
pass
else:
mysqlqps=(int(qpsnow)-int(qpsbefore))/int(d)
return mysqlqps
fffw=open('/tmp/qps.txt','w')
fffw.write(qpsnow)
fffw.close()
def time_delay():
'''Compute the time difference'''
time_now=datetime.now()
ff=open('/tmp/time.txt','r')
time_before_str=ff.read()
ff.close()
if time_before_str=='':
pass
else:
time_before=datetime.strptime(time_before_str,"%Y-%m-%d %H:%M:%S.%f")
delay=(time_now-time_before).seconds
return delay
ffw=open('/tmp/time.txt','w')
print str(time_now)
ffw.write(str(time_now))
ffw.close()
def jastme():
q=QPS()
if not options.crit_threshold:
print "UNKNOWN: Missing critical threshold value."
sys.exit(3)
if not options.warn_threshold:
print "UNKNOWN: Missing warning threshold value."
sys.exit(3)
if q==None:
print 'wait next check,initialize the date'
sys.exit(3)
elif int(q) >= int(options.crit_threshold):
print 'Criticl,The QPS is %s | QPS=%stimes;%s;%s;0' %(q,q,options.warn_threshold,options.crit_threshold)
sys.exit(2)
elif int(options.crit_threshold) > int(q) >= int(options.warn_threshold):
print 'Warning,The QPS is %s | QPS=%stimes;%s;%s;0' %(q,q,options.warn_threshold,options.crit_threshold)
sys.exit(1)
else:
print 'OK,The QPS is %s | QPS=%stimes;%s;%s;0' %(q,q,options.warn_threshold,options.crit_threshold)
sys.exit(0)
if __name__ == '__main__':
jastme()