"""relay - the far end of the browser link: carries the page's HTTP requests to the harness on this machine, one JSON line in, one JSON line out, over the stdin/stdout of an ordinary ssh session (no port forwarding needed). Starts the harness server if nothing answers on the port, and stops the one it started when the link closes. 12.0 C11: each request is carried in its own thread and answered with its id, so a status or a stop goes through while a long turn runs; the first line names what the harness runs (its /api/identity: the loaded build, its tree, its state root), never only that something answered at /. usage (run by o7_browser.py over ssh): python3 relay.py """ import base64 import json import os import subprocess import sys import threading import time import urllib.error import urllib.request PORT, TREE, STATE = int(sys.argv[1]), sys.argv[2], sys.argv[3] BASE = "http://127.0.0.1:%d" % PORT HOP = {"connection", "keep-alive", "transfer-encoding", "content-length", "host", "accept-encoding"} OUT = threading.Lock() def up(): try: urllib.request.urlopen(BASE + "/", timeout=3).read(1) return True except Exception: # noqa: BLE001 return False def ident(): try: return json.load(urllib.request.urlopen(BASE + "/api/identity", timeout=60)) except Exception as e: # noqa: BLE001 return {"error": "the harness on port %d answered at / but not /api/identity (%r): it is not this build's server" % (PORT, e)} def say(obj): with OUT: sys.stdout.write(json.dumps(obj) + "\n") sys.stdout.flush() def carry(q): try: req = urllib.request.Request(BASE + q["path"], data=base64.b64decode(q["body"]) if q.get("body") else None, method=q.get("method", "GET"), headers={k: v for k, v in q.get("headers", {}).items() if k.lower() not in HOP}) try: r = urllib.request.urlopen(req, timeout=7200) code, hdrs, body = r.status, dict(r.headers), r.read() except urllib.error.HTTPError as e: code, hdrs, body = e.code, dict(e.headers), e.read() say({"id": q.get("id"), "status": code, "headers": {k: v for k, v in hdrs.items() if k.lower() not in HOP}, "body": base64.b64encode(body).decode()}) except Exception as e: # noqa: BLE001 say({"id": q.get("id"), "status": 502, "headers": {"Content-Type": "text/plain"}, "body": base64.b64encode(("relay: %r" % e).encode()).decode()}) started = None if not up(): os.makedirs(STATE, exist_ok=True) os.makedirs(os.path.join(os.path.dirname(STATE), "o7tmp"), exist_ok=True) env = dict(os.environ, ORACLE7_STATE=STATE, TMPDIR=os.path.join(os.path.dirname(STATE), "o7tmp"), ORACLE7_WORKSPACE=TREE) py = "/opt/oracle7/venv/bin/python" if os.path.isfile("/opt/oracle7/venv/bin/python") else sys.executable started = subprocess.Popen([py, "oracle7.py", "--workbench", str(PORT)], cwd=TREE, env=env, stdin=subprocess.DEVNULL, stdout=open(os.path.join(STATE, "server.log"), "ab"), stderr=subprocess.STDOUT) for _ in range(180): if up(): break time.sleep(2) ready = up() say({"ready": ready, "started": started is not None, "identity": ident() if ready else None}) try: for line in sys.stdin: try: q = json.loads(line) except ValueError: continue threading.Thread(target=carry, args=(q,), daemon=True).start() finally: if started is not None: started.terminate() try: started.wait(10) except Exception: # noqa: BLE001 started.kill()