# Event listener code adapted from:
# https://supervisord.org/events.html#example-event-listener-implementation
#
# Only difference is that we terminate supervisord (PID 1) when model-server exits.

import sys
import os
import signal

def write_stdout(msg):
    # only eventlistener protocol messages may be sent to stdout
    sys.stdout.write(msg)
    sys.stdout.flush()

def write_stderr(msg):
    sys.stderr.write(msg + '\n')
    sys.stderr.flush()

def main():
    while True:
        # transition from ACKNOWLEDGED to READY
        write_stdout('READY\n')

        # read header line and print it to stderr
        line = sys.stdin.readline()
        write_stderr('Header: ' + repr(line))

        # read event payload and print it to stderr
        headers = dict(x.split(':', 1) for x in line.strip().split())
        payload = sys.stdin.read(int(headers['len']))
        write_stderr('Payload: ' + repr(payload))

        # kill supervisord if model-server exited
        # payload schema: https://supervisord.org/events.html#process-state-exited-event-type
        # example:
        # processname:cat groupname:cat from_state:RUNNING expected:0 pid:2766
        pdata = dict(x.split(':', 1) for x in payload.strip().split())
        if pdata.get('processname') == 'model-server':
            write_stderr('model-server exited, killing supervisord')
            sys.stdout.write('RESULT 2\nOK')
            sys.stdout.flush()
            os.kill(1, signal.SIGTERM)
        else:
            # transition from READY to ACKNOWLEDGED
            write_stderr('Ignoring event for: ' + pdata.get('processname', 'unknown'))
            write_stdout('RESULT 2\nOK')

main()
