Write a Python service monitoring program
Objective:
Redhat under Installation Python2.7
rhel6.4 comes with a 2.6, found that some machines are python2.4. Download the source code to the Python site. Unzip to the Redhat. Then execute the following command:
#./configure --prefix=/usr/local/python27
# make
# make Install
Python2.7 is not enabled by default after this installation. You need to use/usr/local/python27/bin/python2.7 to invoke the new version number of Python.
The following installation methods will directly take over the existing Python
#./configure
# make
# make Install
Start:
The service subprocess is created and monitored by the monitoring master process, and the master process can be started again when the child process closes unexpectedly. A Python subprocess module is used. In this simple code, there is no readily available sample on the Internet.
No way. I wrote a good contribution to it.
The first is the main process code: service_mgr.py
#!/usr/bin/python#-*-coding:utf-8-*-# cheungmine# stdin, stdout, and stderr respectively represent standard input, standard output, and standard errors for subroutines. # # Optional values are: # subprocess. Pipe-Represents the need to create a new pipeline. # A valid file descriptive descriptor (in fact a positive integer) # A File object # None-will not do whatever redirection works. The file descriptive descriptor of the child process inherits the parent process's. # # STDERR value can also be stdout, which indicates that the standard error of the child process is also output to standard output. # # subprocess. pipe# a special value that can be used for the stdin, stdout, and stderr of the Popen for 3 parameters, indicating the need to create a new pipeline. # # subprocess. stdout# a special value that can be used to popen the stderr parameter. Represents a standard error for a subroutine to converge to 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 Rotatingfileha ndler## log settings:should is configured by Configlog_path_file = "./my_service_mgr.log" Log_mode = ' a ' LOG_MAX_SIZE = 4*1 024*1024 # 4M per filelog_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, # indicates that the standard error of the child process is also output to the standard output stdout=subprocess. Pipe # Indicates the need to create a new pipeline) 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 F Ound raise OSError, "Failed to run command!" def run_forever (command): Print_info ("Start child process with command:" + ". Join (command)) logger.info (" Start ch ILD 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.CRI Tical ("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: # r EAD 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"])
Then the child Process code: testpipe.py
#!/usr/bin/python#-*-Coding:utf-8-*-# cheungmine# simulates a woker process, 10 seconds off import osimport sysimport timeimport randomcnt = 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-1sys.exit (-1)
Very easy to perform on Linux:
$ python service_mgr.py
Performed on Windows as a background process:
> Start pythonw service_mgr.py
The code needs to be changed:
Run_forever (["Python", "testpipe.py"])
Write a Python service daemon