File size: 3,754 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""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 <port> <tree> <state dir>"""
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()