Process management Tools Supervisor (ii) Events

Source: Internet
Author: User
Tags event listener readline stdin

Supervisor can be used as a simple process startup, reboot, Control tool, or as a process monitoring framework, which requires the use of the Supervisor events mechanism.

Event Listeners

Supervisor the monitoring of the sub-program is implemented through a program called Event listener. When the supervisor state of the control is changed, some event notifications are generated, and event listener can subscribe to these events notifications.

The event listener itself is also run as a supervisor subroutine. The implementation of the event notification protocol is based on the stdin and stdout of the events listener subroutine. Supervisor sends a specific format of information to the stdin of the event listener and then obtains a specific format of output from stdout of event listener, thus forming a request/reply loop.

Configuration

The configuration of the event listener is placed in the [EVENTLISTENER:X] block in the configuration file.

[eventlistener:mylistener]command=my_custom_listener.pyevents=process_state,tick_60

X is the name of the Listener command, which executes the listener script, events is the type of event to monitor.

The event listener itself is run as a subroutine of the supervisor, so similar to the configuration subroutine [PROGRAM:X] block, the official website example:

[eventlistener:theeventlistenername]command=/bin/eventlistenerprocess_name=% (Program_name) s_% (process_num) 02dnumprocs=5events=process_statebuffer_size=10directory=/tmpumask=022priority=-1autostart=trueautorestart= unexpectedstartsecs=1startretries=3exitcodes=0,2stopsignal=quitstopwaitsecs=10stopasgroup=falsekillasgroup= falseuser=chrismredirect_stderr=falsestdout_logfile=/a/pathstdout_logfile_maxbytes=1mbstdout_logfile_backups= 10stdout_events_enabled=falsestderr_logfile=/a/pathstderr_logfile_maxbytes=1mbstderr_logfile_backups=10stderr_ Events_enabled=falseenvironment=a= "1", b= "2" Serverurl=auto
Event Notification Protocol

An event listener can be in three states, acknowledged, ready, and BUSY, and can only receive notification of events if it is in the readiness State.

Event listener is in the acknowledged state at startup until the event listener outputs a "ready\n" string to stdout.

Event listener is in the ready state after outputting "ready\n" to the STDOUT, supervisor sends an events notification for listener subscriptions to listener in the ready state.

Listener receive event notification is in the busy state, during the listener docking received event notification processing, processing end to stdout output "RESULT 2\nok " or "RESULT 4\nfail", the former represents the processing success, the latter represents the processing failure.

When the supervisor receives an OK or fail output, it places the status of the event listener in acknowledged. The Fail event notification is cached and sent again.

The status of the event listener can exit execution after acknowledged, or it can continue execution, which can form a loop to stdout output "ready\n" .

Supervisor the event notification sent to listener consists of two parts, header and body, separated by the "\ n" line break.

A header example:

ver:3.0 server:supervisor serial:21 pool:listener poolserial:10 eventname:process_communication_stdout len:54

ver: protocol version

Server:supervisor identifier, set by the identifier option in the [Supervisord] block.

serial: Serial number of event

Pool: The name of Listener's pool.

poolserial: The sequence number of the event in the pool

eventname: Event type name

len: Body length behind the header.

A body Example:

Processname:foo Groupname:bar Pid:123this is the data of was sent between the tags

processname: The name of the child process to which the event belongs

groupname: Child process belongs to group name

PID: Sub-process PID

A simple listener script, listener.py:

Import Sysdef write_stdout (s):    # only EventListener protocol messages is sent to stdout Sys.stdout.write    (s) 
   sys.stdout.flush () def write_stderr (s):    Sys.stderr.write (s)    Sys.stderr.flush () def main ():    while True:        # enters Ready status    ┆   write_stdout (' ready\n ')    ┆   # Read Event notification header    ┆ line   = Sys.stdin.readline ()    ┆   write_stderr (line)        # Gets the body length, reads the body    ┆   headers=dict ([X.split (': ') for x in Line.split ()]    ┆   data = sys.stdin.read (int (headers[' len "))    ┆   write_stderr (data+ ' \ n ')        # Send OK into acknowledged status    ┆   write_stdout (' RESULT 2\nok ') if __name__ = = ' __main__ ':    Main ()

Create a listener configuration file in the CONF.D directory mylistener.conf:

[Eventlistener:mylistener]command=python Listener.pydirectory=/thedirectoroflistener.pyuser=userevents=process_ State,tick_5stdout_logfile=/path/to/mylistener_stdout.logstderr_logfile=/path/to/mylistener_stderr.log

Start:

ubuntu:$ sudo supervisorctl start allmylistener:startedcelerybeat:startedubuntu:$ sudo supervisorctl statuscelerybeat                       RUNNING   pid 87729, uptime 0:00:20mylistener                       RUNNING   pid 87728, uptime 0:00:20

Monitoring starts, you can view the contents of the event notification in the log:

ver:3.0 server:supervisor serial:15361 pool:mylistener poolserial:15361 eventname:process_state_running len : 73processname:mylistener groupname:mylistener from_state:starting pid:87728ver:3.0 server:supervisor serial:15362 Pool:mylistener poolserial:15362 eventname:tick_5 len:15when:1514313560ver:3.0 server:supervisor serial:15364 Pool: MyListener poolserial:15364 eventname:process_state_running len:73processname:celerybeat groupname:celerybeat from_ State:starting pid:87729

You can set the type of event to monitor according to your own needs, then make different strain according to different event type and content, the specific event type can be viewed on official website.

The Python supervisor.childutils module wraps the header and body processing:

def get_headers (line): Return Dict ([X.split (': ')-X in Line.split ()]) def eventdata (payload): headerinfo, data = Payload.split (' \ n ', 1) headers = get_headers (headerinfo) return headers, Datadef get_asctime (now=none): If now I S None: # for testing now = Time.time () # Pragma:no Cover msecs = (Now-long (now)) * Part1 = TIME.STRF Time ("%y-%m-%d%h:%m:%s", Time.localtime (now)) Asctime = '%s,%03d '% (part1, msecs) return Asctimeclass Processcommu Nicationsprotocol:def Send (Self, MSG, fp=sys.stdout): Fp.write (Processcommunicationevent.begin_token) FP . Write (msg) Fp.write (Processcommunicationevent.end_token) def stdout (self, msg): Return Self.send (MSG, SY S.stdout) def stderr (self, msg): Return Self.send (MSG, sys.stderr) Pcomm = Processcommunicationsprotocol () class E Ventlistenerprotocol:def Wait (self, Stdin=sys.stdin, stdout=sys.stdout): Self.ready (stdout) line = stdin . ReadLine () Headers = get_headers (line) payload = stdin.read (int (headers[' len ")) return headers, payload def ready (self, Stdout=sys.stdout): Stdout.write (Peventlistenerdispatcher.ready_for_events_token) Stdout.flush () def OK (s Elf, Stdout=sys.stdout): Self.send (' OK ', stdout) def fail (self, stdout=sys.stdout): Self.send (' fail ', STD OUT) def send (self, data, stdout=sys.stdout): Resultlen = len (data) result = '%s%s\n%s '% (peventlistener Dispatcher.result_token_start, str (resultlen), data) St Dout.write (Result) stdout.flush () listener = Eventlistenerprotocol ()

The listener script can be easily written:

Import sysfrom Supervisor Import Childutilsdef write_stdout (s):    # only EventListener protocol messages could be sent to StdOut    Sys.stdout.write (s)    Sys.stdout.flush () def write_stderr (s):    Sys.stderr.write (s)    Sys.stderr.flush () def main ():    while True:    ┆   headers, payload = childutils.listener.wait ()    ┆   Write_stderr (payload+ ' \ n ')    ┆   Childutils.listener.ok (sys.stdout) if __name__ = = ' __main__ ':    Main ()

  

Process management Tools Supervisor (ii) Events

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.