Python写的服务监控程序实例


Posted in Python onJanuary 31, 2015

前言:

Redhat下安装Python2.7

rhel6.4自带的是2.6, 发现有的机器是python2.4。 到python网站下载源代码,解压到Redhat上,然后运行下面的命令:

# ./configure --prefix=/usr/local/python27

# make

# make install

这样安装之后默认不会启用Python2.7,需要使用/usr/local/python27/bin/python2.7调用新版本的python。

而下面的安装方式会直接接管现有的python

# ./configure

# make

# make install

开始:

服务子进程被监控主进程创建并监控,当子进程异常关闭,主进程可以再次启动之。使用了python的subprocess模块。就这个简单的代码,居然互联网上没有现成可用的例子。没办法,我写好了贡献出来吧。

首先是主进程代码:service_mgr.py

#!/usr/bin/python  

#-*- coding: UTF-8 -*-  

# cheungmine  

# stdin、stdout和stderr分别表示子程序的标准输入、标准输出和标准错误。  

#   

# 可选的值有:  

#   subprocess.PIPE - 表示需要创建一个新的管道.  

#   一个有效的文件描述符(其实是个正整数)  

#   一个文件对象  

#   None - 不会做任何重定向工作,子进程的文件描述符会继承父进程的.  

#   

# stderr的值还可以是STDOUT, 表示子进程的标准错误也输出到标准输出.  

#   

# subprocess.PIPE  

# 一个可以被用于Popen的stdin、stdout和stderr 3个参数的特输值,表示需要创建一个新的管道.  

#   

# subprocess.STDOUT  

# 一个可以被用于Popen的stderr参数的特输值,表示子程序的标准错误汇合到标准输出.  

################################################################################  

import os  

import sys  

import getopt  

  

import time  

import datetime  

  

import codecs  

  

import optparse  

import ConfigParser  

  

import signal  

import subprocess  

import select  

  

# logging  

# require python2.6.6 and later  

import logging    

from logging.handlers import RotatingFileHandler  

  

## log settings: SHOULD BE CONFIGURED BY config  

LOG_PATH_FILE = "./my_service_mgr.log"  

LOG_MODE = 'a'  

LOG_MAX_SIZE = 4*1024*1024 # 4M per file  

LOG_MAX_FILES = 4          # 4 Files: my_service_mgr.log.1, printmy_service_mgrlog.2, ...    

LOG_LEVEL = logging.DEBUG    

  

LOG_FORMAT = "%(asctime)s %(levelname)-10s[%(filename)s:%(lineno)d(%(funcName)s)] %(message)s"    

  

handler = RotatingFileHandler(LOG_PATH_FILE, LOG_MODE, LOG_MAX_SIZE, LOG_MAX_FILES)  

formatter = logging.Formatter(LOG_FORMAT)  

handler.setFormatter(formatter)  

  

Logger = logging.getLogger()  

Logger.setLevel(LOG_LEVEL)  

Logger.addHandler(handler)   

  

# color output  

#  

pid = os.getpid()   

  

def print_error(s):  

    print '\033[31m[%d: ERROR] %s\033[31;m' % (pid, s)  

  

def print_info(s):  

    print '\033[32m[%d: INFO] %s\033[32;m' % (pid, s)  

  

def print_warning(s):  

    print '\033[33m[%d: WARNING] %s\033[33;m' % (pid, s)  

  

  

def start_child_proc(command, merged):  

    try:  

        if command is None:  

            raise OSError, "Invalid command"  

  

        child = None  

  

        if merged is True:  

            # merge stdout and stderr  

            child = subprocess.Popen(command,  

                stderr=subprocess.STDOUT, # 表示子进程的标准错误也输出到标准输出  

                stdout=subprocess.PIPE    # 表示需要创建一个新的管道  

            )  

        else:  

            # DO NOT merge stdout and stderr  

            child = subprocess.Popen(command,  

                stderr=subprocess.PIPE,  

                stdout=subprocess.PIPE)  

  

        return child  

  

    except subprocess.CalledProcessError:  

        pass # handle errors in the called executable  

    except OSError:  

        pass # executable not found  

  

    raise OSError, "Failed to run command!"  

  

  

def run_forever(command):  

    print_info("start child process with command: " + ' '.join(command))  

    Logger.info("start child process with command: " + ' '.join(command))  

  

    merged = False  

    child = start_child_proc(command, merged)  

  

    line = ''  

    errln = ''  

  

    failover = 0  

  

    while True:  

        while child.poll() != None:  

            failover = failover + 1  

            print_warning("child process shutdown with return code: " + str(child.returncode))             

            Logger.critical("child process shutdown with return code: " + str(child.returncode))  

  

            print_warning("restart child process again, times=%d" % failover)  

            Logger.info("restart child process again, times=%d" % failover)  

            child = start_child_proc(command, merged)  

  

        # read child process stdout and log it  

        ch = child.stdout.read(1)  

        if ch != '' and ch != '\n':  

            line += ch  

        if ch == '\n':  

            print_info(line)  

            line = ''  

  

        if merged is not True:  

            # read child process stderr and log it  

            ch = child.stderr.read(1)  

            if ch != '' and ch != '\n':  

                errln += ch  

            if ch == '\n':  

                Logger.info(errln)  

                print_error(errln)  

                errln = ''  

  

    Logger.exception("!!!should never run to this!!!")    

  

  

if __name__ == "__main__":  

    run_forever(["python", "./testpipe.py"]) 

然后是子进程代码:testpipe.py

#!/usr/bin/python  

#-*- coding: UTF-8 -*-  

# cheungmine  

# 模拟一个woker进程,10秒挂掉  

import os  

import sys  

  

import time  

import random  

  

cnt = 10  

  

while cnt >= 0:  

    time.sleep(0.5)  

    sys.stdout.write("OUT: %s\n" % str(random.randint(1, 100000)))  

    sys.stdout.flush()  

  

    time.sleep(0.5)  

    sys.stderr.write("ERR: %s\n" % str(random.randint(1, 100000)))  

    sys.stderr.flush()  

  

    #print str(cnt)  

    #sys.stdout.flush()  

    cnt = cnt - 1  

  

sys.exit(-1) 

Linux上运行很简单:

$ python service_mgr.py

Windows上以后台进程运行:
> start pythonw service_mgr.py

代码中需要修改:
run_forever(["python", "testpipe.py"]) 
Python 相关文章推荐
Python 学习笔记
Dec 27 Python
python抓取网页内容示例分享
Feb 24 Python
在ironpython中利用装饰器执行SQL操作的例子
May 02 Python
python daemon守护进程实现
Aug 27 Python
python matplotlib折线图样式实现过程
Nov 04 Python
python隐藏类中属性的3种实现方法
Dec 19 Python
关于tf.TFRecordReader()函数的用法解析
Feb 17 Python
Python抓包程序mitmproxy安装和使用过程图解
Mar 02 Python
Python无头爬虫下载文件的实现
Apr 02 Python
Django 实现 Websocket 广播、点对点发送消息的代码
Jun 03 Python
PyCharm设置注释字体颜色以及是否倾斜的操作
Sep 16 Python
OpenCV利用python来实现图像的直方图均衡化
Oct 21 Python
用python 制作图片转pdf工具
Jan 30 #Python
Python是编译运行的验证方法
Jan 30 #Python
Python的类实例属性访问规则探讨
Jan 30 #Python
Python中的作用域规则详解
Jan 30 #Python
Python中使用Boolean操作符做真值测试实例
Jan 30 #Python
Python中的zip函数使用示例
Jan 29 #Python
Python的另外几种语言实现
Jan 29 #Python
You might like
两种php调用Java对象的方法
2006/10/09 PHP
PHP 反射(Reflection)使用实例
2015/05/12 PHP
Yii中表单用法实例详解
2016/01/05 PHP
Yii视图操作之自定义分页实现方法
2016/07/14 PHP
file模式访问网页时iframe高度自适应解决方案
2013/01/16 Javascript
仿百度的关键词匹配搜索示例
2013/09/25 Javascript
Jquery选中或取消radio示例
2013/09/29 Javascript
使用coffeescript编写node.js项目的方法汇总
2015/08/05 Javascript
JavaScript如何动态创建table表格
2020/08/02 Javascript
jQuery实现简洁的轮播图效果实例
2016/09/07 Javascript
IntersectionObserver API 详解篇
2016/12/11 Javascript
D3.js进阶系列之CSV表格文件的读取详解
2017/06/06 Javascript
Vue使用vue-cli创建项目
2017/09/01 Javascript
angular中ui calendar的一些使用心得(推荐)
2017/11/03 Javascript
记录一篇关于redux-saga的基本使用过程
2018/08/18 Javascript
用VueJS写一个Chrome浏览器插件的实现方法
2019/02/27 Javascript
[49:54]Ti4 循环赛第三日 LGD vs Titan
2014/07/12 DOTA
[44:40]2018DOTA2亚洲邀请赛3月30日 小组赛A组Liquid VS OG
2018/03/31 DOTA
基于Python的关键字监控及告警
2017/07/06 Python
Python写一个基于MD5的文件监听程序
2019/03/11 Python
Python 的字典(Dict)是如何存储的
2019/07/05 Python
Django项目基础配置和基本使用过程解析
2019/11/25 Python
django框架基于queryset和双下划线的跨表查询操作详解
2019/12/11 Python
Pytorch实现各种2d卷积示例
2019/12/30 Python
Pytorch实现基于CharRNN的文本分类与生成示例
2020/01/08 Python
美国珠宝网上商店:Jeulia
2016/09/01 全球购物
匈牙利最大的健身制造商和销售商:inSPORTline
2018/10/30 全球购物
Seavenger官网:潜水服、浮潜、靴子和袜子
2020/03/05 全球购物
出生公证书样本
2014/04/04 职场文书
乡村教师党员四风问题对照检查材料思想汇报
2014/10/08 职场文书
2015中学学校工作总结
2015/07/20 职场文书
2016年寒假社会实践活动总结
2015/10/10 职场文书
《植物妈妈有办法》教学反思
2016/02/23 职场文书
个人的事迹材料怎么写
2019/04/24 职场文书
导游词之唐山景点
2019/12/18 职场文书
Apache Calcite 实现方言转换的代码
2021/04/24 Servers