1#!/usr/bin/env python3
 2
 3"""Receive messages from supervisor process over stdin, using supervisor utility functions.
 4
 5Send an email in response to status changes in other processes.
 6"""
 7
 8import os
 9import sys
10import socket
11import smtplib
12import argparse
13import subprocess
14
15def log(message):
16    """Log `message` to the supervisord stderr file."""
17    sys.stderr.write('{message}\n'.format(message=message))
18    sys.stderr.flush()
19
20
21def listen(launcher):
22    """Listen for messages and send emails."""
23    from supervisor import childutils  # throws off lint/doctest tools because this is
24    # python2 code
25
26    log('Listening')
27
28    while True:
29        # we explicitly use self.stdin, self.stdout, and self.stderr
30        # instead of sys.* so we can unit test this code
31        headers, payload = childutils.listener.wait(sys.stdin, sys.stdout)
32        log('headers ' + str(headers))
33        # log('payload ' + str(payload))
34        pheaders, pdata = childutils.eventdata(payload + '\n')
35        log('pheaders ' + str(pheaders))
36        # log('pdata ' + str(pdata))
37        log('process ' + str(pheaders.get('processname', 'supervisord')))
38        log('state ' + str(headers['eventname']))
39        log('oldstate ' + str(pheaders.get('from_state')))
40        cmd = [launcher,
41               'roles',
42               '--send-daemon',
43               pheaders.get('processname', 'supervisord'),
44               '--state',
45               headers['eventname'],
46               '--old-state',
47               pheaders.get('from_state', 'none'),
48               '--sendmail']
49        log('cmd ' + str(cmd))
50        subprocess.call(cmd)
51        childutils.listener.ok(sys.stdout)
52
53
54def main():
55    """Command line entry point."""
56    if 'SUPERVISOR_SERVER_URL' not in os.environ:
57        sys.stderr.write('This program must be run as a supervisord process (SUPERVISOR_SERVER_URL not set)\n')
58        sys.stderr.flush()
59        return
60
61    parser = argparse.ArgumentParser()
62    parser.add_argument('--launcher',
63                        help=('Project name'))
64    args = parser.parse_args()
65
66    if not args.launcher:
67        parser.error('No launcher specified')
68
69    listen(launcher=args.launcher)
70
71if __name__ == '__main__':
72    main()