File size: 5,111 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | """o7_browser - open the Oracle7 harness page on this computer while Oracle7 runs on the box.
python o7_browser.py (defaults: host o7research, port 8199 here, 8231 there)
python o7_browser.py --host o7research --local 8199 --remote 8231
It starts one ordinary ssh session to the box that runs relay.py there (the box needs no port forwarding), serves the page
at http://127.0.0.1:8199/ here, and carries each request of the page through that session. Close this window to stop; the
harness server it started on the box stops with it. Python standard library only; needs ssh with your key for the host."""
import argparse
import functools
import base64
import http.server
import json
import subprocess
import sys
import threading
import webbrowser
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="o7research")
ap.add_argument("--local", type=int, default=8199)
ap.add_argument("--remote", type=int, default=8231)
ap.add_argument("--tree", default="/opt/rel12/w")
ap.add_argument("--relay", default=None, help="default: the tree's own workbench/relay.py")
ap.add_argument("--state", default="/opt/o7conv/state_runs/browser")
ap.add_argument("--cmd", default=None, help="run this instead of ssh (testing on the box itself)")
ap.add_argument("--no-open", action="store_true")
a = ap.parse_args()
print = functools.partial(print, flush=True) # noqa: A001 (the lines show at once, also into a log)
a.relay = a.relay or a.tree.rstrip("/") + "/workbench/relay.py"
far = a.cmd or "ssh -o BatchMode=yes -o ServerAliveInterval=30 %s python3 %s %d %s %s" % (a.host, a.relay, a.remote, a.tree, a.state)
print("Connecting to %s (the harness may take a minute or two to load the first time) ..." % (a.host if not a.cmd else "relay"))
P = subprocess.Popen(far, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)
hello = json.loads(P.stdout.readline() or b"{}")
if not hello.get("ready"):
print("The harness on %s did not come up: %s" % (a.host, hello))
sys.exit(1)
ID = hello.get("identity") or {}
if ID.get("error") or not ID.get("build"): # 12.0 C11: what runs is named, not assumed from a 200 at /
print("The harness answered but did not say what it runs: %s" % (ID.get("error") or ID))
sys.exit(1)
print("Running build %s: tree %s, state %s, pid %s, version %s; workbench %s (%s files)%s%s" % (
ID["build"], ID["tree"], ID["state"], ID["pid"], ID.get("version"), ID["workbench_at_start"]["sha256"][:16],
ID["workbench_at_start"]["files"], "" if ID.get("running_is_release") else
" - NOT the assembled release's workbench (%s)" % (ID.get("workbench_in_release") or {}).get("sha256", "?")[:16],
"" if ID.get("running_is_on_disk") else " - files changed on disk since it started: %s (restart it to load them)" %
", ".join(ID.get("loaded_but_changed_on_disk") or ["the workbench"])))
WLOCK = threading.Lock() # writing a request line; replies come back by id, in any order
N = [0]
WAIT = {}
def reader():
for line in iter(P.stdout.readline, b""):
try:
r = json.loads(line)
except ValueError:
continue
w = WAIT.get(r.get("id"))
if w:
w[1] = r
w[0].set()
for w in list(WAIT.values()): # the link closed: everyone waiting is told
w[0].set()
threading.Thread(target=reader, daemon=True).start()
def carry(method, path, headers, body):
with WLOCK:
N[0] += 1
n = N[0]
WAIT[n] = [threading.Event(), None]
P.stdin.write((json.dumps({"id": n, "method": method, "path": path, "headers": headers,
"body": base64.b64encode(body).decode() if body else None}) + "\n").encode())
P.stdin.flush()
WAIT[n][0].wait()
r = WAIT.pop(n)[1]
if not r:
return 502, {"Content-Type": "text/plain"}, b"the link to the box closed"
return r["status"], r["headers"], base64.b64decode(r["body"])
class H(http.server.BaseHTTPRequestHandler):
def _go(self, method):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else None
code, hdrs, out = carry(method, self.path, dict(self.headers), body)
self.send_response(code)
for k, v in hdrs.items():
self.send_header(k, v)
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
def do_GET(self): # noqa: N802
self._go("GET")
def do_POST(self): # noqa: N802
self._go("POST")
def log_message(self, *args):
pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", a.local), H)
url = "http://127.0.0.1:%d/" % a.local
print("Oracle7 harness: %s (Ctrl+C to stop)" % url)
if not a.no_open:
webbrowser.open(url)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
P.stdin.close()
P.wait(15)
|