Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions SOURCE-SHA256.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@
"serverbox/lib/view/page/setting/entry.dart": "1fb436babe99bcd456e5a5d3c38dcb51640dd9cde9574325e94f7fce50e37e4f",
"serverbox/test/unit/app/gpu_queue_test.dart": "e3514fe355b58f3a86d1cb83ccff58129532d5da132013f76cfdcc9bfeb7e854",
"tests/browser_check.py": "f5885e5acf430749364699e81fdecf257906f898c971d39f837ae70811b14cd4",
"tests/browser_monitor_check.py": "fd9ff1273517bfeb988d75b96cfb00e288bbe692073e6e3101915526e6e527a1",
"tests/browser_monitor_check.py": "60f374d662cebb4c497596195c1fd7f2f2dd898471bd6755b74d1e0a07f93926",
"tests/browser_stop_check.py": "39b4276e0c19af5ef3af8a0b9e993f2f585c9e2088c2e29b4c728001e1c7d2e0",
"tests/browser_typography_check.py": "a4304aea410b98c0b4407ad24b87c3e914194f2657a9cc0e7842ebd768b74394",
"tests/cloud.test.js": "da8dddec4638a65bb909d192f01fea7e9ff75a3b438ae08e0b76e67396defac1",
"tests/helpers.mjs": "0fe2b5d4bc3576b1a2f0e3ca443748b5d5a2652ab3e715a5305af53279cd3ca0",
"tests/local_python_server.py": "de99fc6b719c483975f196f25781e7f16122a710790eb74fd66ac8fff71d404c",
"tests/local_server.mjs": "f7b943a06fc8881d9e083a05ff556948d8f8273b6fff59bb681e6ad5633520fa",
"tests/modes.test.cjs": "f55a0afd571abe617a9c0cf1dc3f2591085d58dcad5435fd45382e6705548038",
"tests/monitor.test.js": "54fa84e136fe8d9303ec0bfa873d53a402a1cdd34adfd3eb475f32678efc5e0d",
"tests/monitor.test.js": "541a173049863f19885f83787a9387c86d703dcd2cf3f6436621965fd37397cc",
"tests/test_gpuqueue.py": "c657e41630e8f25e4b4c65b84eb9621f9cfc60389d7ed1290218c7437a669972",
"tests/test_host_monitor.py": "951bc42312a4cf24437a114cdf2881e6d6e119992d8a32d0fc4a4f73aa13c494",
"tests/test_launcher.py": "c336ce79267510501294ee1f73600b5b57ab8143469d75a8cf5d827e650e941d",
Expand All @@ -74,10 +74,10 @@
"tests/widget-update.test.cjs": "846ebaf0550e0899e5723f939fe9fb2965ac91030ab761f19be50a576bbe02a5",
"tests/widget.test.cjs": "21dde14aa712b8f3c814354af8a1323e6c7f92af866169e78dd9b4095f501faf",
"updates/gpu-queue-widget.json": "4ff3b46935ab67689c962cc22ceb3155960ff6de7572ff3435f15c481580a475",
"web/app.js": "c0b713c0fa0df7f6012dab436c27967e0d4b50dd5e913a054158bdb9f6c5144e",
"web/index.html": "65095a3bcebc12ed89db0a7c59f47da2ffa1e21b3c933471606e587f411c32b8",
"web/app.js": "8c601abf889844579eeaf6e54b6fb199530bdf216440c6d99a5f35fa17492381",
"web/index.html": "0bfb14d1118a4e5cb778eba6bc774a6c96486cb41744af2c56836980728cb72e",
"web/model.js": "55d7b7162a64eb2b142e6be6b5b4174c463a94b49d8525947e0563ba62896d4c",
"web/monitor.js": "41d58e769c1fa728600ac73a645b1d4ce1ac4ca2d49127e4e6e1bfa073bf6066",
"web/monitor.js": "84d0fc2bf2d5f366a920e5fd3fe1b97adb04a0357af5bd326c041dc4d9fd7c24",
"web/style.css": "c05706fbd5042983fd51632e531b277debdf8a22f378d109696ed980feb98162",
"worker/api.js": "65ba1c1959a75f29eb03d4eaa0b4e1d8a776d3c6003985692d11417f8680dede"
}
5 changes: 4 additions & 1 deletion serverbox/crates/sbm_parser/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,10 @@ pub const LINUX: &[CommandSpec] = &[
// retain the same command ordering.
cmd: ":",
},
CommandSpec { key: SENSORS, cmd: "sensors" },
CommandSpec {
key: SENSORS,
cmd: "if command -v sensors >/dev/null 2>&1; then sensors; fi",
},
CommandSpec {
key: DISK_SMART,
// Most distros restrict raw ATA/NVMe ioctls to root, and this runs
Expand Down
19 changes: 3 additions & 16 deletions serverbox/crates/sbm_parser/tests/script_compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -935,14 +935,8 @@ fn e2e_unix_status_script_runs() {
);
}

/// A command that cannot run says so inside its own segment.
///
/// With stderr discarded, a host without `lm-sensors` and a host with no
/// sensors are the same empty segment, and the page has nothing to tell them
/// apart with — which is why the status functions send it to stdout instead.
/// Emptying `PATH` makes every external command missing at once, which also
/// puts the attribution under test: each complaint has to land in the segment
/// of the command that made it, not in whichever one happened to be open.
/// Probe errors stay in their own segments, and a missing optional `sensors`
/// command leaves an empty segment. Emptying `PATH` exercises both behaviors.
#[cfg(unix)]
#[test]
fn e2e_unix_a_failed_command_speaks_in_its_own_segment() {
Expand Down Expand Up @@ -977,14 +971,7 @@ fn e2e_unix_a_failed_command_speaks_in_its_own_segment() {
// `echo` is a shell builtin, so the branch is still identifiable.
assert_eq!(map.get("echo").map(String::as_str), Some("__linux"));

// The wording is the shell's — dash says `not found`, bash with no PATH
// says `No such file or directory` — so what is asserted is that the
// segment is not empty and names the command that failed.
let sensors = map.get("sensors").map(String::as_str).unwrap_or_default();
assert!(sensors.contains("sensors"), "sensors: {sensors:?}");
// The complaint of the command before it stayed with the command before
// it: this segment names one command and no other.
assert!(!sensors.contains("diskstats"), "sensors: {sensors:?}");
assert!(map.get("sensors").is_none_or(String::is_empty));

// `grep` is quiet about a missing file, and the `uname -n` it falls back
// to is what complains.
Expand Down
8 changes: 6 additions & 2 deletions serverbox/scripts/gpu-task-monitor/patch_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@

OLD = 'if command -v nvidia-smi >/dev/null 2>&1; then nvidia-smi -q -x; elif [ -x /usr/lib/wsl/lib/nvidia-smi ]; then /usr/lib/wsl/lib/nvidia-smi -q -x; fi'
NEW = OLD[:-2] + 'elif [ -x "$HOME/.local/bin/serverbox-gpu-status" ]; then "$HOME/.local/bin/serverbox-gpu-status" xml; fi'
SENSORS = 'if command -v sensors >/dev/null 2>&1; then sensors; fi'
SENSORS_SEGMENT = '\techo SrvBoxSep.b64.c2Vuc29ycw==\n\t\t'


def patch_script(path):
if path.is_symlink() or path.stat().st_uid != os.getuid():
return False
raw = path.read_text()
if OLD not in raw:
patched = raw.replace(OLD, NEW).replace(
f'{SENSORS_SEGMENT}sensors\n', f'{SENSORS_SEGMENT}{SENSORS}\n')
if patched == raw:
return False
backup = path.with_suffix(path.suffix + '.before-gpu-monitor')
try:
Expand All @@ -28,7 +32,7 @@ def patch_script(path):
except FileExistsError:
pass
with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False) as stream:
stream.write(raw.replace(OLD, NEW))
stream.write(patched)
temp = Path(stream.name)
temp.chmod(stat.S_IMODE(path.stat().st_mode))
os.replace(temp, path)
Expand Down
27 changes: 21 additions & 6 deletions serverbox/scripts/gpu-task-monitor/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ def atomic_json(path, data):
os.replace(temp, path)


def _valid_fresh_ttl(value):
return type(value) in (int, float) and 0 < value < math.inf


def latest(root=ROOT):
registry = root / 'registry.json'
if registry.exists():
Expand All @@ -71,6 +75,7 @@ def latest(root=ROOT):
value = json.loads(registry.read_text())
if value.get('schema') != 1 or value.get('source') != 'gpuq':
return None
registry_ttl = value.get('fresh_ttl_s')
records = []
for item in value['resources']:
stamp = float(item.get('collected_at', 0))
Expand All @@ -85,8 +90,10 @@ def latest(root=ROOT):
not math.isfinite(number) or number < 0):
raise ValueError('Invalid GPU measurement')
state = 'ok' if item['status'] == 'online' else item['status']
records.append(dict(item, schema=1, source='gpuq', state=state,
collected_at=stamp))
record = dict(item, schema=1, source='gpuq', state=state, collected_at=stamp)
if _valid_fresh_ttl(registry_ttl) and not _valid_fresh_ttl(item.get('fresh_ttl_s')):
record['fresh_ttl_s'] = registry_ttl
records.append(record)
return max(records, key=lambda x: (fresh(x), x['state'] not in ('closed', 'failed'),
x['collected_at']), default=None)
except (OSError, ValueError, TypeError, KeyError, AttributeError):
Expand All @@ -106,7 +113,10 @@ def fresh(data, now=None, max_age=None):
if not data or data.get('state') != 'ok' or not data.get('gpus'):
return False
if max_age is None:
max_age = 90 if data.get('source') == 'gpuq' else 20
max_age = 20
if data.get('source') == 'gpuq':
ttl = data.get('fresh_ttl_s')
max_age = min(300, max(20, ttl)) if _valid_fresh_ttl(ttl) else 180
age = (time.time() if now is None else now) - data['collected_at']
return math.isfinite(age) and -5 <= age <= max_age

Expand All @@ -115,16 +125,21 @@ def status_text(data, now=None):
if not data:
return 'GPU:等待实例采集(暂无有效数据)'
labels = dict(pending='申请中', ready='实例就绪,等待采样', unknown='连接待核查',
closed='已销毁或回收(平台已确认)', failed='申请或启动失败')
closed='已销毁或回收(平台已确认)', failed='申请或启动失败',
stopped='已停止或数据过期')
retry_labels = dict(retry='查询断开,自动重连中', waiting='查询超时,自动核查中',
reconciling='正在核对原查询回执', sampling='正在重新采样')
fallback = labels['stopped']
if data.get('source') == 'gpuq':
labels['ok'] = '在线 · 采样更新等待中'
fallback = labels['unknown']
if fresh(data, now=now):
state = '实时'
elif data['state'] in ('closed', 'failed'):
elif data['state'] in ('closed', 'failed', 'stopped'):
state = labels[data['state']]
else:
state = retry_labels.get((data.get('monitor') or {}).get('state'),
labels.get(data['state'], '已停止或数据过期'))
labels.get(data['state'], fallback))
release = ' · 待释放,尚未确认销毁' if data.get('release_pending') else ''
request = f' · GPU任务 {data["request"][:8]}'
if not data.get('collected_at'):
Expand Down
45 changes: 41 additions & 4 deletions serverbox/scripts/gpu-task-monitor/test_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ def test_source_command_matches_deployed_probe(self):
lines = (root / 'crates/sbm_parser/src/commands.rs').read_text().splitlines()
line = next(line for line in lines if 'cmd:' in line and 'serverbox-gpu-status' in line)
self.assertEqual(json.loads(line.split('cmd: ', 1)[1].rstrip(',')), p.NEW)
sensors = next(lines[index + 1] for index, line in enumerate(lines) if 'key: SENSORS,' in line)
self.assertEqual(json.loads(sensors.split('cmd: ', 1)[1].rstrip(',')), p.SENSORS)

def test_native_gpu_takes_priority_and_bridge_is_opt_in(self):
with tempfile.TemporaryDirectory() as folder:
Expand All @@ -39,16 +41,51 @@ def test_native_gpu_takes_priority_and_bridge_is_opt_in(self):
def test_script_patch_is_atomic_idempotent_and_keeps_backup(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'srvboxm_v87.sh'
original = '#!/bin/sh\n' + p.OLD + '\n'
prefix = '#!/bin/sh\n\texec 2>&1\n\techo SrvBoxSep.b64.bnZpZGlh\n\t\t'
sensor_segment = '\n\techo SrvBoxSep.b64.c2Vuc29ycw==\n\t\t'
other_segment = '\n\techo unrelated\n\t\tsensors\n'
original = prefix + p.OLD + sensor_segment + 'sensors' + other_segment
path.write_text(original)
path.chmod(0o700)
inode = path.stat().st_ino
self.assertTrue(p.patch_script(path))
self.assertFalse(p.patch_script(path))
self.assertEqual(path.read_text(), '#!/bin/sh\n' + p.NEW + '\n')
self.assertEqual(path.with_suffix('.sh.before-gpu-monitor').read_text(), original)
link = Path(folder) / 'link.sh'
patched = prefix + p.NEW + sensor_segment + p.SENSORS + other_segment
self.assertEqual(path.read_text(), patched)
self.assertNotEqual(path.stat().st_ino, inode)
self.assertEqual(path.stat().st_mode & 0o777, 0o700)
backup = path.with_suffix('.sh.before-gpu-monitor')
self.assertEqual(backup.read_text(), original)
self.assertEqual(backup.stat().st_mode & 0o777, 0o600)

# Clients that already have the NVIDIA fix still need the sensor guard.
path.write_text(prefix + p.NEW + sensor_segment + 'sensors' + other_segment)
self.assertTrue(p.patch_script(path))
self.assertFalse(p.patch_script(path))
self.assertEqual(path.read_text(), patched)
self.assertEqual(backup.read_text(), original)

path.write_text(original)
link = Path(folder) / 'srvboxm_v88.sh'
link.symlink_to(path)
self.assertFalse(p.patch_script(link))
self.assertTrue(link.is_symlink())
self.assertEqual(path.read_text(), original)

def test_optional_sensors_output_is_empty_when_missing_and_preserved_when_present(self):
with tempfile.TemporaryDirectory() as folder:
script = Path(folder) / 'srvboxm_v88.sh'
script.write_text(f'#!/bin/sh\nexec 2>&1\n{p.SENSORS_SEGMENT}sensors\n')
self.assertTrue(p.patch_script(script))
cmd = ['/bin/sh', str(script)]
env = dict(os.environ, PATH=folder)
marker = 'SrvBoxSep.b64.c2Vuc29ycw==\n'
self.assertEqual(subprocess.check_output(cmd, env=env, text=True), marker)

sensors = Path(folder) / 'sensors'
sensors.write_text('#!/bin/sh\nprintf "fixture-sensor\\n"\n')
sensors.chmod(0o700)
self.assertEqual(subprocess.check_output(cmd, env=env, text=True), marker + 'fixture-sensor\n')


if __name__ == '__main__':
Expand Down
57 changes: 52 additions & 5 deletions serverbox/scripts/gpu-task-monitor/test_telemetry.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from contextlib import redirect_stdout
import importlib.util
import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET

spec = importlib.util.spec_from_file_location('telemetry', Path(__file__).with_name('telemetry.py'))
Expand Down Expand Up @@ -34,7 +38,7 @@ def test_unavailable_is_not_zero(self):
def test_stale_error_stopped_and_future_samples_are_not_live(self):
data = self.sample()
self.assertTrue(t.fresh(data, now=115))
self.assertFalse(t.fresh(data, now=121))
self.assertFalse(t.fresh(dict(data, fresh_ttl_s=300), now=121))
self.assertFalse(t.fresh(data, now=90))
for state in ['stopped', 'error']:
self.assertFalse(t.fresh(dict(data, state=state), now=101))
Expand All @@ -50,8 +54,8 @@ def test_atomic_private_snapshot_and_partial_input(self):
self.assertEqual(t.latest(root)['gpus'][0]['temperature_c'], 63)
self.assertEqual(json.loads(path.read_text())['state'], 'ok')

def registry(self, root, resources):
t.atomic_json(root/'registry.json', dict(schema=1, source='gpuq', resources=resources))
def registry(self, root, resources, **fields):
t.atomic_json(root/'registry.json', dict(schema=1, source='gpuq', resources=resources, **fields))

def record(self, request, status='online', stamp=100):
return dict(request=request, status=status, collected_at=stamp,
Expand Down Expand Up @@ -79,10 +83,53 @@ def test_registry_refresh_does_not_refresh_old_gpu_timestamp(self):
root = Path(folder)
self.registry(root, [self.record('new')])
data = t.latest(root)
self.assertTrue(t.fresh(data, now=185))
self.assertFalse(t.fresh(data, now=191))
self.assertEqual(data['collected_at'], 100)
self.assertTrue(t.fresh(data, now=235))
self.assertTrue(t.fresh(data, now=280))
self.assertFalse(t.fresh(data, now=281))
self.assertFalse(t.fresh(data, now=90))

def test_registry_ttl_precedence_and_bounds(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
record = self.record('new')
for override, max_age in [(None, 240), (60, 60), (1, 20), (600, 300),
('60', 240), (True, 240), (-1, 240), (0, 240)]:
with self.subTest(override=override):
self.registry(root, [dict(record, fresh_ttl_s=override)], fresh_ttl_s=240)
data = t.latest(root)
self.assertTrue(t.fresh(data, now=100 + max_age))
self.assertFalse(t.fresh(data, now=101 + max_age))
for invalid_ttl in [float('inf'), float('nan')]:
data = dict(record, source='gpuq', state='ok', fresh_ttl_s=invalid_ttl)
self.assertTrue(t.fresh(data, now=280))
self.assertFalse(t.fresh(data, now=281))

def test_xml_command_suppresses_samples_past_default_and_custom_windows(self):
sample = dict(self.sample(), source='gpuq')
for ttl, now, live in [(None, 235, True), (None, 281, False),
(60, 160, True), (60, 161, False)]:
with self.subTest(ttl=ttl, now=now), patch.object(t, 'latest', return_value=dict(sample, fresh_ttl_s=ttl)), \
patch.object(t.time, 'time', return_value=now), patch.object(t.os, 'umask'), \
patch.object(sys, 'argv', ['telemetry.py', 'xml']), redirect_stdout(io.StringIO()) as out:
t.main()
if live:
xml = ET.fromstring(out.getvalue())
self.assertEqual(xml.findtext('timestamp'), '1970-01-01T08:01:40+08:00')
else:
self.assertEqual(out.getvalue(), '')

def test_expired_online_sample_is_distinct_from_stopped_collector(self):
sample = dict(self.sample(), source='gpuq')
self.assertEqual(t.status_text(sample, now=281).split(' · 采集于')[0],
'GPU:在线 · 采样更新等待中')
self.assertEqual(t.status_text(dict(sample, monitor={'state': 'retry'}), now=281).split(' · 采集于')[0],
'GPU:查询断开,自动重连中')
stopped = dict(sample, state='stopped', monitor={'state': 'retry'})
for data in [stopped, self.sample(), dict(self.sample(), state='error')]:
self.assertEqual(t.status_text(data, now=281).split(' · 采集于')[0],
'GPU:已停止或数据过期')

def test_invalid_registry_metrics_fail_closed(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
Expand Down
10 changes: 8 additions & 2 deletions tests/browser_monitor_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,16 @@ def state(route):
download.value.save_as(OUT / 'fixture-monitor.json')
exported = json.loads((OUT / 'fixture-monitor.json').read_text())
assert len(exported['resources'][0]['history']) == 2
sample_at = time.time() - 100
sample_at = time.time() - 135
page.locator('#refresh').click()
expect(page.locator('.monitor-status')).to_contain_text('采样过期')
expect(page.locator('.monitor-status.fresh')).to_have_text('在线')
expect(page.locator('#server-resources')).to_contain_text('61 °C')
expect(page.locator('#gpu-value')).to_have_text('65%')
sample_at = time.time() - 181
page.locator('#refresh').click()
expect(page.locator('.monitor-status')).to_have_text('在线 · 采样更新等待中')
expect(page.locator('#server-resources')).not_to_contain_text('61 °C')
expect(page.locator('#gpu-value')).to_have_text('—')
page.unroute('**/api/state')
page.route('**/api/state', lambda route: route.abort())
page.locator('#refresh').click()
Expand Down
Loading
Loading