"""Supervise one application process and its narrowly scoped identity agent.""" import json import os import signal import subprocess import sys import time from pathlib import Path def main(): role = os.environ["SERVICE_ROLE"] agent = subprocess.Popen( ["/usr/local/bin/tls-gateway", "/etc/tls/" + role + ".json"] ) child = None def stop(number, _): if child is not None and child.poll() is None: child.send_signal(number) if agent.poll() is None: agent.send_signal(signal.SIGTERM) signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) try: deadline = time.monotonic() + 90 while time.monotonic() < deadline: if agent.poll() is not None: raise RuntimeError("Identity agent stopped") try: data = json.loads(Path("/run/identity/agent.json").read_text()) if data["refreshed_at"] > time.time() - 60: break except OSError, ValueError, KeyError: pass time.sleep(0.2) else: raise RuntimeError("Identity startup deadline") child = subprocess.Popen( [sys.executable, "-m", sys.argv[1], *sys.argv[2:]] ) while child.poll() is None: if agent.poll() is not None: child.terminate() break time.sleep(0.2) try: status = child.wait(timeout=28) except subprocess.TimeoutExpired: child.kill() status = child.wait() raise SystemExit(status) finally: if agent.poll() is None: agent.terminate() try: agent.wait(timeout=3) except subprocess.TimeoutExpired: agent.kill() agent.wait() if __name__ == "__main__": main()