Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1204613
  • 博文数量: 252
  • 博客积分: 5421
  • 博客等级: 大校
  • 技术积分: 2418
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-17 12:59
文章分类

全部博文(252)

文章存档

2017年(3)

2016年(18)

2015年(31)

2014年(18)

2013年(7)

2012年(8)

2011年(12)

2010年(30)

2009年(32)

2008年(57)

2007年(36)

分类: Python/Ruby

2015-08-18 20:36:29


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

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

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

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

  22. def monitorServer():
  23.     try:
  24.         pidFd = open(SERVER_PID_FILE);
  25.         pid = pidFd.readlines();
  26.     except:
  27.         pid = [];
  28.     if not pid:
  29.         logger(1, "pidfile is empty\n");
  30.         startServer();
  31.         return;
  32.     pid = pid[0].strip();
  33.     if not os.access('/proc/'+pid, os.R_OK):
  34.         logger(1, "start server - process(pid:%s) not find\n" % (pid));
  35.         startServer();
  36.         return;
  37.     elif SERVER_NAME not in open('/proc/'+pid+'/cmdline').readline():
  38.         logger(1, "start server - process(pid:%s) is not %s\n" % (pid, SERVER_NAME));
  39.         startServer();
  40.         return;
  41.     else:
  42.         logger(0, "server is running - pid:%s\n" % (pid));
  43.         return;

  44. if __name__ == "__main__":
  45.     monitorServer();

阅读(2141) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~