- 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>
269 lines
10 KiB
Python
269 lines
10 KiB
Python
"""Waking the owner's sleeping workers, from a live plugin
|
||
(``provides: {"machine.wake": "<action>"}`` — the ``wake-on-lan`` plugin,
|
||
2026-11-26).
|
||
|
||
The provider's action runs as the owner with one of two payloads:
|
||
|
||
* ``{"op": "list"}`` → ``{"machines": {<workerId>: {"configured": true, "mac",
|
||
"broadcast", "autoWake": bool, "timeoutSec": int, "lastWokenAt": str|null}}}``
|
||
— which workers it can wake (:func:`list_wakeable`, cached :data:`TTL_SECS`);
|
||
* ``{"op": "wake", "machineId": <workerId>}`` → ``{"ok", "sent", "configured",
|
||
"autoWake", "timeoutSec", …}`` — it sends the magic packet through the
|
||
``machines.wake`` bridge (host sidecar ``POST /wol``, ``plugins/hubwake.py``)
|
||
(:func:`wake_machine`).
|
||
|
||
:func:`maybe_wake_and_wait` is what the send path calls before refusing a run
|
||
**pinned** to an offline worker, or a resume of a session that lives on one
|
||
(``runs/service.py``): a worker set to ``autoWake`` is woken and probed every
|
||
:data:`POLL_S` until it answers (or its ``timeoutSec``, clamped 10–120 s). An
|
||
unpinned run never waits here — it takes the profile's next runner that is up.
|
||
``GET /api/machines/wakeable`` and ``POST /api/machines/{id}/wake`` (the
|
||
⚡ Wake button on an offline worker's card) are in ``plugins/routes.py``.
|
||
|
||
:func:`touched` drops the cache and publishes SSE ``{"type": "machine-wake"}``
|
||
when the provider ran something that may change it (not a ``readOnly``
|
||
action), or was installed, enabled, disabled or uninstalled (:func:`changed`).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import re
|
||
import threading
|
||
import time
|
||
from typing import Any
|
||
|
||
from plugins.store import OWNER_UID
|
||
|
||
log = logging.getLogger(__name__)
|
||
|
||
PROVIDES = "machine.wake"
|
||
TTL_SECS = 30.0
|
||
POLL_S = 2.5
|
||
MIN_WAIT_S, MAX_WAIT_S = 10, 120
|
||
MAX_MACHINES = 200
|
||
_MACHINE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
||
|
||
_lock = threading.Lock()
|
||
_cache: tuple[float, dict[str, dict[str, Any]]] | None = None
|
||
|
||
|
||
def invalidate() -> None:
|
||
global _cache
|
||
with _lock:
|
||
_cache = None
|
||
|
||
|
||
def changed() -> None:
|
||
"""A provider came or went (install, enable, disable, uninstall)."""
|
||
invalidate()
|
||
|
||
|
||
def provides(rec: dict[str, Any] | None) -> bool:
|
||
return PROVIDES in (((rec or {}).get("manifest") or {}).get("provides") or {})
|
||
|
||
|
||
def touched(deps, rec: dict[str, Any] | None, *, action: str | None = None) -> None:
|
||
"""The plugin ``rec`` ran something: when it provides machine wake (and
|
||
``action``, if named, isn't read-only), drop the cache and tell the app
|
||
to refetch."""
|
||
if not provides(rec):
|
||
return
|
||
if action:
|
||
act = (((rec or {}).get("manifest") or {}).get("actions") or {}).get(action) or {}
|
||
if act.get("readOnly"):
|
||
return
|
||
invalidate()
|
||
_publish(deps, {"type": "machine-wake"})
|
||
|
||
|
||
def _publish(deps, ev: dict) -> None:
|
||
try:
|
||
deps.hub.publish(ev)
|
||
except Exception: # noqa: BLE001 — no hub (tests)
|
||
pass
|
||
|
||
|
||
def _provider(deps) -> tuple[dict[str, Any], str] | None:
|
||
"""The owner's first enabled, approved plugin providing ``machine.wake``."""
|
||
from plugins.waiting import _providers_for
|
||
try:
|
||
found = _providers_for(deps, OWNER_UID, PROVIDES)
|
||
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
|
||
return None
|
||
for rec, _grant in found:
|
||
mf = rec.get("manifest") or {}
|
||
act = (mf.get("provides") or {}).get(PROVIDES)
|
||
if act in (mf.get("actions") or {}):
|
||
return rec, act
|
||
return None
|
||
|
||
|
||
def has_provider(deps) -> bool:
|
||
return _provider(deps) is not None
|
||
|
||
|
||
def _run(deps, payload: dict[str, Any], timeout: int = 20) -> Any:
|
||
"""The provider's action on ``payload``; None without one or on failure."""
|
||
prov = _provider(deps)
|
||
if not prov:
|
||
return None
|
||
rec, action = prov
|
||
from plugins.runner import run_script
|
||
act = (rec.get("manifest") or {}).get("actions", {}).get(action) or {}
|
||
try:
|
||
return run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
|
||
payload={"trigger": PROVIDES, **payload},
|
||
timeout_sec=min(timeout, int(act.get("timeoutSec") or timeout)))
|
||
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
|
||
log.warning("%s %s via %s failed: %s", PROVIDES, payload.get("op"), rec.get("id"), e)
|
||
return None
|
||
|
||
|
||
def _int(v: Any, default: int | None = None) -> int | None:
|
||
if isinstance(v, bool):
|
||
return default
|
||
try:
|
||
return int(v)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def _str(v: Any, n: int = 64) -> str | None:
|
||
return v[:n] if isinstance(v, str) and v.strip() else None
|
||
|
||
|
||
def normalize(raw: Any) -> dict[str, dict[str, Any]]:
|
||
"""A ``list`` answer → ``{workerId: entry}`` (valid ids, known fields)."""
|
||
machines = raw.get("machines") if isinstance(raw, dict) else None
|
||
out: dict[str, dict[str, Any]] = {}
|
||
for wid, m in (machines.items() if isinstance(machines, dict) else []):
|
||
if not isinstance(wid, str) or not _MACHINE_RE.fullmatch(wid) or not isinstance(m, dict):
|
||
continue
|
||
out[wid] = {
|
||
"configured": m.get("configured") is True,
|
||
"mac": _str(m.get("mac"), 17),
|
||
"broadcast": _str(m.get("broadcast"), 15),
|
||
"autoWake": m.get("autoWake") is True,
|
||
"timeoutSec": _int(m.get("timeoutSec")),
|
||
"lastWokenAt": _str(m.get("lastWokenAt")),
|
||
}
|
||
if len(out) >= MAX_MACHINES:
|
||
break
|
||
return out
|
||
|
||
|
||
def list_wakeable(deps) -> dict[str, dict[str, Any]]:
|
||
"""What the provider can wake (copies), cached :data:`TTL_SECS`; ``{}``
|
||
without a provider."""
|
||
global _cache
|
||
now = time.monotonic()
|
||
with _lock:
|
||
c = _cache
|
||
if c is not None and now - c[0] < TTL_SECS:
|
||
return {k: dict(v) for k, v in c[1].items()}
|
||
got = normalize(_run(deps, {"op": "list"})) if has_provider(deps) else {}
|
||
with _lock:
|
||
_cache = (time.monotonic(), got)
|
||
return {k: dict(v) for k, v in got.items()}
|
||
|
||
|
||
def wake_machine(deps, worker_id: str) -> dict[str, Any]:
|
||
"""Ask the provider to wake ``worker_id``: its answer, ``ok`` / ``sent`` /
|
||
``configured`` / ``autoWake`` always present."""
|
||
base = {"ok": False, "sent": False, "configured": False, "autoWake": False,
|
||
"timeoutSec": None, "machineId": worker_id}
|
||
if not _MACHINE_RE.fullmatch(worker_id or ""):
|
||
return {**base, "error": "bad machine id"}
|
||
if not has_provider(deps):
|
||
return {**base, "error": f"no plugin provides {PROVIDES}"}
|
||
raw = _run(deps, {"op": "wake", "machineId": worker_id}, timeout=30)
|
||
invalidate() # lastWokenAt moved
|
||
_publish(deps, {"type": "machine-wake"})
|
||
if not isinstance(raw, dict):
|
||
return {**base, "error": "the wake plugin didn't answer"}
|
||
out = {**base, **{k: v for k, v in raw.items() if isinstance(k, str)}}
|
||
for k in ("ok", "sent", "configured", "autoWake"):
|
||
out[k] = raw.get(k) is True
|
||
out["timeoutSec"] = _int(raw.get("timeoutSec"))
|
||
out["machineId"] = worker_id
|
||
return out
|
||
|
||
|
||
def _eligible(w: dict | None) -> bool:
|
||
"""An owner's paired worker — never a guest's computer, never pending."""
|
||
return bool(w) and not w.get("owner") and not w.get("pending")
|
||
|
||
|
||
def wait_online(deps, worker_id: str, timeout_s: float) -> bool:
|
||
"""Probe ``worker_id`` every :data:`POLL_S` until it is online (publishing
|
||
``workers``) or ``timeout_s`` passes."""
|
||
import workers as workers_mod
|
||
store = deps.worker_store
|
||
end = time.monotonic() + timeout_s
|
||
while True:
|
||
w = store.get(worker_id)
|
||
if not w:
|
||
return False
|
||
try:
|
||
workers_mod.probe(store, w)
|
||
except Exception as e: # noqa: BLE001 — a probe error is "not up yet"
|
||
log.debug("probe %s: %s", worker_id, e)
|
||
if store.online(worker_id):
|
||
_publish(deps, {"type": "workers"})
|
||
return True
|
||
if time.monotonic() + POLL_S > end:
|
||
return False
|
||
time.sleep(POLL_S)
|
||
|
||
|
||
def maybe_wake_and_wait(deps, worker_id: str, *, default_timeout_s: int = 60) -> bool:
|
||
"""Wake an offline worker the provider has ``autoWake`` on and wait for it.
|
||
True once it is online; False at once when it isn't configured, isn't
|
||
set to auto-wake or the packet didn't go out, else after the timeout."""
|
||
store = deps.worker_store
|
||
if not _eligible(store.get(worker_id)):
|
||
return False
|
||
if store.online(worker_id):
|
||
return True
|
||
entry = list_wakeable(deps).get(worker_id)
|
||
if not entry or not entry.get("configured") or not entry.get("autoWake"):
|
||
return False
|
||
res = wake_machine(deps, worker_id)
|
||
if not res.get("ok") or not res.get("sent"):
|
||
log.info("auto-wake of %s not sent: %s", worker_id, res.get("error") or res)
|
||
return False
|
||
want = res.get("timeoutSec") or entry.get("timeoutSec") or default_timeout_s
|
||
timeout = min(max(int(want), MIN_WAIT_S), MAX_WAIT_S)
|
||
log.info("auto-wake: %s woken, waiting up to %ss", worker_id, timeout)
|
||
return wait_online(deps, worker_id, timeout)
|
||
|
||
|
||
def probe_in_background(deps, worker_id: str, *, every_s: float = 3.0,
|
||
for_s: float = 60.0) -> threading.Thread:
|
||
"""After a manual wake: probe the worker every ``every_s`` for ``for_s``
|
||
until it is online, so the ``workers`` SSE flips its card by itself."""
|
||
import workers as workers_mod
|
||
|
||
def run() -> None:
|
||
store = deps.worker_store
|
||
end = time.monotonic() + for_s
|
||
while time.monotonic() < end:
|
||
time.sleep(every_s)
|
||
w = store.get(worker_id)
|
||
if not w:
|
||
return
|
||
try:
|
||
changed = workers_mod.probe(store, w)
|
||
except Exception: # noqa: BLE001
|
||
changed = False
|
||
if store.online(worker_id):
|
||
_publish(deps, {"type": "workers"})
|
||
return
|
||
if changed:
|
||
_publish(deps, {"type": "workers"})
|
||
|
||
t = threading.Thread(target=run, daemon=True, name=f"wake-probe-{worker_id}")
|
||
t.start()
|
||
return t
|