python守護tomcat

下面腳本實現定時檢測tomcat是否還活着,如果死了就啟動它,如果活太久了(24小時)就殺掉再啟動。

#!/data/pythons/p35/bin/python
# -*- coding: utf8 -*-

#定時任務 /etc/crontab
#*/5 * * * * root (/data/pythons/p36/bin/python /data/pythons/scripts/serviceDeamon.py tomcat-8780)

import psutil,time,datetime,subprocess,sys

def log42(logFile,logText):
    ts = int(time.time())
    dt = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    with open("/tmp/"+dt[0:10]+logFile+".log", "a") as myfile:
        myfile.write(dt+" "+logText+"\n")
        
def startByCmdline(cmdlineKeyword): 
    command = 'export JAVA_HOME=/usr/local/java/jdk1.7.0_71;/bin/sh /data/web/'+cmdlineKeyword+'/bin/startup.sh'
    status,output = subprocess.getstatusoutput(command)
    log42('service'+cmdlineKeyword,"started"+ str(status))
    
def killByCmdline(cmdlineKeyword):    
    alive = False
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name','cmdline','create_time','ppid'])
        except psutil.NoSuchProcess:
            pass
        else:
            if any('/'+cmdlineKeyword in s for s in pinfo['cmdline']):
                alive = True
                aliveTime = time.time()-pinfo['create_time']
                if aliveTime > 60*60*24:        
                    log42('service'+cmdlineKeyword,"old enough "+str(aliveTime/60))
                    p = psutil.Process(pinfo['pid'])
                    p.kill()
                    time.sleep(3)
                    startByCmdline(cmdlineKeyword)
                else:
                    log42('service'+cmdlineKeyword,"too young "+str(aliveTime/60))
            else:
                pass
            
    if not alive :
        log42('service'+cmdlineKeyword,"died")
        startByCmdline(cmdlineKeyword)
                
if __name__ == '__main__':
    #'tomcat-8780'
    if str(sys.argv[1]).__contains__('tomcat') :
        killByCmdline(str(sys.argv[1]))
    else:
        log42('service',"wrong param")
        print('param like:tomcat-8780')

你的電子郵件位址並不會被公開。 必要欄位標記為 *