cat GEngin.py :
#!/usr/bin/env python
# coding=gbk
import sys
import os
import random
import datetime
import time
from time import sleep
def CheckInput():
"Check Input parameters , they should be a pysql file."
print "Usage : python ./" + sys.argv[0]
if not os.path.exists("conf/metrix.cfg"):
print "Error : config file conf/metrix.cfg does not exsits ! "
sys.exit()
## kill previous proc For restart
if os.path.exists("pid/pid.txt"):
pfile = open("pid/pid.txt",'r')
for p in pfile:
pid = p.strip()
os.system("kill -9 "+pid)
pfile.close()
os.system("rm pid/pid.txt")
pfile = open("pid/pid.txt",'a')
pid = os.getpid()
pfile.write(str(pid))
pfile.close()
if __name__== '__main__':
CheckInput() # check parameter and asign PyFileName
LogFile = open("log/"+sys.argv[0]+".log",'a')
# File Prefix of logs
filePre="noTask"
for fi in os.listdir("flag"):
if fi.endswith(".flag"):
filePre=fi.split('.')[0].strip()
# host name for gmetrix
host=""
f = os.popen("hostname")
for res in f:
if res.startswith("tdw"):
host=res.strip()
LogFile.write("******** Start task "+filePre+" monitoring ******* ")
# Main Loop untile flag is null
while True:
if len(os.listdir("flag")) < 1 or len(os.listdir("flag")) > 1:
sleep(10)
LogFile.write("Finish previous take "+filePre+"  .... No task ,Main loop ..... ")
LogFile.flush()
continue
if len(os.listdir("flag")) == 1 and not os.path.exists("flag/"+filePre+".flag"):
LogFile.write("Finish previous take "+filePre+"..... ")
for fi in os.listdir("flag"):
if fi.endswith(".flag"):
filePre=fi.split('.')[0].strip()
LogFile.write("***** Start New Task "+filePre+" monitoring ******* ")
# Deal with config metrix one by one
insFile = open("conf/metrix.cfg",'r')
for line in insFile:
mGroup,mName,mItem,mShell,mFile,mUnit,mWeiht,nouse = line.split('|');
outPutFile = filePre+"_"+mGroup+mName+mItem+host+".txt"
value = ""
if mShell.endswith(".py"):
f = os.popen("python script/"+mShell+" "+outPutFile)
for res in f:
if res.startswith("value:"):
value=res.split(':')[1].strip()
else:
value="0"
f.close()
if mShell.endswith(".sh"):
f = os.popen("script/"+mShell+" "+outPutFile)
for res in f:
if res.startswith("value:"):
value=res.split(':')[1].strip()
else:
value="0"
f.close()
cmd = "gmetric -n "+mGroup+"_"+mName+"_"+mItem+" -v "+value+" -t "+mUnit+" -u "+mWeiht+" -S "+host+":"+host
print cmd
f = os.popen(cmd)
ntime = str(time.strftime("%Y-%m-%d %X",time.localtime()))
LogFile.write(ntime+" "+cmd+" ")
insFile.close()
LogFile.flush()
if len(os.listdir("flag")) == 1 and os.path.exists("flag/"+filePre+".flag"):
sleep(8)
LogFile.close()
  Ganglia 中显示的监控指标:
  将运行的GEngin.py脚本加入监控,防止进程异常退出