- sidecar: POST /wol (routes_wol.py, host only) — strict MAC / IPv4 /
port checks, a UDP magic packet with SO_BROADCAST.
- manifest: the machines.wake capability (operator-approved) and
provides: machine.wake.
- plugins/hubwake.py: the machines.wake bridge for the plugin's own
handlers — POST …/hub/wol, POST …/hub/workers/{wid}/probe,
GET …/hub/wake/workers (each also under …/bridge/…).
- plugins/machine_wake.py: list_wakeable (30 s cache, dropped on the
provider's actions / install changes, SSE machine-wake), wake_machine,
maybe_wake_and_wait, probe_in_background.
- runs/service.py: a run pinned to an offline worker, and a resume of a
session on one, wait for an auto-wake before the 409 worker_offline;
an unpinned run still falls back to the next runner up, no wake.
- GET /api/machines/wakeable (lab.read), POST /api/machines/{id}/wake
(workers.manage), schemas + regenerated openapi / orval types.
- Settings → Machines: ⚡ Wake on an offline worker the plugin has
configured (Waking… until the workers SSE flips it online).
- tests: sidecar/test_wol.py, backend/test_machine_wake.py,
WakeButton.test.tsx; docs/plugins.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
444 lines
22 KiB
Python
444 lines
22 KiB
Python
"""Wake-on-LAN core support (2026-11-26, for the ``wake-on-lan`` plugin): the
|
|
``machines.wake`` capability and ``provides: machine.wake``, the
|
|
``plugins/machine_wake.py`` hook (list cache, wake, ``maybe_wake_and_wait``),
|
|
the ``machines.wake`` bridge (``plugins/hubwake.py``), the auto-wake of a
|
|
pinned spawn / a resume on an offline worker (an unpinned one falls back
|
|
without waking), and ``GET /api/machines/wakeable`` + ``POST
|
|
/api/machines/{id}/wake``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"ARCHIVE_DIR": TMP / "arch", "META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror", "CRON_PATH": TMP / "cron.json",
|
|
"PROFILES_PATH": TMP / "profiles.json", "USERS_PATH": TMP / "users.json",
|
|
"AUTH_PATH": TMP / "auth.json", "INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import accounts # noqa: E402
|
|
import main # noqa: E402
|
|
import workers # noqa: E402
|
|
from plugins import hubwake, machine_wake # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_summary, requires_operator, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from runs.service import _send_message # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
from users.caller import guest_from_record # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
MF = {"schema": 1, "id": "wake-on-lan", "name": "Wake-on-LAN",
|
|
"capabilities": ["machines.wake", "workers.read"],
|
|
"actions": {"wake": {"script": "handlers/wake.py"},
|
|
"view": {"script": "handlers/wake.py", "readOnly": True}},
|
|
"provides": {"machine.wake": "wake"}}
|
|
# list → w1 configured + autoWake, w2 configured manual-only, ../x dropped;
|
|
# wake → sent for w1/w2, refused for anything else.
|
|
HANDLER = """import json, sys
|
|
p = json.load(sys.stdin)
|
|
cfg = {"w1": {"configured": True, "mac": "aa:bb:cc:dd:ee:ff", "broadcast": "192.168.1.255",
|
|
"autoWake": True, "timeoutSec": 30, "lastWokenAt": None},
|
|
"w2": {"configured": True, "mac": "aa:bb:cc:dd:ee:00", "autoWake": False, "timeoutSec": 5},
|
|
"../x": {"configured": True}}
|
|
if p.get("op") == "list":
|
|
print(json.dumps({"machines": cfg}))
|
|
elif p.get("op") == "wake":
|
|
m = p.get("machineId")
|
|
ok = m in ("w1", "w2")
|
|
print(json.dumps({"ok": ok, "sent": ok, "configured": ok,
|
|
"autoWake": bool(ok and cfg[m]["autoWake"]),
|
|
"timeoutSec": cfg[m]["timeoutSec"] if ok else None, "trigger": p.get("trigger")}))
|
|
else:
|
|
print("{}")
|
|
"""
|
|
FILES = {"handlers/wake.py": HANDLER}
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, files: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest))
|
|
for rel, body in files.items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(body)
|
|
return root
|
|
|
|
|
|
def _install(td, manifest=MF, files=FILES) -> PluginStore:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", manifest, files)),
|
|
is_owner=True, approve=True)
|
|
return store
|
|
|
|
|
|
class FakeWorkers:
|
|
"""A worker store whose ``online`` set the tests move."""
|
|
|
|
def __init__(self, ws, online=()):
|
|
self.w = {w["id"]: w for w in ws}
|
|
self.on = set(online)
|
|
self.st: dict[str, dict] = {}
|
|
|
|
def list(self):
|
|
return list(self.w.values())
|
|
|
|
def get(self, wid):
|
|
return self.w.get(wid)
|
|
|
|
def online(self, wid):
|
|
return wid in self.on
|
|
|
|
def status(self, wid):
|
|
return {"status": "online" if wid in self.on else "offline", **self.st.get(wid, {})}
|
|
|
|
def set_status(self, wid, **st):
|
|
self.st.setdefault(wid, {}).update(st)
|
|
if st.get("status") == "online":
|
|
self.on.add(wid)
|
|
return True
|
|
|
|
|
|
WS = [{"id": "w1", "name": "Tower", "url": "http://192.168.1.20:8790", "host": "192.168.1.20",
|
|
"hostname": "tower", "token": "secret"},
|
|
{"id": "w2", "name": "Laptop", "url": "http://10.0.0.2:8790", "token": "secret"},
|
|
{"id": "g1", "name": "Cel's", "url": "http://x:1", "token": "t", "owner": "cel"},
|
|
{"id": "p1", "name": "Pending", "url": "http://x:1", "token": "t", "pending": True}]
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
def setUp(self):
|
|
machine_wake.invalidate()
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.store = _install(self.td.name)
|
|
self.workers = FakeWorkers(WS)
|
|
self.published: list[dict] = []
|
|
self.patches = [mock.patch.object(DEPS, "plugin_store", self.store),
|
|
mock.patch.object(DEPS, "worker_store", self.workers),
|
|
mock.patch.object(DEPS.hub, "publish", side_effect=self.published.append),
|
|
mock.patch.object(machine_wake, "POLL_S", 0.0)]
|
|
for p in self.patches:
|
|
p.start()
|
|
|
|
def tearDown(self):
|
|
for p in reversed(self.patches):
|
|
p.stop()
|
|
self.td.cleanup()
|
|
machine_wake.invalidate()
|
|
|
|
|
|
# ── manifest ─────────────────────────────────────────────────────────────────
|
|
class Manifest(unittest.TestCase):
|
|
def test_capability_and_provides_validate_and_ask_the_operator(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "p", MF, FILES))
|
|
self.assertEqual(mf["capabilities"], ["machines.wake", "workers.read"])
|
|
self.assertEqual(mf["provides"], {"machine.wake": "wake"})
|
|
self.assertTrue(requires_operator(mf))
|
|
labels = capability_summary(mf)
|
|
self.assertTrue(any(i["kind"] == "provides" and i.get("privileged") and "Wakes" in i["label"]
|
|
for i in labels))
|
|
self.assertTrue(any(i["kind"] == "capability" and i.get("privileged") and "Wake-on-LAN" in i["label"]
|
|
for i in labels))
|
|
|
|
def test_provides_must_name_a_declared_action(self):
|
|
with tempfile.TemporaryDirectory() as td, self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "p", {**MF, "provides": {"machine.wake": "nope"}}, FILES))
|
|
|
|
|
|
# ── the hook ─────────────────────────────────────────────────────────────────
|
|
class Hook(Base):
|
|
def test_list_normalized_and_cached(self):
|
|
got = machine_wake.list_wakeable(DEPS)
|
|
self.assertEqual(sorted(got), ["w1", "w2"]) # ../x dropped
|
|
self.assertEqual(got["w1"], {"configured": True, "mac": "aa:bb:cc:dd:ee:ff",
|
|
"broadcast": "192.168.1.255", "autoWake": True,
|
|
"timeoutSec": 30, "lastWokenAt": None})
|
|
self.assertFalse(got["w2"]["autoWake"])
|
|
with mock.patch("plugins.runner.run_script") as run:
|
|
machine_wake.list_wakeable(DEPS)
|
|
run.assert_not_called() # cached
|
|
|
|
def test_a_write_action_drops_the_cache_a_read_only_one_doesnt(self):
|
|
machine_wake.list_wakeable(DEPS)
|
|
tc = TestClient(main.app, headers=OWNER_H)
|
|
tc.post("/api/plugins/wake-on-lan/actions/view", json={})
|
|
self.assertIsNotNone(machine_wake._cache)
|
|
self.assertNotIn({"type": "machine-wake"}, self.published)
|
|
tc.post("/api/plugins/wake-on-lan/actions/wake", json={"op": "noop"})
|
|
self.assertIsNone(machine_wake._cache)
|
|
self.assertIn({"type": "machine-wake"}, self.published)
|
|
|
|
def test_no_provider(self):
|
|
with tempfile.TemporaryDirectory() as td, \
|
|
mock.patch.object(DEPS, "plugin_store", PluginStore(pathlib.Path(td))):
|
|
self.assertEqual(machine_wake.list_wakeable(DEPS), {})
|
|
res = machine_wake.wake_machine(DEPS, "w1")
|
|
self.assertEqual((res["ok"], res["sent"]), (False, False))
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "w1"))
|
|
|
|
def test_wake_machine(self):
|
|
res = machine_wake.wake_machine(DEPS, "w1")
|
|
self.assertEqual((res["ok"], res["sent"], res["configured"], res["autoWake"], res["timeoutSec"]),
|
|
(True, True, True, True, 30))
|
|
self.assertEqual(res["trigger"], "machine.wake")
|
|
self.assertFalse(machine_wake.wake_machine(DEPS, "nope")["ok"])
|
|
self.assertIn("bad", machine_wake.wake_machine(DEPS, "../x")["error"])
|
|
|
|
def test_maybe_wake_and_wait_wakes_then_polls_until_online(self):
|
|
probes = []
|
|
|
|
def probe(store, w):
|
|
probes.append(w["id"])
|
|
if len(probes) >= 3:
|
|
store.on.add(w["id"])
|
|
return True
|
|
with mock.patch.object(workers, "probe", side_effect=probe), \
|
|
mock.patch.object(machine_wake, "wake_machine", wraps=machine_wake.wake_machine) as wake:
|
|
self.assertTrue(machine_wake.maybe_wake_and_wait(DEPS, "w1"))
|
|
wake.assert_called_once_with(DEPS, "w1")
|
|
self.assertEqual(probes, ["w1"] * 3)
|
|
self.assertIn({"type": "workers"}, self.published)
|
|
|
|
def test_maybe_wake_and_wait_gives_up_after_the_clamped_timeout(self):
|
|
clock = iter(range(0, 10_000, 5))
|
|
with mock.patch.object(workers, "probe", return_value=False) as probe, \
|
|
mock.patch.object(machine_wake.time, "monotonic", side_effect=lambda: next(clock)):
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "w1"))
|
|
# timeoutSec 30 at 5 s a tick: a handful of probes, never forever
|
|
self.assertTrue(1 <= probe.call_count <= 8, probe.call_count)
|
|
|
|
def test_no_wait_when_not_auto_or_not_configured_or_not_the_owners(self):
|
|
with mock.patch.object(workers, "probe") as probe, \
|
|
mock.patch.object(machine_wake, "wake_machine") as wake:
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "w2")) # autoWake off
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "nope")) # unknown
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "g1")) # a guest's
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "p1")) # pending
|
|
wake.assert_not_called()
|
|
probe.assert_not_called()
|
|
|
|
def test_not_sent_means_no_wait(self):
|
|
with mock.patch.object(machine_wake, "wake_machine", return_value={"ok": True, "sent": False}), \
|
|
mock.patch.object(workers, "probe") as probe:
|
|
self.assertFalse(machine_wake.maybe_wake_and_wait(DEPS, "w1"))
|
|
probe.assert_not_called()
|
|
|
|
def test_normalize(self):
|
|
out = machine_wake.normalize({"machines": {"w1": {"configured": "yes", "autoWake": 1,
|
|
"timeoutSec": "45"}, "w 2": {}, "w3": "x"}})
|
|
self.assertEqual(out, {"w1": {"configured": False, "mac": None, "broadcast": None,
|
|
"autoWake": False, "timeoutSec": 45, "lastWokenAt": None}})
|
|
self.assertEqual(machine_wake.normalize(None), {})
|
|
|
|
|
|
# ── the machines.wake bridge ─────────────────────────────────────────────────
|
|
class Bridge(Base):
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.tc = TestClient(main.app)
|
|
self.h = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'wake-on-lan', ttl=600)}"}
|
|
self.base = "/proxy/tools/plugins/wake-on-lan"
|
|
|
|
def test_wol_forwards_to_the_host_sidecar(self):
|
|
reply = {"ok": True, "mac": "aa:bb:cc:dd:ee:ff", "broadcast": "192.168.1.255", "port": 9}
|
|
for prefix in ("hub", "bridge"):
|
|
with mock.patch("runs.sidecar_client._sidecar_call", return_value=reply) as call:
|
|
r = self.tc.post(f"{self.base}/{prefix}/wol", headers=self.h, json={"mac": "AA-BB-CC-DD-EE-FF"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), reply)
|
|
self.assertEqual(call.call_args.args[1:],
|
|
("/wol", {"mac": "AA-BB-CC-DD-EE-FF", "broadcast": "192.168.1.255", "port": 9}))
|
|
|
|
def test_wol_refuses_bad_bodies_before_the_sidecar(self):
|
|
with mock.patch("runs.sidecar_client._sidecar_call") as call:
|
|
for body in ({"mac": "zz:bb:cc:dd:ee:ff"}, {"mac": "aa:bb:cc:dd:ee"}, {"mac": "aa:bb:cc:dd:ee:ff\n"},
|
|
{"mac": "aa:bb:cc:dd:ee:ff", "broadcast": "lan.local"},
|
|
{"mac": "aa:bb:cc:dd:ee:ff", "port": 0}, {"mac": "aa:bb:cc:dd:ee:ff", "port": 70000},
|
|
{"mac": "aa:bb:cc:dd:ee:ff", "port": True}, ["x"]):
|
|
r = self.tc.post(f"{self.base}/hub/wol", headers=self.h, json=body)
|
|
self.assertEqual(r.status_code, 400, body)
|
|
self.assertEqual(r.json()["detail"]["kind"], "bad_request")
|
|
call.assert_not_called()
|
|
|
|
def test_wol_passes_a_sidecar_error_through(self):
|
|
err = HTTPException(502, {"message": "sidecar unreachable", "kind": "sidecar"})
|
|
with mock.patch("runs.sidecar_client._sidecar_call", side_effect=err):
|
|
r = self.tc.post(f"{self.base}/hub/wol", headers=self.h, json={"mac": "aa:bb:cc:dd:ee:ff"})
|
|
self.assertEqual(r.status_code, 502)
|
|
self.assertEqual(r.json()["error"]["kind"], "sidecar")
|
|
|
|
def test_probe(self):
|
|
def probe(store, w):
|
|
store.set_status(w["id"], status="online", lastSeen="2026-11-26T10:00:00Z")
|
|
return True
|
|
with mock.patch.object(workers, "probe", side_effect=probe):
|
|
r = self.tc.post(f"{self.base}/bridge/workers/w1/probe", headers=self.h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"online": True, "status": "online", "lastSeen": "2026-11-26T10:00:00Z"})
|
|
self.assertIn({"type": "workers"}, self.published)
|
|
with mock.patch.object(workers, "probe", return_value=False):
|
|
r = self.tc.post(f"{self.base}/hub/workers/w2/probe", headers=self.h)
|
|
self.assertEqual(r.json(), {"online": False, "status": "offline", "lastSeen": None})
|
|
for wid in ("g1", "p1", "nope"):
|
|
r = self.tc.post(f"{self.base}/hub/workers/{wid}/probe", headers=self.h)
|
|
self.assertEqual(r.status_code, 404, wid)
|
|
|
|
def test_workers_safe_fields(self):
|
|
for path in ("hub/wake/workers", "bridge/workers"):
|
|
r = self.tc.get(f"{self.base}/{path}", headers=self.h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
rows = r.json()["workers"]
|
|
self.assertEqual([w["id"] for w in rows], ["w1", "w2"])
|
|
self.assertEqual(rows[0], {"id": "w1", "name": "Tower", "host": "192.168.1.20", "hostname": "tower",
|
|
"status": "offline", "running": 0, "lastSeen": None})
|
|
self.assertEqual(rows[1]["host"], "10.0.0.2")
|
|
self.assertNotIn("secret", r.text)
|
|
|
|
def test_only_the_plugins_owner_handler_with_the_capability(self):
|
|
guest = {"Authorization": f"Bearer {access.mint_handler('cel', 'wake-on-lan', ttl=600)}"}
|
|
self.assertIn(self.tc.get(f"{self.base}/bridge/workers", headers=guest).status_code, (403, 404))
|
|
self.assertEqual(self.tc.get(f"{self.base}/bridge/workers").status_code, 401)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bare = _install(td, {**MF, "capabilities": ["workers.read"]})
|
|
with mock.patch.object(DEPS, "plugin_store", bare):
|
|
r = self.tc.post(f"{self.base}/hub/wol", headers=self.h, json={"mac": "aa:bb:cc:dd:ee:ff"})
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
|
|
# ── the hub API ──────────────────────────────────────────────────────────────
|
|
class Api(Base):
|
|
def test_wakeable(self):
|
|
r = TestClient(main.app, headers=OWNER_H).get("/api/machines/wakeable")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(sorted(r.json()["machines"]), ["w1", "w2"])
|
|
|
|
def test_wake_sends_and_probes_in_the_background(self):
|
|
with mock.patch.object(machine_wake, "probe_in_background") as bg:
|
|
r = TestClient(main.app, headers=OWNER_H).post("/api/machines/w2/wake")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual((r.json()["ok"], r.json()["sent"]), (True, True))
|
|
bg.assert_called_once_with(DEPS, "w2")
|
|
self.assertEqual(TestClient(main.app, headers=OWNER_H).post("/api/machines/g1/wake").status_code, 404)
|
|
self.assertEqual(TestClient(main.app, headers=OWNER_H).post("/api/machines/nope/wake").status_code, 404)
|
|
|
|
def test_wake_without_a_provider_is_a_409(self):
|
|
with tempfile.TemporaryDirectory() as td, \
|
|
mock.patch.object(DEPS, "plugin_store", PluginStore(pathlib.Path(td))):
|
|
r = TestClient(main.app, headers=OWNER_H).post("/api/machines/w1/wake")
|
|
self.assertEqual(r.status_code, 409)
|
|
|
|
def test_background_probe_stops_once_online(self):
|
|
calls = []
|
|
|
|
def probe(store, w):
|
|
calls.append(1)
|
|
store.on.add(w["id"])
|
|
return True
|
|
with mock.patch.object(workers, "probe", side_effect=probe):
|
|
machine_wake.probe_in_background(DEPS, "w1", every_s=0.0, for_s=5).join(5)
|
|
self.assertEqual(len(calls), 1)
|
|
self.assertIn({"type": "workers"}, self.published)
|
|
|
|
def test_owner_only_and_the_route_table(self):
|
|
from authz.routes import TABLE
|
|
from plugins.routes import machine_wake_now, machines_wakeable
|
|
guest = guest_from_record({"id": "cel", "name": "Cel"})
|
|
for call in (lambda: machines_wakeable(DEPS, guest), lambda: machine_wake_now(DEPS, guest, "w1")):
|
|
with self.assertRaises(HTTPException) as e:
|
|
call()
|
|
self.assertEqual(e.exception.status_code, 403)
|
|
self.assertEqual(TABLE[("GET", "/api/machines/wakeable")], "lab.read")
|
|
self.assertEqual(TABLE[("POST", "/api/machines/{worker_id}/wake")], "workers.manage")
|
|
|
|
|
|
# ── the send path ────────────────────────────────────────────────────────────
|
|
class SendPath(unittest.TestCase):
|
|
"""A real (fake) worker paired and made offline: a run pinned to it, or a
|
|
resume of a session on it, waits for the wake; an unpinned one doesn't."""
|
|
|
|
SID = "33333333-2222-3333-4444-555555555555"
|
|
|
|
def setUp(self):
|
|
from _fakeworker import FakeWorker
|
|
self.fw = FakeWorker(TMP / "remote", TMP / "state")
|
|
self.w = workers.pair(DEPS.worker_store, self.fw.pairing_string("work"),
|
|
account=None, name="mac", hub_name="t",
|
|
resolve_login=lambda _l: None, valid_account=accounts.valid)
|
|
DEPS.profile_store.assign_worker(self.w, "work")
|
|
DEPS.profile_store.patch_runner(self.w["id"], {"default": True})
|
|
DEPS.worker_store.set_status(self.w["id"], status="offline")
|
|
|
|
def tearDown(self):
|
|
self.fw.stop()
|
|
DEPS.worker_store.delete(self.w["id"])
|
|
DEPS.profile_store.forget_worker(self.w["id"])
|
|
|
|
def _wakes(self, ok=True):
|
|
def wake(deps, wid):
|
|
if ok:
|
|
deps.worker_store.set_status(wid, status="online")
|
|
return ok
|
|
return mock.patch.object(machine_wake, "maybe_wake_and_wait", side_effect=wake)
|
|
|
|
def test_a_pinned_spawn_waits_for_the_wake(self):
|
|
with self._wakes() as wake:
|
|
out = _send_message(DEPS, "hi", worker=self.w["id"])
|
|
wake.assert_called_once_with(DEPS, self.w["id"])
|
|
self.assertEqual(self.fw.calls[-1][0], "/spawn")
|
|
self.assertEqual(DEPS.meta_store.get(out["sessionId"])["worker"], self.w["id"])
|
|
|
|
def test_a_pinned_spawn_whose_wake_fails_is_still_a_409(self):
|
|
with self._wakes(ok=False) as wake, self.assertRaises(HTTPException) as cm:
|
|
_send_message(DEPS, "hi", worker=self.w["id"])
|
|
wake.assert_called_once()
|
|
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
|
|
self.assertEqual(self.fw.calls, [])
|
|
|
|
def test_an_unpinned_spawn_never_wakes(self):
|
|
with self._wakes() as wake:
|
|
for kw in ({"profile": "work"}, {"account": "work"}):
|
|
with self.assertRaises(HTTPException) as cm:
|
|
_send_message(DEPS, "hi", **kw)
|
|
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
|
|
wake.assert_not_called()
|
|
|
|
def test_an_unpinned_spawn_falls_back_to_the_next_runner_up_without_waking(self):
|
|
dev = DEPS.worker_store.put({**self.w, "id": "devbox000002", "name": "devbox"})
|
|
DEPS.worker_store.set_status(dev["id"], status="online")
|
|
try:
|
|
DEPS.profile_store.assign_worker(dev, "work")
|
|
with self._wakes() as wake:
|
|
out = _send_message(DEPS, "hi", profile="work")
|
|
wake.assert_not_called()
|
|
self.assertEqual(DEPS.meta_store.get(out["sessionId"])["worker"], dev["id"])
|
|
finally:
|
|
DEPS.worker_store.delete(dev["id"])
|
|
DEPS.profile_store.forget_worker(dev["id"])
|
|
|
|
def test_a_resume_on_an_offline_worker_waits_for_the_wake(self):
|
|
DEPS.meta_store.update(self.SID, {"worker": self.w["id"], "account": "work", "state": "finished"})
|
|
with self._wakes(ok=False), self.assertRaises(HTTPException) as cm:
|
|
_send_message(DEPS, "more", session_id=self.SID, cwd="/Users/g/repo")
|
|
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
|
|
with self._wakes() as wake:
|
|
_send_message(DEPS, "more", session_id=self.SID, cwd="/Users/g/repo")
|
|
wake.assert_called_once_with(DEPS, self.w["id"])
|
|
self.assertEqual(self.fw.calls[-1][0], "/resume")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|