python编写windows tomcat守护进程
在上一篇 windows下bat curl实现tomcat进程守护 中,根据几年前写的bat deamon程序乱改了下,实现了tomcat deamon的功能,在这篇最后也提到python实现起来,要更强大和智能的多。本篇就来一个基于python实现的功能更强大的tomcat 守护进程。目前实现的功能:
1、通过性更强 ---通过修改config文件即可实现对其他tomcat程序的守护;
2、具有日志查看 --- 轮询30个日志文件;
3、无需借助curl 等工具或安装其他环境 ---借助py2exe可以将python脚本可以生成exe文件;
代码如下:
1#!-*- encoding: utf-8 -*-
2# code by yangbk
3# mysite: www.361way.com
4import urllib2
5import logging
6import os
7import time
8from ConfigParser import ConfigParser
9from logging.handlers import TimedRotatingFileHandler
10LOG_FILE = "./logs/output.log"
11logger = logging.getLogger()
12logger.setLevel(logging.INFO)
13fh = TimedRotatingFileHandler(LOG_FILE,when='midnight',interval=1,backupCount=7) //每天
14datefmt = '%Y-%m-%d %H:%M:%S'
15format_str = '%(asctime)s %(levelname)s %(message)s '
16formatter = logging.Formatter(format_str, datefmt)
17fh.setFormatter(formatter)
18fh.suffix = "%Y%m%d%H%M"
19logger.addHandler(fh)
20def getUrlcode(url):
21 try:
22 start = time.time()
23 response = urllib2.urlopen(url,timeout=10)
24 msg = 'httpcode is : ' + str(response.getcode()) + ' - open use time :' + str((time.time()-start)*1000) + 'ms'
25 logging.info(msg)
26 return response.getcode()
27 except urllib2.URLError as e:
28 msg = 'open url error ,reason is:' + str(e.reason)
29 logging.info(msg)
30def get(field, key):
31 result = ""
32 try:
33 result = cf.get(field, key)
34 except:
35 result = ""
36 return result
37def read_config(config_file_path, field, key):
38 cf = ConfigParser()
39 try:
40 cf.read(config_file_path)
41 result = cf.get(field, key)
42 except:
43 sys.exit(1)
44 return result
45CONFIGFILE='./cfg/config.ini'
46os.environ["JAVA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','JAVA_HOME')
47os.environ["CATALINA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','CATALINA_HOME')
48ProgramPath = read_config(CONFIGFILE,'MonitorProgram','StartPath')
49ProcessName = read_config(CONFIGFILE,'MonitorProcessName','ProcessName')
50url = read_config(CONFIGFILE,'MonitorUrl','Url')
51#url = "http://dh.361way.com/"
52while True:
53 HttpCode = getUrlcode(url)
54 if HttpCode is not 200:
55 command = 'taskkill /F /FI "WINDOWSTITLE eq ' + ProcessName + '"'
56 os.system(command)
57 os.system(ProgramPath)
58 time.sleep(30)
config.ini文件的内容如下:
1[MonitorProgram]
2StartPath: C:/tomcat/bin/startup.bat
3CATALINA_HOME: C:\\tomcat\\
4JAVA_HOME: C:\\Program Files\\Java\\jdk1.8.0_31
5[MonitorProcessName]
6ProcessName: tomcat_8080
7[MonitorUrl]
8Url: http://127.0.0.1:8080
以上代码如果仅仅只针对单个应用,代码可以更简洁,因为配置文件部分可以不通过configparse模块进行读取 。而且这里对configparse模块进行了重新处理(get函数与read_config函数),避免获取的key不存在时,出现的报错情况。具体出错时的报错见下图:
产生的日志文件内容如下:
12016-10-09 15:08:30 INFO open url error ,reason is:[Errno 10061]
22016-10-09 15:09:00 INFO httpcode is 200 - open url use time 111.999988556ms
32016-10-09 15:09:30 INFO httpcode is 200 - open url use time 7.99989700317ms
42016-10-09 15:10:00 INFO httpcode is 200 - open url use time 6.00004096167ms
除此之外,还可以增加邮件通知功能,具体可以参考:python邮件发送模块
代码稍作修改,也可以很方便的通过端口检测确认业务是否健康,端口检测的脚本内容如下:
1import os
2import socket
3def IsOpen(ip,port):
4 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
5 try:
6 s.connect((ip,int(port)))
7 s.shutdown(2)
8 print '%d is open' % port
9 return True
10 except:
11 print '%d is down' % port
12 return False
13if __name__ == '__main__':
14 IsOpen('127.0.0.1',800)
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-tomcat-deamon/5235.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.