Service monitoring program instance written in Python, python monitoring program instance

Source: Internet
Author: User
Tags python subprocess

Service monitoring program instance written in Python, python monitoring program instance

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:

Copy codeThe Code is as follows:
#./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

Copy codeThe Code is as follows:
#./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

Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
# Cheungmine
# Stdin, stdout, and stderr indicate the standard input, output, and error of the subroutine respectively.
#
# Optional values:
# Subprocess. PIPE-indicates that a new pipeline needs to be created.
# A valid file descriptor (actually a positive integer)
# A file object
# None-No redirection is performed, 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 special value that can be used for stdin, stdout, and stderr parameters of Popen, indicating that a new pipeline needs to be created.
#
# Subprocess. STDOUT
# A stderr parameter that can be used in Popen indicates that the standard errors of the subroutine are merged to the standard output.
######################################## ########################################
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: shocould be configured by config
LOG_PATH_FILE = "./my_service_mgr.log"
LOG_MODE = 'A'
LOG_MAX_SIZE = 4*1024*1024 #4 M 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)-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 stderr
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

Failed 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 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 ("!!! Shocould never run to this !!! ")


If _ name _ = "_ main __":
Run_forever (["python", "./testpipe. py"])

Then the sub-process code: testpipe. py

Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
# Cheungmine
# Simulate a woker process, which crashes in 10 seconds
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)

Running on Linux is simple:
Copy codeThe Code is as follows:
$ Python service_mgr.py

After Windows, processes run:
Copy codeThe Code is as follows:
> Start pythonw service_mgr.py

The code must be modified:
Copy codeThe Code is as follows:
Run_forever (["python", "testpipe. 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.