python编写windows tomcat守护进程

2016年10月9日 发表评论 阅读评论

在上一篇 windows下bat curl实现tomcat进程守护 中,根据几年前写的bat deamon程序乱改了下,实现了tomcat deamon的功能,在这篇最后也提到python实现起来,要更强大和智能的多。本篇就来一个基于python实现的功能更强大的tomcat 守护进程。目前实现的功能:

1、通过性更强 ---通过修改config文件即可实现对其他tomcat程序的守护;

2、具有日志查看 --- 轮询30个日志文件;

3、无需借助curl 等工具或安装其他环境 ---借助py2exe可以将python脚本可以生成exe文件;

代码如下:

#!-*- encoding: utf-8 -*-
# code by yangbk
# mysite: www.361way.com
import urllib2
import logging
import os
import time
from ConfigParser import ConfigParser
from logging.handlers import TimedRotatingFileHandler
LOG_FILE = "./logs/output.log"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = TimedRotatingFileHandler(LOG_FILE,when='midnight',interval=1,backupCount=7)   //每天
datefmt = '%Y-%m-%d %H:%M:%S'
format_str = '%(asctime)s %(levelname)s %(message)s '
formatter = logging.Formatter(format_str, datefmt)
fh.setFormatter(formatter)
fh.suffix = "%Y%m%d%H%M"
logger.addHandler(fh)
def getUrlcode(url):
    try:
        start = time.time()
        response = urllib2.urlopen(url,timeout=10)
        msg = 'httpcode is : ' + str(response.getcode()) + ' - open use time :' + str((time.time()-start)*1000) + 'ms'
        logging.info(msg)
        return response.getcode()
    except urllib2.URLError as e:
        msg = 'open url error ,reason is:' + str(e.reason)
        logging.info(msg)
def get(field, key):
    result = ""
    try:
        result = cf.get(field, key)
    except:
        result = ""
    return result
def read_config(config_file_path, field, key):
    cf = ConfigParser()
    try:
        cf.read(config_file_path)
        result = cf.get(field, key)
    except:
        sys.exit(1)
    return result
CONFIGFILE='./cfg/config.ini'
os.environ["JAVA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','JAVA_HOME')
os.environ["CATALINA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','CATALINA_HOME')
ProgramPath = read_config(CONFIGFILE,'MonitorProgram','StartPath')
ProcessName = read_config(CONFIGFILE,'MonitorProcessName','ProcessName')
url = read_config(CONFIGFILE,'MonitorUrl','Url')
#url = "http://dh.361way.com/"
while True:
    HttpCode = getUrlcode(url)
    if HttpCode is not 200:
         command = 'taskkill /F /FI "WINDOWSTITLE eq ' + ProcessName + '"'
         os.system(command)
         os.system(ProgramPath)
    time.sleep(30)

config.ini文件的内容如下:

[MonitorProgram]
StartPath: C:/tomcat/bin/startup.bat
CATALINA_HOME: C:\\tomcat\\
JAVA_HOME: C:\\Program Files\\Java\\jdk1.8.0_31
[MonitorProcessName]
ProcessName: tomcat_8080
[MonitorUrl]
Url: http://127.0.0.1:8080

以上代码如果仅仅只针对单个应用,代码可以更简洁,因为配置文件部分可以不通过configparse模块进行读取 。而且这里对configparse模块进行了重新处理(get函数与read_config函数),避免获取的key不存在时,出现的报错情况。具体出错时的报错见下图:

configparser

产生的日志文件内容如下:

2016-10-09 15:08:30 INFO open url error ,reason is:[Errno 10061]
2016-10-09 15:09:00 INFO httpcode is 200 - open url use time 111.999988556ms
2016-10-09 15:09:30 INFO httpcode is 200 - open url use time 7.99989700317ms
2016-10-09 15:10:00 INFO httpcode is 200 - open url use time 6.00004096167ms

除此之外,还可以增加邮件通知功能,具体可以参考:python邮件发送模块

代码稍作修改,也可以很方便的通过端口检测确认业务是否健康,端口检测的脚本内容如下:

import os
import socket
def IsOpen(ip,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        print '%d is open' % port
        return True
    except:
        print '%d is down' % port
        return False
if __name__ == '__main__':
    IsOpen('127.0.0.1',800)




本站的发展离不开您的资助,金额随意,欢迎来赏!

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.