1. 程式人生 > >檢查伺服器的pid檔案,如果檔案不存在或pid對應的程序已死重啟伺服器

檢查伺服器的pid檔案,如果檔案不存在或pid對應的程序已死重啟伺服器

# -*- coding: utf-8 -*-
# @author flynetcn
import sys, os, re, datetime;

LOG_FILE = '/var/log/www/serverMonitor.log';
SERVER_PID_FILE = '/var/log/www/server.pid';
SERVER_NAME = 'myserver';
START_SERVER_CMD = 'sh /bin/www/service/start.sh';

def logger(level, str):
	logFd = open(LOG_FILE, 'a');
	logFd.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')+": "+("WARNING " if level else "NOTICE ")+str);
	logFd.close();

def startServer():
	import subprocess;
	logger(0, "start server...\n");
	logFd = open(LOG_FILE, 'a');
	ret = subprocess.call([START_SERVER_CMD], shell=True, stdout=logFd, stderr=logFd);
	logFd.close();
	if ret != 0:
		logger(1, "start server failed - %s\n" % (str(ret)));
	else:
		logger(0, "start server ok\n");

def monitorServer():
	try:
		pidFd = open(SERVER_PID_FILE);
		pid = pidFd.readlines();
	except:
		pid = [];
	if not pid:
		logger(1, "pidfile is empty\n");
		startServer();
		return;
	pid = pid[0].strip();
	if not os.access('/proc/'+pid, os.R_OK):
		logger(1, "start server - process(pid:%s) not find\n" % (pid));
		startServer();
		return;
	elif SERVER_NAME not in open('/proc/'+pid+'/cmdline').readline():
		logger(1, "start server - process(pid:%s) is not %s\n" % (pid, SERVER_NAME));
		startServer();
		return;
	else:
		logger(0, "server is running - pid:%s\n" % (pid));
		return;

if __name__ == "__main__":
	monitorServer();