workbox 0.2.0__tar.gz
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-0.2.0/.gitignore +47 -0
- workbox-0.2.0/PKG-INFO +62 -0
- workbox-0.2.0/README.md +52 -0
- workbox-0.2.0/pyproject.toml +24 -0
- workbox-0.2.0/workbox/__init__.py +108 -0
- workbox-0.2.0/workbox/box.py +262 -0
- workbox-0.2.0/workbox/cli.py +264 -0
- workbox-0.2.0/workbox/gateway.py +371 -0
- workbox-0.2.0/workbox/runner.py +618 -0
- workbox-0.2.0/workbox/ws.py +101 -0
workbox-0.2.0/.gitignore
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
2
|
+
|
|
3
|
+
# dependencies
|
|
4
|
+
/node_modules
|
|
5
|
+
/.pnp
|
|
6
|
+
.pnp.*
|
|
7
|
+
.yarn/*
|
|
8
|
+
!.yarn/patches
|
|
9
|
+
!.yarn/plugins
|
|
10
|
+
!.yarn/releases
|
|
11
|
+
!.yarn/versions
|
|
12
|
+
|
|
13
|
+
# testing
|
|
14
|
+
/coverage
|
|
15
|
+
|
|
16
|
+
# next.js
|
|
17
|
+
/.next/
|
|
18
|
+
/out/
|
|
19
|
+
|
|
20
|
+
# production
|
|
21
|
+
/build
|
|
22
|
+
|
|
23
|
+
# misc
|
|
24
|
+
.DS_Store
|
|
25
|
+
*.pem
|
|
26
|
+
|
|
27
|
+
# debug
|
|
28
|
+
npm-debug.log*
|
|
29
|
+
yarn-debug.log*
|
|
30
|
+
yarn-error.log*
|
|
31
|
+
.pnpm-debug.log*
|
|
32
|
+
|
|
33
|
+
# env files (can opt-in for committing if needed)
|
|
34
|
+
.env*
|
|
35
|
+
!.env.example
|
|
36
|
+
|
|
37
|
+
# vercel
|
|
38
|
+
.vercel
|
|
39
|
+
|
|
40
|
+
# typescript
|
|
41
|
+
*.tsbuildinfo
|
|
42
|
+
next-env.d.ts
|
|
43
|
+
|
|
44
|
+
# Python
|
|
45
|
+
__pycache__/
|
|
46
|
+
*.pyc
|
|
47
|
+
.venv/
|
workbox-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: workbox
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Workbox: SSH into your GPU boxes, and log metrics and samples from training jobs.
|
|
5
|
+
Classifier: Environment :: Console
|
|
6
|
+
Classifier: Operating System :: OS Independent
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# workbox
|
|
12
|
+
|
|
13
|
+
The Python package for Workbox: GPU boxes with Jupyter, VS Code, a terminal
|
|
14
|
+
and SSH, and training jobs that keep everything they make.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install workbox # or: uv tool install workbox
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
It has no dependencies, and works on Python 3.10 and later.
|
|
21
|
+
|
|
22
|
+
## SSH into your boxes
|
|
23
|
+
|
|
24
|
+
Sign in once on each computer. It opens your browser to approve the computer, makes a key for Workbox and adds
|
|
25
|
+
`Host *.workbox` to `~/.ssh/config`:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
workbox login --url https://your-workbox
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Then connect to a running box by its name, from the terminal or from your editor:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
workbox boxes # your boxes and their names
|
|
35
|
+
workbox ssh tinystories # or: ssh tinystories.workbox
|
|
36
|
+
scp data.csv tinystories.workbox:~/work/
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
In VS Code or Cursor, use Remote-SSH and connect to `tinystories.workbox`. A running job's machine is
|
|
40
|
+
`<project>-job-<number>.workbox`, for example `workbox ssh tinystories-job-42`.
|
|
41
|
+
|
|
42
|
+
Each connection gets a certificate for that one box, valid for 12 hours, and a one-use pass through the box's HTTPS
|
|
43
|
+
port. No port is left open and no key stays on the box. `workbox logout` signs the computer out; you can also sign
|
|
44
|
+
computers out from your account in Workbox. You need OpenSSH (`ssh` and `ssh-keygen`), which macOS, Linux and
|
|
45
|
+
Windows 10 or later have.
|
|
46
|
+
|
|
47
|
+
## Metrics and samples from your training code
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import workbox
|
|
51
|
+
|
|
52
|
+
workbox.log(step=step, loss=loss, lr=lr) # live charts on the job's page
|
|
53
|
+
workbox.sample(step=step, text=story) # or image="plot.png", or a PIL image
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Inside a Workbox job these are reported as the job runs. Anywhere else (your laptop, Colab) they do nothing, so the
|
|
57
|
+
same code runs everywhere. They never raise: a training run never fails over a chart.
|
|
58
|
+
|
|
59
|
+
## What else is in it
|
|
60
|
+
|
|
61
|
+
The same package runs inside every Workbox image: `workbox-runner` runs a job and reports to Workbox, and
|
|
62
|
+
`workbox-box` runs a box (its gateway, tools and SSH). You don't run those yourself.
|
workbox-0.2.0/README.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# workbox
|
|
2
|
+
|
|
3
|
+
The Python package for Workbox: GPU boxes with Jupyter, VS Code, a terminal
|
|
4
|
+
and SSH, and training jobs that keep everything they make.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install workbox # or: uv tool install workbox
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
It has no dependencies, and works on Python 3.10 and later.
|
|
11
|
+
|
|
12
|
+
## SSH into your boxes
|
|
13
|
+
|
|
14
|
+
Sign in once on each computer. It opens your browser to approve the computer, makes a key for Workbox and adds
|
|
15
|
+
`Host *.workbox` to `~/.ssh/config`:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
workbox login --url https://your-workbox
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Then connect to a running box by its name, from the terminal or from your editor:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
workbox boxes # your boxes and their names
|
|
25
|
+
workbox ssh tinystories # or: ssh tinystories.workbox
|
|
26
|
+
scp data.csv tinystories.workbox:~/work/
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
In VS Code or Cursor, use Remote-SSH and connect to `tinystories.workbox`. A running job's machine is
|
|
30
|
+
`<project>-job-<number>.workbox`, for example `workbox ssh tinystories-job-42`.
|
|
31
|
+
|
|
32
|
+
Each connection gets a certificate for that one box, valid for 12 hours, and a one-use pass through the box's HTTPS
|
|
33
|
+
port. No port is left open and no key stays on the box. `workbox logout` signs the computer out; you can also sign
|
|
34
|
+
computers out from your account in Workbox. You need OpenSSH (`ssh` and `ssh-keygen`), which macOS, Linux and
|
|
35
|
+
Windows 10 or later have.
|
|
36
|
+
|
|
37
|
+
## Metrics and samples from your training code
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import workbox
|
|
41
|
+
|
|
42
|
+
workbox.log(step=step, loss=loss, lr=lr) # live charts on the job's page
|
|
43
|
+
workbox.sample(step=step, text=story) # or image="plot.png", or a PIL image
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Inside a Workbox job these are reported as the job runs. Anywhere else (your laptop, Colab) they do nothing, so the
|
|
47
|
+
same code runs everywhere. They never raise: a training run never fails over a chart.
|
|
48
|
+
|
|
49
|
+
## What else is in it
|
|
50
|
+
|
|
51
|
+
The same package runs inside every Workbox image: `workbox-runner` runs a job and reports to Workbox, and
|
|
52
|
+
`workbox-box` runs a box (its gateway, tools and SSH). You don't run those yourself.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "workbox"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Workbox: SSH into your GPU boxes, and log metrics and samples from training jobs."
|
|
5
|
+
requires-python = ">=3.10"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
classifiers = [
|
|
8
|
+
"Programming Language :: Python :: 3",
|
|
9
|
+
"Operating System :: OS Independent",
|
|
10
|
+
"Environment :: Console",
|
|
11
|
+
]
|
|
12
|
+
dependencies = []
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
workbox = "workbox.cli:main"
|
|
16
|
+
workbox-runner = "workbox.runner:main"
|
|
17
|
+
workbox-box = "workbox.box:main"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["workbox"]
|
|
@@ -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
|
|
@@ -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())
|