workbox 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- workbox/__init__.py +108 -0
- workbox/box.py +262 -0
- workbox/cli.py +264 -0
- workbox/gateway.py +371 -0
- workbox/runner.py +618 -0
- workbox/ws.py +101 -0
- workbox-0.2.0.dist-info/METADATA +62 -0
- workbox-0.2.0.dist-info/RECORD +10 -0
- workbox-0.2.0.dist-info/WHEEL +4 -0
- workbox-0.2.0.dist-info/entry_points.txt +4 -0
workbox/__init__.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Metrics and samples from a Workbox job (specs/jobs.md §9).
|
|
2
|
+
|
|
3
|
+
import workbox
|
|
4
|
+
workbox.log(step=step, loss=loss, lr=lr)
|
|
5
|
+
workbox.sample(step=step, text=story) # or image="plot.png", or a PIL image
|
|
6
|
+
|
|
7
|
+
Inside a job, the runner sets WORKBOX_EVENTS to a file, and every call appends one JSON line to it, which
|
|
8
|
+
the runner reports to Workbox. Anywhere else (a laptop, Colab), every call does nothing, so the same code
|
|
9
|
+
runs everywhere. Calls never raise: a training run must not fail over a chart.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
__all__ = ["log", "sample", "enabled"]
|
|
24
|
+
|
|
25
|
+
_lock = threading.Lock()
|
|
26
|
+
_sample_count = 0
|
|
27
|
+
_MAX_TEXT = 20_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def enabled() -> bool:
|
|
31
|
+
"""Whether this code is running as a Workbox job."""
|
|
32
|
+
return bool(os.environ.get("WORKBOX_EVENTS"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _write(event: dict[str, Any]) -> None:
|
|
36
|
+
path = os.environ.get("WORKBOX_EVENTS")
|
|
37
|
+
if not path:
|
|
38
|
+
return
|
|
39
|
+
event["time"] = time.time()
|
|
40
|
+
line = json.dumps(event, separators=(",", ":"))
|
|
41
|
+
with _lock, open(path, "a", encoding="utf-8") as events:
|
|
42
|
+
events.write(line + "\n")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _number(value: Any) -> float | None:
|
|
46
|
+
"""A metric's value as a float: plain numbers, NumPy scalars and one-element tensors."""
|
|
47
|
+
try:
|
|
48
|
+
if hasattr(value, "item"):
|
|
49
|
+
value = value.item()
|
|
50
|
+
number = float(value)
|
|
51
|
+
except (TypeError, ValueError, RuntimeError):
|
|
52
|
+
return None
|
|
53
|
+
return number if math.isfinite(number) else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _step(step: Any) -> int | None:
|
|
57
|
+
"""A step as a whole number (a NumPy or tensor step too), or None."""
|
|
58
|
+
number = _number(step)
|
|
59
|
+
return int(number) if number is not None else None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def log(step: int | None = None, **metrics: Any) -> None:
|
|
63
|
+
"""Records metrics at a training step, e.g. log(step=100, loss=1.84, lr=3e-4).
|
|
64
|
+
|
|
65
|
+
Values that aren't numbers, or are NaN or infinite, are left out.
|
|
66
|
+
"""
|
|
67
|
+
if not enabled():
|
|
68
|
+
return
|
|
69
|
+
try:
|
|
70
|
+
values = {name: number for name, value in metrics.items() if (number := _number(value)) is not None}
|
|
71
|
+
if values:
|
|
72
|
+
_write({"type": "metric", "step": _step(step), "values": values})
|
|
73
|
+
except Exception: # noqa: BLE001 - never break the training run
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def sample(step: int | None = None, text: str | None = None, image: Any = None, name: str | None = None) -> None:
|
|
78
|
+
"""Records something the model made at a step: text, or an image (a file path or a PIL image).
|
|
79
|
+
|
|
80
|
+
Images are copied next to the events file, so they are kept even if the code overwrites its own.
|
|
81
|
+
"""
|
|
82
|
+
global _sample_count
|
|
83
|
+
if not enabled() or (text is None and image is None):
|
|
84
|
+
return
|
|
85
|
+
try:
|
|
86
|
+
step = _step(step)
|
|
87
|
+
event: dict[str, Any] = {"type": "sample", "step": step, "name": name}
|
|
88
|
+
if text is not None:
|
|
89
|
+
event["text"] = str(text)[:_MAX_TEXT]
|
|
90
|
+
if image is not None:
|
|
91
|
+
is_path = isinstance(image, (str, os.PathLike))
|
|
92
|
+
if not is_path and not hasattr(image, "save"):
|
|
93
|
+
return
|
|
94
|
+
folder = Path(os.environ["WORKBOX_EVENTS"]).parent / "samples"
|
|
95
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
with _lock:
|
|
97
|
+
_sample_count += 1
|
|
98
|
+
count = _sample_count
|
|
99
|
+
suffix = (Path(image).suffix if is_path else "") or ".png"
|
|
100
|
+
target = folder / f"{count:05d}-step-{step if step is not None else 'na'}{suffix}"
|
|
101
|
+
if is_path:
|
|
102
|
+
shutil.copyfile(image, target)
|
|
103
|
+
else:
|
|
104
|
+
image.save(target)
|
|
105
|
+
event["image"] = str(target)
|
|
106
|
+
_write(event)
|
|
107
|
+
except Exception: # noqa: BLE001 - never break the training run
|
|
108
|
+
pass
|
workbox/box.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""The box agent (specs/boxes.md §5): what a box runs, as the runner is what a job runs.
|
|
2
|
+
|
|
3
|
+
Started as `workbox-box` with WORKBOX_BOX_ID, WORKBOX_URL and WORKBOX_TOKEN set. It checks in, restores ~/work
|
|
4
|
+
(or writes the lab's starter files), runs the setup when the box has no build, starts sshd and the gateway, says
|
|
5
|
+
when the tool it opens with answers, and reports every few seconds: connections, CPU, memory, GPU and disk. The
|
|
6
|
+
answers tell it to run step checks, save ~/work to R2, pack it for a job, or stop. Standard library only.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from workbox.gateway import Gateway, Tool
|
|
23
|
+
from workbox.runner import Workbox, download, fetch_input, gpu_metrics, sh, upload
|
|
24
|
+
|
|
25
|
+
HOME = Path.home()
|
|
26
|
+
WORK = HOME / "work"
|
|
27
|
+
STATE = HOME / ".workbox"
|
|
28
|
+
LOGS = STATE / "logs"
|
|
29
|
+
SSH = STATE / "ssh"
|
|
30
|
+
GATEWAY_PORT = int(os.environ.get("WORKBOX_GATEWAY_PORT", "9000"))
|
|
31
|
+
SSH_PORT = 2222
|
|
32
|
+
REPORT_SECONDS = 10
|
|
33
|
+
|
|
34
|
+
# Bash writes each command to ~/.bash_history as it runs, so step checks can see what a learner typed; login
|
|
35
|
+
# shells reset PATH, so ~/.profile puts the Workbox Python environment back.
|
|
36
|
+
PRELUDE = [
|
|
37
|
+
'grep -qs "history -a" ~/.bashrc || echo \'PROMPT_COMMAND="history -a${PROMPT_COMMAND:+; $PROMPT_COMMAND}"\' >> ~/.bashrc',
|
|
38
|
+
"! test -d /opt/workbox/venv || grep -qs /opt/workbox/venv ~/.profile || echo 'PATH=/opt/workbox/venv/bin:$PATH' >> ~/.profile",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Log:
|
|
43
|
+
"""The agent's own log (~/.workbox/logs/box.log), which setup and downloads write to."""
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
LOGS.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
self.file = open(LOGS / "box.log", "a", encoding="utf-8")
|
|
48
|
+
|
|
49
|
+
def add(self, line: str) -> None:
|
|
50
|
+
self.file.write(line.rstrip("\n") + "\n")
|
|
51
|
+
self.file.flush()
|
|
52
|
+
|
|
53
|
+
def tail(self, count: int = 200) -> str:
|
|
54
|
+
return "\n".join((LOGS / "box.log").read_text(encoding="utf-8", errors="replace").splitlines()[-count:])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SetupFailed(Exception):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def prepare(plan: dict[str, Any], log: Log) -> None:
|
|
62
|
+
"""~/work from R2 or the starter files, then the shell settings, inputs and setup."""
|
|
63
|
+
WORK.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
if work := plan.get("work"):
|
|
65
|
+
archive = STATE / "work.tar.gz"
|
|
66
|
+
log.add("Restoring ~/work")
|
|
67
|
+
download(work["url"], archive)
|
|
68
|
+
if subprocess.run(["tar", "-xzf", str(archive), "-C", str(HOME)]).returncode != 0:
|
|
69
|
+
raise SetupFailed("restore_failed")
|
|
70
|
+
archive.unlink(missing_ok=True)
|
|
71
|
+
for file in plan.get("files", []):
|
|
72
|
+
target = WORK / file["path"]
|
|
73
|
+
if not target.exists():
|
|
74
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
target.write_bytes(base64.b64decode(file["content"]))
|
|
76
|
+
for command in PRELUDE:
|
|
77
|
+
sh(command, log, HOME)
|
|
78
|
+
for source in plan.get("inputs", []):
|
|
79
|
+
try:
|
|
80
|
+
fetch_input(source, log)
|
|
81
|
+
except Exception as error: # noqa: BLE001 - any failure here is the download's
|
|
82
|
+
log.add(f"{source}: {error}")
|
|
83
|
+
raise SetupFailed("download_failed") from error
|
|
84
|
+
# Setup already run on this machine (a box resumed where it was) isn't run again.
|
|
85
|
+
done = STATE / "setup-done"
|
|
86
|
+
if plan.get("setup") and not (done.exists() and done.read_text() == plan.get("setupHash")):
|
|
87
|
+
for command in plan["setup"]:
|
|
88
|
+
if sh(command, log) != 0:
|
|
89
|
+
raise SetupFailed("setup_failed")
|
|
90
|
+
done.write_text(str(plan.get("setupHash")))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def start_sshd(ssh: dict[str, Any], log: Log) -> int | None:
|
|
94
|
+
"""sshd as this user on 127.0.0.1, trusting only Workbox's SSH CA for this box. None when it can't run."""
|
|
95
|
+
sshd = shutil.which("sshd") or "/usr/sbin/sshd"
|
|
96
|
+
if not Path(sshd).exists():
|
|
97
|
+
log.add("No sshd in this image: SSH is off.")
|
|
98
|
+
return None
|
|
99
|
+
SSH.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
host_key = SSH / "host_ed25519"
|
|
101
|
+
if not host_key.exists():
|
|
102
|
+
subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(host_key)], check=False)
|
|
103
|
+
(SSH / "ca.pub").write_text(ssh["caPublicKey"].strip() + "\n")
|
|
104
|
+
(SSH / "principals").write_text(ssh["principal"] + "\n")
|
|
105
|
+
user = os.environ.get("USER") or Path.home().name
|
|
106
|
+
config = SSH / "sshd_config"
|
|
107
|
+
config.write_text(
|
|
108
|
+
"\n".join(
|
|
109
|
+
[
|
|
110
|
+
f"Port {SSH_PORT}",
|
|
111
|
+
"ListenAddress 127.0.0.1",
|
|
112
|
+
f"HostKey {host_key}",
|
|
113
|
+
f"PidFile {SSH / 'sshd.pid'}",
|
|
114
|
+
f"TrustedUserCAKeys {SSH / 'ca.pub'}",
|
|
115
|
+
f"AuthorizedPrincipalsFile {SSH / 'principals'}",
|
|
116
|
+
"AuthorizedKeysFile none",
|
|
117
|
+
"PubkeyAuthentication yes",
|
|
118
|
+
"PasswordAuthentication no",
|
|
119
|
+
"KbdInteractiveAuthentication no",
|
|
120
|
+
"UsePAM no",
|
|
121
|
+
"StrictModes no",
|
|
122
|
+
f"AllowUsers {user}",
|
|
123
|
+
"PrintMotd no",
|
|
124
|
+
"Subsystem sftp internal-sftp",
|
|
125
|
+
"",
|
|
126
|
+
]
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
subprocess.Popen([sshd, "-D", "-e", "-f", str(config)], stdout=open(LOGS / "sshd.log", "ab"), stderr=subprocess.STDOUT, start_new_session=True)
|
|
130
|
+
return SSH_PORT
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class Stats:
|
|
134
|
+
"""What the heartbeat says about the machine: CPU from /proc/stat between reports, memory, GPU, disk."""
|
|
135
|
+
|
|
136
|
+
def __init__(self) -> None:
|
|
137
|
+
self.cpu = self.read_cpu()
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def read_cpu() -> tuple[int, int]:
|
|
141
|
+
try:
|
|
142
|
+
values = [int(value) for value in Path("/proc/stat").read_text().splitlines()[0].split()[1:]]
|
|
143
|
+
idle = values[3] + (values[4] if len(values) > 4 else 0)
|
|
144
|
+
return sum(values), idle
|
|
145
|
+
except (OSError, ValueError, IndexError):
|
|
146
|
+
return 0, 0
|
|
147
|
+
|
|
148
|
+
def take(self) -> dict[str, Any]:
|
|
149
|
+
total, idle = self.read_cpu()
|
|
150
|
+
spent, waited = total - self.cpu[0], idle - self.cpu[1]
|
|
151
|
+
self.cpu = (total, idle)
|
|
152
|
+
stats: dict[str, Any] = {"cpu": round(100 * (spent - waited) / spent, 1) if spent > 0 else 0}
|
|
153
|
+
try:
|
|
154
|
+
info = {line.split(":")[0]: int(line.split()[1]) for line in Path("/proc/meminfo").read_text().splitlines()}
|
|
155
|
+
stats["memoryGb"] = round((info["MemTotal"] - info["MemAvailable"]) / 1e6, 2)
|
|
156
|
+
except (OSError, KeyError, ValueError, IndexError):
|
|
157
|
+
pass
|
|
158
|
+
gpus = gpu_metrics()
|
|
159
|
+
uses = [metric["value"] for metric in gpus if metric["name"].startswith("gpu_use")]
|
|
160
|
+
memory = [metric["value"] for metric in gpus if metric["name"].startswith("gpu_memory_gb")]
|
|
161
|
+
if uses:
|
|
162
|
+
stats["gpu"] = max(uses)
|
|
163
|
+
stats["gpuMemoryGb"] = round(sum(memory), 2)
|
|
164
|
+
usage = shutil.disk_usage(HOME)
|
|
165
|
+
stats["diskGb"] = round(usage.used / 1e9, 2)
|
|
166
|
+
return stats
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def pack(url: str) -> bool:
|
|
170
|
+
"""~/work as one archive, uploaded through a signed link: to keep it while paused, or as a job's code."""
|
|
171
|
+
archive = STATE / "pack.tar.gz"
|
|
172
|
+
if subprocess.run(["tar", "-czf", str(archive), "-C", str(HOME), "--exclude=work/.ipynb_checkpoints", "work"]).returncode not in (0, 1):
|
|
173
|
+
return False
|
|
174
|
+
try:
|
|
175
|
+
return upload(url, archive)
|
|
176
|
+
finally:
|
|
177
|
+
archive.unlink(missing_ok=True)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def run_checks(script: str) -> str:
|
|
181
|
+
try:
|
|
182
|
+
return subprocess.run(["bash", "-lc", script], cwd=WORK, capture_output=True, text=True, timeout=30).stdout
|
|
183
|
+
except subprocess.TimeoutExpired as error:
|
|
184
|
+
return str(error.stdout or "")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class Local:
|
|
188
|
+
"""Stands in for Workbox when a script tests a provider (pnpm sandbox:smoke): the plan is the JSON file at
|
|
189
|
+
WORKBOX_PLAN_FILE, and reports go nowhere."""
|
|
190
|
+
|
|
191
|
+
def post(self, step: str, body: Any = None) -> dict[str, Any]:
|
|
192
|
+
if step == "checkin":
|
|
193
|
+
return json.loads(Path(os.environ["WORKBOX_PLAN_FILE"]).read_text())
|
|
194
|
+
return {}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def agent() -> None:
|
|
198
|
+
workbox: Any = Local() if os.environ.get("WORKBOX_PLAN_FILE") else Workbox("box")
|
|
199
|
+
log = Log()
|
|
200
|
+
plan = await asyncio.to_thread(workbox.post, "checkin")
|
|
201
|
+
if plan.get("stop") or "tools" not in plan:
|
|
202
|
+
print(f"workbox-box: Workbox refused the check-in ({plan.get('error', 'no answer')}); stopping.", flush=True)
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
try:
|
|
206
|
+
await asyncio.to_thread(prepare, plan, log)
|
|
207
|
+
except SetupFailed as error:
|
|
208
|
+
await asyncio.to_thread(workbox.post, "ready", {"ok": False, "kind": str(error), "detail": log.tail()})
|
|
209
|
+
return
|
|
210
|
+
|
|
211
|
+
ssh_port = start_sshd(plan["ssh"], log) if plan.get("ssh") else None
|
|
212
|
+
tools = [Tool(**tool) for tool in plan["tools"]]
|
|
213
|
+
gateway = Gateway(
|
|
214
|
+
os.environ["WORKBOX_BOX_ID"], plan["gatewayKey"], tools, plan["opens"], plan.get("origins", []), ssh_port, WORK, LOGS
|
|
215
|
+
)
|
|
216
|
+
gateway.epoch = float(plan.get("epoch", 0))
|
|
217
|
+
serving = asyncio.create_task(gateway.serve(GATEWAY_PORT))
|
|
218
|
+
|
|
219
|
+
opening = gateway.tools.get(plan["opens"])
|
|
220
|
+
ok = await opening.ensure(WORK, LOGS) if opening else True
|
|
221
|
+
tool_log = LOGS / f"{plan['opens']}.log"
|
|
222
|
+
detail = "" if ok or not tool_log.exists() else tool_log.read_text(errors="replace")[-4000:]
|
|
223
|
+
await asyncio.to_thread(workbox.post, "ready", {"ok": ok, "kind": None if ok else "tool_failed", "detail": detail})
|
|
224
|
+
|
|
225
|
+
stats = Stats()
|
|
226
|
+
checks: str | None = None
|
|
227
|
+
while not serving.done():
|
|
228
|
+
await asyncio.sleep(plan.get("reportSeconds", REPORT_SECONDS))
|
|
229
|
+
body: dict[str, Any] = {
|
|
230
|
+
**stats.take(),
|
|
231
|
+
"connections": gateway.connections,
|
|
232
|
+
"ssh": gateway.ssh_sessions,
|
|
233
|
+
"idleSeconds": int(time.time() - gateway.last_activity),
|
|
234
|
+
}
|
|
235
|
+
if checks is not None:
|
|
236
|
+
body["checkOutput"], checks = checks, None
|
|
237
|
+
answer = await asyncio.to_thread(workbox.post, "report", body)
|
|
238
|
+
if answer.get("stop"):
|
|
239
|
+
break
|
|
240
|
+
if "epoch" in answer:
|
|
241
|
+
gateway.epoch = float(answer["epoch"])
|
|
242
|
+
if "revoked" in answer:
|
|
243
|
+
gateway.revoked = set(answer["revoked"])
|
|
244
|
+
if script := answer.get("checks"):
|
|
245
|
+
checks = await asyncio.to_thread(run_checks, script)
|
|
246
|
+
for kind in ("save", "pack"):
|
|
247
|
+
if target := answer.get(kind):
|
|
248
|
+
saved = await asyncio.to_thread(pack, target["url"])
|
|
249
|
+
await asyncio.to_thread(workbox.post, "saved", {"kind": kind, "ok": saved, "id": target.get("id")})
|
|
250
|
+
serving.cancel()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def main() -> None:
|
|
254
|
+
# `workbox-box input <source>`: one input into ~/inputs, for a template's build (lib/labs/template.ts).
|
|
255
|
+
if len(sys.argv) == 3 and sys.argv[1] == "input":
|
|
256
|
+
fetch_input(sys.argv[2], Log())
|
|
257
|
+
return
|
|
258
|
+
asyncio.run(agent())
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
if __name__ == "__main__":
|
|
262
|
+
sys.exit(main())
|
workbox/cli.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""The `workbox` command (specs/boxes.md §6): sign in once, then SSH into your boxes with your own tools.
|
|
2
|
+
|
|
3
|
+
workbox login --url https://your-workbox # approve this computer in the browser
|
|
4
|
+
workbox boxes # your boxes and their names
|
|
5
|
+
workbox ssh tinystories # or `ssh tinystories.workbox`, VS Code Remote, scp, rsync
|
|
6
|
+
workbox logout
|
|
7
|
+
|
|
8
|
+
`login` adds `Host *.workbox` to ~/.ssh/config with `workbox connect %h` as its ProxyCommand: each connection gets
|
|
9
|
+
a certificate for that one box (valid 12 hours) and a one-use ticket, and runs over the box's HTTPS port.
|
|
10
|
+
Standard library only.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
import socket
|
|
20
|
+
import ssl
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
import urllib.error
|
|
26
|
+
import urllib.parse
|
|
27
|
+
import urllib.request
|
|
28
|
+
import webbrowser
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from workbox import ws
|
|
33
|
+
|
|
34
|
+
DIR = Path.home() / ".workbox"
|
|
35
|
+
CREDENTIALS = DIR / "credentials"
|
|
36
|
+
KEY = DIR / "ssh" / "id_ed25519"
|
|
37
|
+
SSH_CONFIG = Path.home() / ".ssh" / "config"
|
|
38
|
+
BEGIN, END = "# workbox: begin", "# workbox: end"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def fail(message: str) -> None:
|
|
42
|
+
print(f"workbox: {message}", file=sys.stderr)
|
|
43
|
+
sys.exit(1)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def credentials() -> dict[str, str]:
|
|
47
|
+
try:
|
|
48
|
+
return json.loads(CREDENTIALS.read_text())
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
fail("you're not signed in. Run `workbox login --url <your Workbox address>` first.")
|
|
51
|
+
raise
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def call(url: str, path: str, body: Any = None, token: str | None = None) -> dict[str, Any]:
|
|
55
|
+
request = urllib.request.Request(
|
|
56
|
+
f"{url.rstrip('/')}{path}",
|
|
57
|
+
data=json.dumps(body or {}).encode(),
|
|
58
|
+
method="POST",
|
|
59
|
+
headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {})},
|
|
60
|
+
)
|
|
61
|
+
try:
|
|
62
|
+
with urllib.request.urlopen(request, timeout=30) as response:
|
|
63
|
+
return json.loads(response.read() or b"{}")
|
|
64
|
+
except urllib.error.HTTPError as error:
|
|
65
|
+
try:
|
|
66
|
+
message = json.loads(error.read()).get("error")
|
|
67
|
+
except ValueError:
|
|
68
|
+
message = None
|
|
69
|
+
if error.code == 401:
|
|
70
|
+
fail("your sign-in has ended. Run `workbox login` again.")
|
|
71
|
+
fail(message or f"Workbox answered {error.code}.")
|
|
72
|
+
except (urllib.error.URLError, OSError) as error:
|
|
73
|
+
fail(f"couldn't reach Workbox at {url} ({error}).")
|
|
74
|
+
raise AssertionError
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def ssh_config() -> None:
|
|
78
|
+
"""Adds (or refreshes) the Host *.workbox block in ~/.ssh/config."""
|
|
79
|
+
command = f'"{sys.executable}" -m workbox.cli connect %h'
|
|
80
|
+
block = "\n".join(
|
|
81
|
+
[
|
|
82
|
+
BEGIN,
|
|
83
|
+
"Host *.workbox",
|
|
84
|
+
" User learner",
|
|
85
|
+
f" ProxyCommand {command}",
|
|
86
|
+
f" IdentityFile {KEY}",
|
|
87
|
+
f" CertificateFile {KEY.parent}/%h-cert.pub",
|
|
88
|
+
" IdentitiesOnly yes",
|
|
89
|
+
" StrictHostKeyChecking accept-new",
|
|
90
|
+
f" UserKnownHostsFile {KEY.parent}/known_hosts",
|
|
91
|
+
END,
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
SSH_CONFIG.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
95
|
+
text = SSH_CONFIG.read_text() if SSH_CONFIG.exists() else ""
|
|
96
|
+
if BEGIN in text and END in text:
|
|
97
|
+
start, end = text.index(BEGIN), text.index(END) + len(END)
|
|
98
|
+
text = text[:start] + block + text[end:]
|
|
99
|
+
else:
|
|
100
|
+
text = block + "\n\n" + text
|
|
101
|
+
SSH_CONFIG.write_text(text)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def login(args: argparse.Namespace) -> None:
|
|
105
|
+
url = (args.url or os.environ.get("WORKBOX_URL") or "").rstrip("/")
|
|
106
|
+
if not url and CREDENTIALS.exists():
|
|
107
|
+
url = json.loads(CREDENTIALS.read_text()).get("url", "")
|
|
108
|
+
if not url:
|
|
109
|
+
fail("say where your Workbox is: `workbox login --url https://…` (it's on the box page).")
|
|
110
|
+
device = call(url, "/api/cli/device", {"name": socket.gethostname()})
|
|
111
|
+
print(f"Approve this computer in your browser. The code is {device['userCode']}.")
|
|
112
|
+
print(f"If the browser doesn't open, go to {device['verifyUrl']}")
|
|
113
|
+
webbrowser.open(device["verifyUrl"])
|
|
114
|
+
until = time.time() + device.get("expiresIn", 600)
|
|
115
|
+
while time.time() < until:
|
|
116
|
+
time.sleep(device.get("interval", 3))
|
|
117
|
+
answer = call(url, "/api/cli/token", {"deviceCode": device["deviceCode"]})
|
|
118
|
+
if answer.get("token"):
|
|
119
|
+
break
|
|
120
|
+
if answer.get("denied"):
|
|
121
|
+
fail("the sign-in was refused.")
|
|
122
|
+
else:
|
|
123
|
+
fail("the code expired before it was approved. Run `workbox login` again.")
|
|
124
|
+
DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
125
|
+
CREDENTIALS.write_text(json.dumps({"url": url, "token": answer["token"]}))
|
|
126
|
+
CREDENTIALS.chmod(0o600)
|
|
127
|
+
if not KEY.exists():
|
|
128
|
+
KEY.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
129
|
+
if not shutil.which("ssh-keygen"):
|
|
130
|
+
fail("ssh-keygen wasn't found. Install OpenSSH, then run `workbox login` again.")
|
|
131
|
+
subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "workbox", "-f", str(KEY)], check=True)
|
|
132
|
+
ssh_config()
|
|
133
|
+
print(f"Signed in as {answer.get('name', 'you')}. Connect with `workbox ssh <box>` or `ssh <box>.workbox`.")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def logout(_: argparse.Namespace) -> None:
|
|
137
|
+
if CREDENTIALS.exists():
|
|
138
|
+
saved = credentials()
|
|
139
|
+
call(saved["url"], "/api/cli/logout", token=saved["token"])
|
|
140
|
+
CREDENTIALS.unlink()
|
|
141
|
+
print("Signed out.")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def boxes(_: argparse.Namespace) -> None:
|
|
145
|
+
saved = credentials()
|
|
146
|
+
answer = call(saved["url"], "/api/cli/boxes", token=saved["token"])
|
|
147
|
+
if not answer.get("boxes"):
|
|
148
|
+
print("You have no boxes running. Start one in Workbox.")
|
|
149
|
+
for box in answer.get("boxes", []):
|
|
150
|
+
print(f"{box['name']:<24} {box['state']:<12} {box['size']}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def certificate(name: str) -> dict[str, Any]:
|
|
154
|
+
"""Asks Workbox for this box: a certificate for our key, valid for it alone, a ticket and its address."""
|
|
155
|
+
saved = credentials()
|
|
156
|
+
public_key = KEY.with_suffix(".pub").read_text().strip()
|
|
157
|
+
answer = call(saved["url"], "/api/cli/connect", {"box": name, "publicKey": public_key}, saved["token"])
|
|
158
|
+
(KEY.parent / f"{name}.workbox-cert.pub").write_text(answer["certificate"].strip() + "\n")
|
|
159
|
+
return answer
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ssh(args: argparse.Namespace) -> None:
|
|
163
|
+
certificate(args.box)
|
|
164
|
+
host = f"{args.box}.workbox"
|
|
165
|
+
if not shutil.which("ssh"):
|
|
166
|
+
fail("ssh wasn't found. Install OpenSSH.")
|
|
167
|
+
sys.exit(subprocess.call(["ssh", host, *args.rest]))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def connect(args: argparse.Namespace) -> None:
|
|
171
|
+
"""ssh's ProxyCommand: pipes standard input and output through the box's /ssh WebSocket."""
|
|
172
|
+
name = args.host.removesuffix(".workbox")
|
|
173
|
+
answer = certificate(name)
|
|
174
|
+
address = urllib.parse.urlsplit(answer["url"])
|
|
175
|
+
secure = address.scheme == "https"
|
|
176
|
+
port = address.port or (443 if secure else 80)
|
|
177
|
+
raw = socket.create_connection((address.hostname, port), timeout=30)
|
|
178
|
+
sock = ssl.create_default_context().wrap_socket(raw, server_hostname=address.hostname) if secure else raw
|
|
179
|
+
key = ws.new_key()
|
|
180
|
+
path = f"{address.path.rstrip('/')}/ssh?t={urllib.parse.quote(answer['ticket'])}"
|
|
181
|
+
sock.sendall(
|
|
182
|
+
(
|
|
183
|
+
f"GET {path} HTTP/1.1\r\nHost: {address.netloc}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
|
184
|
+
f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
|
|
185
|
+
).encode()
|
|
186
|
+
)
|
|
187
|
+
reader = sock.makefile("rb")
|
|
188
|
+
status = reader.readline().decode("latin-1")
|
|
189
|
+
headers = {}
|
|
190
|
+
while (line := reader.readline().decode("latin-1").strip()) != "":
|
|
191
|
+
name_, _, value = line.partition(":")
|
|
192
|
+
headers[name_.strip().lower()] = value.strip()
|
|
193
|
+
if " 101 " not in status or headers.get("sec-websocket-accept") != ws.accept_key(key):
|
|
194
|
+
fail("the box refused the connection. Check it is running, then try again.")
|
|
195
|
+
sock.settimeout(None)
|
|
196
|
+
lock = threading.Lock()
|
|
197
|
+
|
|
198
|
+
def send(opcode: int, payload: bytes) -> None:
|
|
199
|
+
with lock:
|
|
200
|
+
sock.sendall(ws.frame(opcode, payload, mask=True))
|
|
201
|
+
|
|
202
|
+
def upstream() -> None:
|
|
203
|
+
stdin = sys.stdin.buffer
|
|
204
|
+
while chunk := (stdin.read1(1 << 16) if hasattr(stdin, "read1") else stdin.read(1 << 16)):
|
|
205
|
+
send(ws.BINARY, chunk)
|
|
206
|
+
send(ws.CLOSE, b"")
|
|
207
|
+
|
|
208
|
+
threading.Thread(target=upstream, daemon=True).start()
|
|
209
|
+
stdout = sys.stdout.buffer
|
|
210
|
+
try:
|
|
211
|
+
while True:
|
|
212
|
+
opcode, payload = read_frame(reader)
|
|
213
|
+
if opcode == ws.CLOSE:
|
|
214
|
+
break
|
|
215
|
+
if opcode == ws.PING:
|
|
216
|
+
send(ws.PONG, payload)
|
|
217
|
+
elif opcode in (ws.BINARY, 0x0, 0x1):
|
|
218
|
+
stdout.write(payload)
|
|
219
|
+
stdout.flush()
|
|
220
|
+
except (EOFError, OSError):
|
|
221
|
+
pass
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def read_frame(reader: Any) -> tuple[int, bytes]:
|
|
225
|
+
def exactly(count: int) -> bytes:
|
|
226
|
+
data = reader.read(count)
|
|
227
|
+
if len(data) < count:
|
|
228
|
+
raise EOFError
|
|
229
|
+
return data
|
|
230
|
+
|
|
231
|
+
first, second = exactly(2)
|
|
232
|
+
length = second & 0x7F
|
|
233
|
+
if length == 126:
|
|
234
|
+
length = int.from_bytes(exactly(2), "big")
|
|
235
|
+
elif length == 127:
|
|
236
|
+
length = int.from_bytes(exactly(8), "big")
|
|
237
|
+
mask = exactly(4) if second & 0x80 else None
|
|
238
|
+
payload = exactly(length)
|
|
239
|
+
if mask:
|
|
240
|
+
payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
|
|
241
|
+
return first & 0x0F, payload
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def main() -> None:
|
|
245
|
+
parser = argparse.ArgumentParser(prog="workbox", description="SSH into your Workbox boxes.")
|
|
246
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
247
|
+
login_parser = commands.add_parser("login", help="approve this computer")
|
|
248
|
+
login_parser.add_argument("--url", help="your Workbox address, e.g. https://workbox.example")
|
|
249
|
+
login_parser.set_defaults(run=login)
|
|
250
|
+
commands.add_parser("logout", help="sign this computer out").set_defaults(run=logout)
|
|
251
|
+
commands.add_parser("boxes", help="list your boxes").set_defaults(run=boxes)
|
|
252
|
+
ssh_parser = commands.add_parser("ssh", help="SSH into a box")
|
|
253
|
+
ssh_parser.add_argument("box")
|
|
254
|
+
ssh_parser.add_argument("rest", nargs=argparse.REMAINDER, help="more arguments for ssh")
|
|
255
|
+
ssh_parser.set_defaults(run=ssh)
|
|
256
|
+
connect_parser = commands.add_parser("connect", help="ssh's ProxyCommand (set up by login)")
|
|
257
|
+
connect_parser.add_argument("host")
|
|
258
|
+
connect_parser.set_defaults(run=connect)
|
|
259
|
+
args = parser.parse_args()
|
|
260
|
+
args.run(args)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
if __name__ == "__main__":
|
|
264
|
+
main()
|