- 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>
180 lines
6.6 KiB
Python
180 lines
6.6 KiB
Python
"""``machines.wake`` — Wake-on-LAN for a plugin's handlers (the ``wake-on-lan``
|
|
plugin, 2026-11-26; ``plugins/machine_wake.py`` is the other half).
|
|
|
|
Owner only, operator approval, the plugin's own handlers only. Each route is
|
|
served at ``…/hub/…`` (the bridges' convention) and at ``…/bridge/…`` (the
|
|
same handler):
|
|
|
|
* ``POST …/plugins/{pid}/hub/wol`` — ``{"mac", "broadcast" = "192.168.1.255",
|
|
"port" = 9}`` → the host sidecar's ``POST /wol`` (it sends the magic packet
|
|
onto the LAN, which the hub's container can't); its JSON reply
|
|
``{"ok", "mac", "broadcast", "port"}`` passed back.
|
|
* ``POST …/plugins/{pid}/hub/workers/{wid}/probe`` — one health check of an
|
|
owner's worker now (``workers.probe``; ``workers`` SSE when it moved):
|
|
``{"online", "status", "lastSeen"}``.
|
|
* ``GET …/plugins/{pid}/hub/wake/workers`` (and ``…/bridge/workers``) — the
|
|
owner's paired workers, safe fields only: ``{"workers": [{id, name, host,
|
|
hostname, status, running, lastSeen}]}``.
|
|
|
|
Refusals carry ``{"error": {message, kind}, "detail": {message, kind}}`` like
|
|
``machines.mcp``'s: a bad body 400 ``bad_request``, an unknown / guest's /
|
|
pending worker 404 ``unknown_machine``, the sidecar's own errors passed through.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import logging
|
|
import re
|
|
import urllib.parse
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.hubmachines import _refuse
|
|
from plugins.proxyroutes import _active_plugin, _who
|
|
|
|
log = logging.getLogger(__name__)
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
CAP = "machines.wake"
|
|
BASE = "/proxy/tools/plugins/{pid}"
|
|
MAC_RE = re.compile(r"^([0-9A-Fa-f]{2}[:\-]){5}[0-9A-Fa-f]{2}$")
|
|
_MACHINE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
DEFAULT_BROADCAST = "192.168.1.255"
|
|
DEFAULT_PORT = 9
|
|
|
|
|
|
def _bridge(request: Request, pid: str):
|
|
"""(rec, error): the plugin's own handler, run for the owner, holding
|
|
``machines.wake``."""
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, err
|
|
if who.handler != pid:
|
|
return None, _refuse(403, f"{CAP} is only available to the plugin's own handlers",
|
|
"handler_only")
|
|
if not who.is_owner:
|
|
return None, _refuse(403, f"{CAP} is owner-only", "capability")
|
|
_, rec, _, _, err = _active_plugin(request.app.state.ai, who, pid)
|
|
if err:
|
|
return None, err
|
|
if CAP not in (rec["manifest"].get("capabilities") or []):
|
|
return None, _refuse(403, f"plugin lacks {CAP} capability", "capability")
|
|
return rec, None
|
|
|
|
|
|
def wol_payload(body: Any) -> tuple[dict | None, str | None]:
|
|
"""The body → ``({mac, broadcast, port}, None)`` or ``(None, why)``."""
|
|
if not isinstance(body, dict):
|
|
return None, "body must be a JSON object"
|
|
mac = body.get("mac")
|
|
if not isinstance(mac, str) or not MAC_RE.fullmatch(mac):
|
|
return None, "mac must look like aa:bb:cc:dd:ee:ff"
|
|
broadcast = body.get("broadcast") or DEFAULT_BROADCAST
|
|
try:
|
|
broadcast = str(ipaddress.IPv4Address(broadcast))
|
|
except (ipaddress.AddressValueError, ValueError, TypeError):
|
|
return None, "broadcast must be an IPv4 address"
|
|
port = body.get("port", DEFAULT_PORT)
|
|
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
|
return None, "port must be 1-65535"
|
|
return {"mac": mac, "broadcast": broadcast, "port": port}, None
|
|
|
|
|
|
def send_wol(deps, payload: dict) -> tuple[int, dict]:
|
|
from runs.sidecar_client import _sidecar_call
|
|
try:
|
|
return 200, _sidecar_call(deps, "/wol", payload, timeout=10)
|
|
except HTTPException as e:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
d = {"message": str(d.get("message") or d)[:300], "kind": str(d.get("kind") or "wol")}
|
|
return e.status_code, {"error": d, "detail": d}
|
|
|
|
|
|
def _owners_worker(deps, wid: str) -> dict | None:
|
|
w = deps.worker_store.get(wid) if _MACHINE_RE.fullmatch(wid or "") else None
|
|
if not w or w.get("owner") or w.get("pending"):
|
|
return None
|
|
return w
|
|
|
|
|
|
def probe_payload(deps, w: dict) -> dict:
|
|
import workers as workers_mod
|
|
store = deps.worker_store
|
|
try:
|
|
changed = workers_mod.probe(store, w)
|
|
except Exception as e: # noqa: BLE001 — a probe error reads as offline
|
|
log.debug("probe %s: %s", w.get("id"), e)
|
|
changed = False
|
|
if changed:
|
|
try:
|
|
deps.hub.publish({"type": "workers"})
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
st = store.status(w["id"]) or {}
|
|
return {"online": store.online(w["id"]), "status": st.get("status", "unknown"),
|
|
"lastSeen": st.get("lastSeen")}
|
|
|
|
|
|
def _host(url: str | None) -> str | None:
|
|
try:
|
|
return urllib.parse.urlsplit(url or "").hostname
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def workers_payload(deps) -> dict:
|
|
store = deps.worker_store
|
|
rows = []
|
|
for w in store.list():
|
|
if w.get("owner") or w.get("pending"):
|
|
continue
|
|
st = store.status(w["id"]) or {}
|
|
rows.append({"id": w["id"], "name": w.get("name") or w["id"],
|
|
"host": w.get("host") or _host(w.get("url")), "hostname": w.get("hostname"),
|
|
"status": st.get("status", "unknown"), "running": st.get("running", 0),
|
|
"lastSeen": st.get("lastSeen")})
|
|
return {"workers": rows}
|
|
|
|
|
|
@router.post(BASE + "/hub/wol")
|
|
@router.post(BASE + "/bridge/wol")
|
|
async def hub_wol(pid: str, request: Request):
|
|
_rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
try:
|
|
body = await request.json()
|
|
except Exception:
|
|
body = None
|
|
payload, why = wol_payload(body)
|
|
if why:
|
|
return _refuse(400, why, "bad_request")
|
|
status, out = await run_in_threadpool(send_wol, request.app.state.ai, payload)
|
|
return JSONResponse(out, status_code=status)
|
|
|
|
|
|
@router.post(BASE + "/hub/workers/{wid}/probe")
|
|
@router.post(BASE + "/bridge/workers/{wid}/probe")
|
|
async def hub_probe(pid: str, wid: str, request: Request):
|
|
_rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
deps = request.app.state.ai
|
|
w = _owners_worker(deps, wid)
|
|
if not w:
|
|
return _refuse(404, f"unknown machine: {wid!r}", "unknown_machine")
|
|
return await run_in_threadpool(probe_payload, deps, w)
|
|
|
|
|
|
@router.get(BASE + "/hub/wake/workers")
|
|
@router.get(BASE + "/bridge/workers")
|
|
async def hub_wake_workers(pid: str, request: Request):
|
|
_rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
return await run_in_threadpool(workers_payload, request.app.state.ai)
|