Write a python service monitoring program

Source: Internet
Author: User
Tags python subprocess

Write a python service monitoring program

Preface:

Install Python2.7 in Redhat

Rhel6.4 comes with 2.6, and some machines are found to be python2.4. Download the source code from the python website, decompress it to Redhat, and then run the following command:

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

# Make

# Make install

After installation, Python2.7 is not enabled by default. You need to use/usr/local/python27/bin/python2.7 to call the new version of python.

The following installation method directly takes over the existing python

#./Configure

# Make

# Make install

Start:
The service sub-process is created and monitored by the monitored master process. When the sub-process is shut down abnormally, the master process can be started again. Python subprocess module is used. In this simple code, there is no ready-to-use example on the Internet. No way. I have made a contribution.

The first is the main process code: service_mgr.py

#! /Usr/bin/python #-*-coding: UTF-8-*-# cheungmine # stdin, stdout, and stderr indicate the standard input, standard output, and standard error of the subroutine respectively. # Optional values: # subprocess. PIPE-indicates that a new pipeline needs to be created. # A valid file descriptor (in fact, it is a positive integer) # A file object # None-does not perform any redirection, and the file descriptor of the child process inherits from the parent process. # The stderr value can also be STDOUT, indicating that the standard error of the sub-process is also output to the standard output. # subprocess. PIPE # a specific value that can be used by stdin, stdout, and stderr parameters of Popen, indicating that a new pipeline needs to be created. # subprocess. STDOUT # A stderr value that can be used for the Popen parameter, indicating that the standard errors of the subroutine are merged to the standard output. ######################################## ######################################## import osimport sysimport Getoptimport timeimport datetimeimport codecsimport optparseimport ConfigParserimport signalimport subprocessimport select # logging # require python2.6.6 and laterimport logging from logging. handlers import RotatingFileHandler # log settings: shocould be configured by configLOG_PATH_FILE = ". /my_service_mgr.log "LOG_MODE = 'A' LOG _ MAX_SIZE = 4*1024*1024 #4 M per fileLOG_MAX_FILES = 4 #4 Files: my_serv Ice_mgr.log.1, printmy_service_mgrlog.2 ,... LOG_LEVEL = logging. DEBUG LOG_FORMAT = "% (asctime) s % (levelname)-10 s [% (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 [31 m [% d: ERROR] % s \ 033 [31; M' % (pid, s) def print_info (s): print '\ 033 [32 m [% d: INFO] % s \ 033 [32; M' % (pid, s) def print_warning (s ): print '\ 033 [33 m [% 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 stder R child = subprocess. popen (command, stderr = subprocess. STDOUT, # indicates that the standard error of the sub-process is also output to the standard output stdout = subprocess. PIPE # indicates that a new pipeline needs to be created.) else: # do not merge stdout and stderr child = subprocess. popen (command, stderr = subprocess. PIPE, stdout = subprocess. PIPE) return child processing t subprocess. calledProcessError: pass # handle errors in the called executable failed t 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 Nd 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 ("!!! Shocould never run to this !!! ") If _ name _ =" _ main _ ": run_forever ([" python ","./testpipe. py "])
Then the sub-process code: testpipe. py
#! /Usr/bin/python #-*-coding: UTF-8-*-# cheungmine # simulate a woker process, import osimport sysimport timeimport randomcnt = 10 while cnt> = 0: time. sleep (1, 0.5) sys. stdout. write ("OUT: % s \ n" % str (random. randint (1, 100000) sys. stdout. flush () time. sleep (1, 0.5) sys. stderr. write ("ERR: % s \ n" % str (random. randint (1, 100000) sys. stderr. flush () # print str (cnt) # sys. stdout. flush () cnt = cnt-1sys. exit (-1)

$ Python service_mgr.py

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.