diff --git a/CHANGELOG.md b/CHANGELOG.md index d5fa0cc7..9a9b98f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,20 @@ and listed with their assets on the ### Added +- **The share switch is back, and makes this machine a node** (ADR-0113, + #171). On, the hub runs a node agent for the pool (sidebar, **Pool → This + machine**): on Linux inside the hub, on Windows in a WSL2 distribution you + name, with Docker Engine of its own and mirrored networking, so a Windows + machine (and its NVIDIA GPU) can run other members' lanes. The machine + stays one member of the pool. The hub checks the distribution and shows + what is missing with the command for it, and a setup prompt for a coding + agent; it changes nothing there itself. Off while others' lanes run, the + agent takes no new lanes and ends with the last. An admin still grants the + machine as a node. Not on macOS yet. +- **`devstack node agent --no-new-lanes` and `--membership `**: an + agent that takes no new lanes (its report says it shares nothing), and + one that serves a membership from another folder. + - **A lane on a node gets the GPUs it asked for, and no other lane does** (ADR-0112). A lane with `[lanes.need] gpus` holds that many of the node's free GPUs for as long as its lease lives; its container gets exactly diff --git a/SECURITY.md b/SECURITY.md index a1f42449..1b81721f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -104,6 +104,12 @@ browsers as well. - Your machine reports to the coordinator what it has (CPU, memory, GPUs, load) and which devstack it runs; a node reports what it offers and its lanes. + - **The share switch** (off by default) makes your machine a node: the hub + runs a node agent, and once an admin granted the machine, other members' + lanes run on it, with the limits of a node (ADR-0033). On Windows the + agent runs as root in the WSL distribution you name, with a copy of the + machine's pool membership (its private key included) in + `/var/lib/devstack-node/` there, readable by root only. - **Telemetry** to the pool's collector only with your consent, per pool, off by default (`devstack join --telemetry`, `devstack pool telemetry on|off`, the pool area): devstack's diagnostic log, cut to first lines as diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index df51c13a..109d2ca8 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -45,6 +45,7 @@ mod lastcommit; pub mod mcp; mod mcpclient; pub mod mcpscope; +mod nodehost; mod notice; mod notify; mod open; @@ -691,7 +692,7 @@ fn router(state: AppState) -> axum::Router { axum::routing::put(publiclinks::put).delete(publiclinks::delete), ) .route("/hub/pool", get(pool::overview)) - .route("/hub/pool/share", get(share::get)) + .route("/hub/pool/share", get(share::get).put(share::put)) .route("/hub/pool/shared", get(shared::list)) .route("/hub/pool/shared/{lease}/open", post(shared::open)) .route("/hub/pool/shared/{lease}/connect", post(shared::connect)) diff --git a/crates/devstack-hub/src/nodehost.rs b/crates/devstack-hub/src/nodehost.rs new file mode 100644 index 00000000..84fdfc83 --- /dev/null +++ b/crates/devstack-hub/src/nodehost.rs @@ -0,0 +1,1244 @@ +//! The share switch makes this machine a node (ADR-0113): with it on, the +//! hub runs the node agent for the pool and starts it again when it ends; +//! off, it ends it. +//! +//! - **Linux:** the agent runs inside the hub (`devstack_node::node::serve` +//! on a thread of its own), with the machine's membership. +//! - **Windows:** lanes are Linux containers, so the agent runs in a WSL2 +//! distribution the user named, as root (`wsl.exe -d -u root -- +//! devstack node agent …`), with a copy of the machine's membership there +//! (`/var/lib/devstack-node/`): one member per machine (point 2). +//! The hub never sets the distribution up (point 3): it checks it and says +//! what is missing, as commands and as a prompt for a coding agent. +//! - **macOS:** not yet. +//! +//! Off while other members' lanes run here (point 5): the agent goes on +//! without taking new lanes (`--no-new-lanes`) and ends once the last one +//! did. While the hub's agent runs, the hub does not report the machine +//! itself (#170). +//! +//! - `GET /hub/pool/share?pool=` carries the switch and the agent's state +//! (`switch`, `host`), see `share.rs` +//! - `PUT /hub/pool/share?pool=` `{enabled, max_cpus?, max_memory?, distro?, +//! port?}`: change the switch; acted on within a few seconds + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// How often the hub looks at each pool's switch and agent. +const EVERY: Duration = Duration::from_secs(5); +/// The agent's port unless the switch names another. +pub const DEFAULT_PORT: u16 = 4261; +/// An agent that ends sooner than this after its start failed: it is +/// started again only after [`BACKOFF`]. +const SETTLE: Duration = Duration::from_secs(30); +const BACKOFF: Duration = Duration::from_secs(60); +/// Where the hub on Windows puts the membership's copy in the distribution. +#[cfg_attr(not(windows), allow(dead_code))] +pub const WSL_DIR: &str = "/var/lib/devstack-node"; +/// The Hyper-V firewall rule the setup names (`New-NetFirewallHyperVRule`). +#[cfg_attr(not(windows), allow(dead_code))] +pub const FIREWALL_RULE: &str = "devstack-node"; + +/// The switch of one pool, in `node-host.json` beside its membership. A file +/// of its own: the `share.json` of releases before 0.23 may still say +/// `enabled`, which must not start an agent now. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Switch { + #[serde(default)] + pub enabled: bool, + /// Caps on what the node's lanes take together. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_cpus: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_memory: Option, + /// Windows: the WSL distribution the agent runs in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub distro: Option, + /// The agent's port; [`DEFAULT_PORT`] when not set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub port: Option, +} + +fn switch_path(dir: &Path) -> PathBuf { + dir.join("node-host.json") +} + +impl Switch { + pub fn load(dir: &Path) -> Self { + std::fs::read(switch_path(dir)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() + } + + pub fn save(&self, dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + std::fs::write( + switch_path(dir), + serde_json::to_vec_pretty(self).expect("switch serialises"), + ) + } + + pub fn port(&self) -> u16 { + self.port.unwrap_or(DEFAULT_PORT) + } + + /// What an empty or impossible value would make of the agent. + pub fn problem(&self) -> Option { + if self.max_cpus.is_some_and(|c| !c.is_finite() || c <= 0.0) { + return Some("max_cpus: a number of cores above 0".into()); + } + if self.max_memory == Some(0) { + return Some("max_memory: above 0".into()); + } + if self.port == Some(0) { + return Some("port: 1 to 65535".into()); + } + if let Some(d) = &self.distro + && !valid_distro(d) + { + return Some("distro: the name `wsl -l` shows (letters, digits, `.`, `-`, `_`)".into()); + } + None + } +} + +/// A WSL distribution's name as `wsl -l` shows it; passed to `wsl.exe -d`. +pub fn valid_distro(d: &str) -> bool { + !d.is_empty() + && d.len() <= 64 + && d.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) +} + +/// One thing the agent needs, and whether this machine has it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Check { + pub name: String, + pub ok: bool, + /// What was found. + pub detail: String, + /// What to run when it is missing. + #[serde(skip_serializing_if = "Option::is_none")] + pub fix: Option, + /// Missing, the agent still starts (the GPU, the firewall rule). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub optional: bool, +} + +/// What the switch did of the agent. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum State { + /// The switch is off, and no agent of the hub runs. + #[default] + Off, + /// Not on this platform (macOS). + Unsupported, + /// Something the agent needs is missing (`checks`). + Blocked, + Starting, + Running, + /// Off, and other members' lanes still run here: the agent takes no new + /// ones and ends with the last. + Draining, + /// It ended soon after its start; tried again after a minute. + Failed, + /// A node agent started by hand runs for this membership: the hub + /// leaves it alone. + Foreign, +} + +/// The agent as the hub runs it, per pool. +#[derive(Debug, Clone, Default, Serialize)] +pub struct Host { + pub state: State, + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + /// Where requesters reach the agent. + #[serde(skip_serializing_if = "Option::is_none")] + pub api: Option, + /// Whether an admin granted this machine to run lanes; `None` when the + /// coordinator was not asked. + #[serde(skip_serializing_if = "Option::is_none")] + pub granted: Option, + /// Other members' lanes that run here. + pub guests: usize, + /// Windows: what the distribution has. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub checks: Vec, + /// Windows: the distributions there are (Docker Desktop's left out). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub distros: Vec, + /// For a coding agent: how to set up what `checks` misses. + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt: Option, + /// The agent's last lines of output. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub output: Vec, +} + +/// What to do with a pool's agent, from its switch and what runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Act { + Nothing, + Start { + new_lanes: bool, + }, + /// Started again: other caps, or new lanes no longer taken. + Restart { + new_lanes: bool, + }, + Stop, +} + +/// What runs now, for [`decide`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Running { + pub new_lanes: bool, + /// Its caps, distribution or port differ from the switch. + pub stale: bool, +} + +/// The step from what runs (`running`) towards what the switch says, with +/// `guests` other members' lanes here. +pub fn decide(enabled: bool, running: Option, guests: usize) -> Act { + match (enabled, running) { + (true, None) => Act::Start { new_lanes: true }, + (true, Some(r)) if !r.new_lanes || r.stale => Act::Restart { new_lanes: true }, + (true, Some(_)) => Act::Nothing, + (false, None) => Act::Nothing, + (false, Some(_)) if guests == 0 => Act::Stop, + (false, Some(r)) if r.new_lanes => Act::Restart { new_lanes: false }, + (false, Some(_)) => Act::Nothing, + } +} + +/// The agent's arguments after `devstack` (Windows runs it as a process; on +/// Linux it runs inside the hub). +#[cfg_attr(not(windows), allow(dead_code))] +pub fn agent_args( + pool: &str, + sw: &Switch, + api: &str, + membership: Option<&str>, + new_lanes: bool, +) -> Vec { + let mut a: Vec = vec![ + "node".into(), + "agent".into(), + "--pool".into(), + pool.into(), + "--listen".into(), + format!("0.0.0.0:{}", sw.port()), + "--api".into(), + api.into(), + ]; + if let Some(m) = membership { + a.extend(["--membership".into(), m.into()]); + } + if let Some(c) = sw.max_cpus { + a.extend(["--max-cpus".into(), c.to_string()]); + } + if let Some(m) = sw.max_memory { + a.extend([ + "--max-memory-gib".into(), + format!("{:.2}", m as f64 / f64::from(1u32 << 30)), + ]); + } + if !new_lanes { + a.push("--no-new-lanes".into()); + } + a +} + +/// The address of this machine that reaches `coordinator` +/// (`https://host:port`): the one other members reach it at too, in the +/// same network. No packet is sent. +pub fn local_address(coordinator: &str) -> Option { + let rest = coordinator.split("://").nth(1).unwrap_or(coordinator); + let hostport = rest.split('/').next()?; + let target = if hostport.contains(':') { + hostport.to_string() + } else { + format!("{hostport}:443") + }; + let sock = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; + sock.connect(target).ok()?; + let ip = sock.local_addr().ok()?.ip(); + (!ip.is_unspecified()).then_some(ip) +} + +/// One agent the hub runs (none on macOS yet). +#[cfg_attr(target_os = "macos", allow(dead_code))] +struct Agent { + new_lanes: bool, + /// The switch it was started with. + switch: Switch, + started: Instant, + output: std::sync::Arc>>, + run: Run, +} + +enum Run { + #[cfg(target_os = "linux")] + InProcess { + stop: Option>, + thread: std::thread::JoinHandle<()>, + }, + #[cfg(windows)] + Wsl { + child: std::process::Child, + distro: String, + }, + /// Never made: keeps the enum inhabited where neither runs. + #[allow(dead_code)] + None, +} + +impl Agent { + fn ended(&mut self) -> bool { + match &mut self.run { + #[cfg(target_os = "linux")] + Run::InProcess { thread, .. } => thread.is_finished(), + #[cfg(windows)] + Run::Wsl { child, .. } => !matches!(child.try_wait(), Ok(None)), + Run::None => true, + } + } + + fn stop(self, pool: &str) { + match self.run { + #[cfg(target_os = "linux")] + Run::InProcess { stop, thread } => { + if let Some(s) = stop { + let _ = s.send(()); + } + let _ = thread.join(); + } + #[cfg(windows)] + Run::Wsl { mut child, distro } => { + wsl::kill_agent(&distro, pool); + let _ = child.kill(); + let _ = child.wait(); + } + Run::None => {} + } + let _ = pool; + } +} + +#[derive(Default)] +struct Pools { + hosts: BTreeMap, + agents: BTreeMap, + /// When an agent of the pool last failed: not started again before + /// [`BACKOFF`]. + failed: BTreeMap, +} + +static POOLS: OnceLock> = OnceLock::new(); + +/// Start looking after the switches, once per hub. +pub fn start(state: PathBuf) { + if POOLS.set(Mutex::new(Pools::default())).is_err() { + return; + } + std::thread::spawn(move || { + loop { + for (pool, dir) in devstack_node::member::pools(&state) { + round(&pool, &dir); + } + std::thread::sleep(EVERY); + } + }); +} + +/// Act on a changed switch now, not at the next round. +pub fn poke(pool: &str, dir: &Path) { + let (p, d) = (pool.to_string(), dir.to_path_buf()); + std::thread::spawn(move || round(&p, &d)); +} + +/// The pool's agent as last seen. +pub fn host(pool: &str) -> Host { + POOLS + .get() + .and_then(|p| p.lock().unwrap().hosts.get(pool).cloned()) + .unwrap_or_default() +} + +/// Whether an agent of the hub runs for the pool: the hub does not report +/// the machine then (#170). +pub fn runs(pool: &str) -> bool { + POOLS + .get() + .is_some_and(|p| p.lock().unwrap().agents.contains_key(pool)) +} + +fn set(pool: &str, f: impl FnOnce(&mut Host)) { + if let Some(p) = POOLS.get() { + f(p.lock().unwrap().hosts.entry(pool.to_string()).or_default()); + } +} + +/// One look at a pool: the switch, what runs, and the step between them. +/// Serialised per hub: two rounds of one pool never act at once. +fn round(pool: &str, dir: &Path) { + static ONE: Mutex<()> = Mutex::new(()); + let _one = ONE.lock().unwrap(); + let Some(pools) = POOLS.get() else { return }; + let sw = Switch::load(dir); + let local = devstack_node::member::Local::new(dir); + let member = match local.membership() { + Ok(Some(m)) if m.state == devstack_node::store::State::Approved => m, + _ => { + // No approved member: nothing may run. + let agent = pools.lock().unwrap().agents.remove(pool); + if let Some(a) = agent { + a.stop(pool); + } + set(pool, |h| *h = Host::default()); + return; + } + }; + let guests = crate::share::guests(pool).map_or(0, |g| g.len()); + let granted = if sw.enabled || pools.lock().unwrap().agents.contains_key(pool) { + local + .members() + .ok() + .and_then(|ms| ms.into_iter().find(|m| m.id == member.id)) + .map(|m| m.node) + } else { + None + }; + set(pool, |h| { + h.guests = guests; + h.granted = granted; + }); + + if cfg!(target_os = "macos") { + set(pool, |h| { + h.state = State::Unsupported; + h.detail = Some("A Mac cannot run other members' lanes yet.".into()); + }); + return; + } + + // An agent of ours that ended: noted, and taken off. + { + let mut p = pools.lock().unwrap(); + if p.agents.get_mut(pool).is_some_and(Agent::ended) { + let a = p.agents.remove(pool).expect("checked above"); + let soon = a.started.elapsed() < SETTLE; + let out = a.output.lock().unwrap().clone(); + if soon { + p.failed.insert(pool.to_string(), Instant::now()); + } + let h = p.hosts.entry(pool.to_string()).or_default(); + h.output = out; + if soon { + h.state = State::Failed; + h.detail = Some( + h.output + .iter() + .rev() + .find(|l| !l.trim().is_empty()) + .cloned() + .unwrap_or_else(|| "the node agent ended".into()), + ); + } + drop(p); + a.stop(pool); + } + } + + let running = { + let p = pools.lock().unwrap(); + p.agents.get(pool).map(|a| Running { + new_lanes: a.new_lanes, + stale: Switch { + enabled: true, + ..a.switch.clone() + } != Switch { + enabled: true, + ..sw.clone() + }, + }) + }; + // An agent started by hand for this membership (on Linux; on Windows + // the machine's own membership runs none). + if running.is_none() && devstack_node::node::agent_runs(dir) { + set(pool, |h| { + h.state = State::Foreign; + h.detail = Some( + "A node agent started by hand runs for this machine: the switch leaves it alone." + .into(), + ); + }); + return; + } + + match decide(sw.enabled, running, guests) { + Act::Nothing => { + let st = match running { + Some(r) if r.new_lanes => State::Running, + Some(_) => State::Draining, + None => { + let h = host(pool); + if h.state == State::Failed && sw.enabled { + State::Failed + } else { + State::Off + } + } + }; + let output = pools + .lock() + .unwrap() + .agents + .get(pool) + .map(|a| a.output.lock().unwrap().clone()); + set(pool, |h| { + h.state = st; + if st != State::Failed { + h.detail = None; + } + if let Some(o) = output { + h.output = o; + } + if st == State::Off { + h.api = None; + h.checks.clear(); + h.prompt = None; + } + }); + } + Act::Stop => { + let agent = pools.lock().unwrap().agents.remove(pool); + if let Some(a) = agent { + a.stop(pool); + } + set(pool, |h| { + h.state = State::Off; + h.detail = None; + h.api = None; + }); + } + Act::Start { new_lanes } | Act::Restart { new_lanes } => { + let failed_at = pools.lock().unwrap().failed.get(pool).copied(); + if failed_at.is_some_and(|t| t.elapsed() < BACKOFF) && running.is_none() { + return; + } + if let Some(why) = sw.problem() { + set(pool, |h| { + h.state = State::Blocked; + h.detail = Some(why); + }); + return; + } + let Some(ip) = local_address(&member.coordinator) else { + set(pool, |h| { + h.state = State::Blocked; + h.detail = Some(format!( + "No address of this machine reaches the coordinator at {}.", + member.coordinator + )); + }); + return; + }; + let api = format!("https://{ip}:{}", sw.port()); + if let Err(why) = ready(pool, &sw) { + set(pool, |h| { + h.state = State::Blocked; + h.detail = Some(why); + }); + return; + } + let old = pools.lock().unwrap().agents.remove(pool); + if let Some(a) = old { + a.stop(pool); + } + set(pool, |h| { + h.state = State::Starting; + h.detail = None; + h.api = Some(api.clone()); + h.output.clear(); + }); + match launch(pool, dir, &sw, &api, new_lanes) { + Ok(agent) => { + let mut p = pools.lock().unwrap(); + p.failed.remove(pool); + p.agents.insert(pool.to_string(), agent); + let h = p.hosts.entry(pool.to_string()).or_default(); + h.state = if new_lanes { + State::Running + } else { + State::Draining + }; + } + Err(e) => { + pools + .lock() + .unwrap() + .failed + .insert(pool.to_string(), Instant::now()); + set(pool, |h| { + h.state = State::Failed; + h.detail = Some(e); + }); + } + } + } + } +} + +/// Whether what the agent needs is there; the checks go to the pool's +/// [`Host`]. On Linux the agent's own start says what is missing. +fn ready(pool: &str, sw: &Switch) -> Result<(), String> { + #[cfg(windows)] + { + let distros = wsl::distros(); + set(pool, |h| h.distros = distros.clone()); + let Some(distro) = sw.distro.clone() else { + set(pool, |h| { + h.checks.clear(); + h.prompt = Some(wsl::prompt(None, &[], sw.port())); + }); + return Err( + "Choose the WSL distribution the node agent runs in (one with Docker Engine of its own, not Docker Desktop's)." + .into(), + ); + }; + let checks = wsl::checks(&distro, &distros, sw.port()); + let missing = checks.iter().any(|c| !c.ok && !c.optional); + let prompt = checks + .iter() + .any(|c| !c.ok) + .then(|| wsl::prompt(Some(&distro), &checks, sw.port())); + set(pool, |h| { + h.checks = checks; + h.prompt = prompt; + }); + if missing { + return Err(format!( + "The WSL distribution `{distro}` lacks what the node agent needs: see the checks." + )); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = (pool, sw); + Ok(()) + } +} + +/// Last lines of output kept per agent. +#[cfg_attr(target_os = "macos", allow(dead_code))] +const KEEP_LINES: usize = 40; + +#[cfg_attr(target_os = "macos", allow(dead_code))] +fn keep(out: &Mutex>, line: String) { + let mut o = out.lock().unwrap(); + o.push(line); + let n = o.len(); + if n > KEEP_LINES { + o.drain(..n - KEEP_LINES); + } +} + +fn launch( + pool: &str, + dir: &Path, + sw: &Switch, + api: &str, + new_lanes: bool, +) -> Result { + let output = std::sync::Arc::new(Mutex::new(Vec::::new())); + #[cfg(target_os = "linux")] + { + let _ = &output; + let config = devstack_node::node::NodeConfig { + dir: dir.to_path_buf(), + api: api.to_string(), + share: devstack_node::share::Settings { + enabled: new_lanes, + max_cpus: sw.max_cpus, + max_memory: sw.max_memory, + }, + dedicated: false, + free: None, + on_update: None, + }; + let listen: std::net::SocketAddr = ([0, 0, 0, 0], sw.port()).into(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let out = output.clone(); + let thread = std::thread::Builder::new() + .name(format!("node-agent-{pool}")) + .spawn(move || { + let rt = match tokio::runtime::Runtime::new() { + Ok(rt) => rt, + Err(e) => return keep(&out, e.to_string()), + }; + let r = rt.block_on(async move { + let listener = tokio::net::TcpListener::bind(listen) + .await + .map_err(|e| format!("listen on {listen}: {e}"))?; + devstack_node::node::serve(config, listener, async { + let _ = rx.await; + }) + .await + .map_err(|e| e.to_string()) + }); + if let Err(e) = r { + keep(&out, e); + } + }) + .map_err(|e| e.to_string())?; + Ok(Agent { + new_lanes, + switch: sw.clone(), + started: Instant::now(), + output, + run: Run::InProcess { + stop: Some(tx), + thread, + }, + }) + } + #[cfg(windows)] + { + let distro = sw.distro.clone().ok_or("no WSL distribution chosen")?; + let target = format!("{WSL_DIR}/{pool}"); + wsl::copy_membership(&distro, dir, &target)?; + // One from an earlier hub may still run there. + wsl::kill_agent(&distro, pool); + let args = agent_args(pool, sw, api, Some(&target), new_lanes); + let child = wsl::spawn_agent(&distro, &args, output.clone())?; + Ok(Agent { + new_lanes, + switch: sw.clone(), + started: Instant::now(), + output, + run: Run::Wsl { child, distro }, + }) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = (pool, dir, sw, api, new_lanes, output); + Err("not on this platform".into()) + } +} + +/// The distribution's side on Windows: listed, checked, given the +/// membership, and running the agent, all through `wsl.exe`. +#[cfg_attr(not(windows), allow(dead_code))] +pub mod wsl { + use super::{Check, FIREWALL_RULE, WSL_DIR}; + use std::path::Path; + use std::process::{Command, Stdio}; + + /// `wsl.exe` lists in UTF-16 (little endian) where it is not told + /// otherwise. + pub fn decode(out: &[u8]) -> String { + if out.len() >= 2 + && out.len().is_multiple_of(2) + && out.iter().skip(1).step_by(2).all(|b| *b == 0) + { + let units: Vec = out + .as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .collect(); + String::from_utf16_lossy(&units) + } else { + String::from_utf8_lossy(out).into_owned() + } + } + + /// The names `wsl -l -q` prints, Docker Desktop's left out. + pub fn parse_list(text: &str) -> Vec { + text.lines() + .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\0')) + .filter(|l| !l.is_empty() && !l.starts_with("docker-desktop")) + .map(str::to_string) + .collect() + } + + fn wsl() -> Command { + let mut c = Command::new("wsl.exe"); + devstack_desktop::no_window(&mut c); + c + } + + pub fn distros() -> Vec { + wsl() + .args(["-l", "-q"]) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| parse_list(&decode(&o.stdout))) + .unwrap_or_default() + } + + /// `script` in `distro` as root, with `~/.local/bin` (where + /// `install.sh` puts devstack) and WSL's GPU tools on `PATH`. + fn sh(distro: &str, script: &str) -> Command { + let mut c = wsl(); + c.args(["-d", distro, "-u", "root", "--", "sh", "-c"]); + c.arg(format!( + "PATH=\"$HOME/.local/bin:/usr/local/bin:/usr/lib/wsl/lib:$PATH\"; export PATH; {script}" + )); + c + } + + /// What the checks read in the distribution, one `key=value` per line. + const PROBE: &str = r#"echo "mode=$(wslinfo --networking-mode 2>/dev/null || echo unknown)" +echo "docker=$(docker info --format '{{.OperatingSystem}}' 2>/dev/null)" +echo "nvidia_runtime=$(docker info --format '{{json .Runtimes}}' 2>/dev/null | grep -c nvidia)" +echo "gpus=$(nvidia-smi -L 2>/dev/null | grep -c '^GPU')" +echo "devstack=$(devstack --version 2>/dev/null)" +echo "memory=$(awk '/MemTotal/ {print $2 * 1024}' /proc/meminfo)""#; + + /// The probe's lines as a map. + pub fn parse_probe(text: &str) -> std::collections::BTreeMap { + text.lines() + .filter_map(|l| l.split_once('=')) + .map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + .collect() + } + + /// What `distro` has, as the agent needs it, from the probe's values and + /// whether the firewall rule exists (`None`: not known). + pub fn judge( + distro: &str, + exists: bool, + probe: &std::collections::BTreeMap, + firewall: Option, + version: &str, + port: u16, + ) -> Vec { + let get = |k: &str| probe.get(k).map(String::as_str).unwrap_or(""); + let mut c = vec![Check { + name: "distribution".into(), + ok: exists, + detail: if exists { + format!("`{distro}` is there") + } else { + format!("no WSL distribution `{distro}`") + }, + fix: (!exists).then(|| format!("wsl --install -d {distro}")), + optional: false, + }]; + if !exists { + return c; + } + let mode = get("mode"); + c.push(Check { + name: "networking".into(), + ok: mode == "mirrored", + detail: format!("networking mode: {}", if mode.is_empty() { "unknown" } else { mode }), + fix: (mode != "mirrored").then(|| { + "In %UserProfile%\\.wslconfig under [wsl2]: networkingMode=mirrored, then `wsl --shutdown` (ends Docker Desktop too: start it again)".into() + }), + optional: false, + }); + let docker = get("docker"); + let own = !docker.is_empty() && !docker.contains("Docker Desktop"); + c.push(Check { + name: "docker".into(), + ok: own, + detail: if docker.is_empty() { + "no Docker engine answers in the distribution".into() + } else if own { + format!("Docker Engine: {docker}") + } else { + "`docker` talks to Docker Desktop".into() + }, + fix: (!own).then(|| { + format!( + "Turn Docker Desktop's WSL integration off for `{distro}`, then in it as root: curl -fsSL https://get.docker.com | sh" + ) + }), + optional: false, + }); + let dv = get("devstack"); + let same = dv.split_whitespace().nth(1) == Some(version); + c.push(Check { + name: "devstack".into(), + ok: same, + detail: if dv.is_empty() { + "devstack is not installed in the distribution".into() + } else { + format!("{dv} (this machine: {version})") + }, + fix: (!same).then(|| { + format!( + "In `{distro}` as root: curl -fsSL https://github.com/nuetzliches/devstack/releases/latest/download/install.sh | sh -s -- --version {version}" + ) + }), + optional: false, + }); + let gpus: u32 = get("gpus").parse().unwrap_or(0); + let runtime = get("nvidia_runtime").parse::().unwrap_or(0) > 0; + c.push(Check { + name: "gpu".into(), + ok: gpus == 0 || runtime, + detail: match (gpus, runtime) { + (0, _) => "no NVIDIA GPU visible (the node offers none)".into(), + (n, true) => format!("{n} NVIDIA GPU(s), the container toolkit is set up"), + (n, false) => format!("{n} NVIDIA GPU(s), but Docker has no `nvidia` runtime"), + }, + fix: (gpus > 0 && !runtime).then(|| { + "Install the NVIDIA Container Toolkit in the distribution, then: nvidia-ctk runtime configure --runtime=docker && systemctl restart docker".into() + }), + optional: true, + }); + c.push(Check { + name: "firewall".into(), + ok: firewall == Some(true), + detail: match firewall { + Some(true) => format!("Hyper-V firewall rule `{FIREWALL_RULE}` is there"), + Some(false) => format!("no Hyper-V firewall rule `{FIREWALL_RULE}`: other members may not reach port {port}"), + None => "the Hyper-V firewall rule could not be read".into(), + }, + fix: (firewall != Some(true)).then(|| { + format!( + "In an elevated PowerShell: New-NetFirewallHyperVRule -Name {FIREWALL_RULE} -DisplayName \"devstack node agent\" -Direction Inbound -VMCreatorId '{{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}}' -Protocol TCP -LocalPorts {port}" + ) + }), + optional: true, + }); + c + } + + /// Whether the Hyper-V firewall rule exists; `None` when it cannot be + /// read (an older Windows, or PowerShell refused). + fn firewall() -> Option { + let mut c = Command::new("powershell.exe"); + devstack_desktop::no_window(&mut c); + let out = c + .args([ + "-NoProfile", + "-NonInteractive", + "-Command", + &format!( + "if (Get-NetFirewallHyperVRule -Name {FIREWALL_RULE} -ErrorAction SilentlyContinue) {{ 'yes' }} else {{ 'no' }}" + ), + ]) + .output() + .ok()?; + match String::from_utf8_lossy(&out.stdout).trim() { + "yes" => Some(true), + "no" => Some(false), + _ => None, + } + } + + pub fn checks(distro: &str, distros: &[String], port: u16) -> Vec { + let exists = distros.iter().any(|d| d.eq_ignore_ascii_case(distro)); + let probe = if exists { + sh(distro, PROBE) + .stdin(Stdio::null()) + .output() + .map(|o| parse_probe(&String::from_utf8_lossy(&o.stdout))) + .unwrap_or_default() + } else { + Default::default() + }; + let version = devstack_node::version::Release::this().version; + judge(distro, exists, &probe, firewall(), &version, port) + } + + /// For a coding agent on this machine: set up what the checks miss. + pub fn prompt(distro: Option<&str>, checks: &[Check], port: u16) -> String { + let mut p = String::from( + "Set up a WSL2 distribution on this Windows machine so that devstack can run its node agent there, for other members of the devstack pool to run lanes on this machine. Ask before each step that changes the machine, and say what it changes.\n\n", + ); + match distro { + None => p.push_str( + "1. Pick or create a distribution of its own, not one Docker Desktop's WSL integration uses: `wsl --install -d Ubuntu-24.04`, initialised as root. Then enter its name in the dashboard (Pool, This machine).\n", + ), + Some(d) => { + p.push_str(&format!( + "The distribution is `{d}`; run commands in it as root (`wsl -d {d} -u root`).\n" + )); + let mut n = 0; + for c in checks.iter().filter(|c| !c.ok) { + n += 1; + p.push_str(&format!("{n}. {}: {}", c.name, c.detail)); + if let Some(f) = &c.fix { + p.push_str(&format!(". {f}")); + } + p.push('\n'); + } + } + } + p.push_str(&format!( + "\nThe node agent listens on port {port}; the dashboard starts it once every required check passes. Do not start the agent by hand. Steps that need an elevated shell (the firewall rule) are for the user to run: show them the command." + )); + p + } + + /// The membership's files (not its folders: the Windows side's state) + /// into `target` in the distribution, readable by root only. + pub fn copy_membership(distro: &str, dir: &Path, target: &str) -> Result<(), String> { + let files: Vec<_> = std::fs::read_dir(dir) + .map_err(|e| format!("{}: {e}", dir.display()))? + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .filter(|e| e.file_name() != "node-host.json") + .collect(); + let mkdir = sh( + distro, + &format!("umask 077 && mkdir -p '{target}' && chmod 700 '{WSL_DIR}' '{target}'"), + ) + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("wsl.exe: {e}"))?; + if !mkdir.status.success() { + return Err(format!( + "cannot make {target} in `{distro}`: {}", + String::from_utf8_lossy(&mkdir.stderr).trim() + )); + } + for f in files { + let name = f.file_name().to_string_lossy().into_owned(); + if !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) + { + continue; + } + let bytes = std::fs::read(f.path()).map_err(|e| format!("{name}: {e}"))?; + let mut child = sh(distro, &format!("umask 077 && cat > '{target}/{name}'")) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("wsl.exe: {e}"))?; + { + use std::io::Write; + let mut stdin = child.stdin.take().ok_or("wsl.exe: no stdin")?; + stdin + .write_all(&bytes) + .map_err(|e| format!("{name} into `{distro}`: {e}"))?; + } + let out = child.wait_with_output().map_err(|e| e.to_string())?; + if !out.status.success() { + return Err(format!( + "{name} into `{distro}`: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + } + Ok(()) + } + + /// Ends the pool's agent in the distribution, one an earlier hub left + /// running included. + pub fn kill_agent(distro: &str, pool: &str) { + let _ = sh( + distro, + &format!("pkill -TERM -f -- '--membership {WSL_DIR}/{pool}( |$)' ; true"), + ) + .stdin(Stdio::null()) + .output(); + } + + pub fn spawn_agent( + distro: &str, + args: &[String], + output: std::sync::Arc>>, + ) -> Result { + let quoted: Vec = args.iter().map(|a| format!("'{a}'")).collect(); + let mut child = sh(distro, &format!("exec devstack {}", quoted.join(" "))) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("wsl.exe: {e}"))?; + for pipe in [ + child + .stdout + .take() + .map(|s| Box::new(s) as Box), + child + .stderr + .take() + .map(|s| Box::new(s) as Box), + ] + .into_iter() + .flatten() + { + let out = output.clone(); + std::thread::spawn(move || { + use std::io::BufRead; + for line in std::io::BufReader::new(pipe).lines().map_while(Result::ok) { + super::keep(&out, line); + } + }); + } + Ok(child) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_switch_and_what_runs_give_the_step() { + let run = |new_lanes, stale| Some(Running { new_lanes, stale }); + assert_eq!(decide(true, None, 0), Act::Start { new_lanes: true }); + assert_eq!(decide(true, run(true, false), 3), Act::Nothing); + assert_eq!( + decide(true, run(true, true), 0), + Act::Restart { new_lanes: true } + ); + assert_eq!( + decide(true, run(false, false), 1), + Act::Restart { new_lanes: true } + ); + assert_eq!(decide(false, None, 2), Act::Nothing); + // Off with guests: no new lanes, the running ones go on. + assert_eq!( + decide(false, run(true, false), 2), + Act::Restart { new_lanes: false } + ); + assert_eq!(decide(false, run(false, false), 2), Act::Nothing); + // The last one ended: the agent goes. + assert_eq!(decide(false, run(false, false), 0), Act::Stop); + assert_eq!(decide(false, run(true, false), 0), Act::Stop); + } + + #[test] + fn the_agent_is_told_the_switch() { + let sw = Switch { + enabled: true, + max_cpus: Some(8.0), + max_memory: Some(8 << 30), + distro: Some("Ubuntu-24.04".into()), + port: None, + }; + let a = agent_args( + "default", + &sw, + "https://10.0.0.7:4261", + Some("/var/lib/devstack-node/default"), + false, + ); + let s = a.join(" "); + assert_eq!( + s, + "node agent --pool default --listen 0.0.0.0:4261 --api https://10.0.0.7:4261 --membership /var/lib/devstack-node/default --max-cpus 8 --max-memory-gib 8.00 --no-new-lanes" + ); + assert!( + !agent_args("default", &Switch::default(), "https://x:4261", None, true) + .contains(&"--no-new-lanes".to_string()) + ); + } + + #[test] + fn an_impossible_switch_is_refused() { + let ok = Switch { + enabled: true, + distro: Some("Ubuntu-24.04".into()), + ..Switch::default() + }; + assert_eq!(ok.problem(), None); + for bad in [ + Switch { + max_cpus: Some(0.0), + ..ok.clone() + }, + Switch { + max_memory: Some(0), + ..ok.clone() + }, + Switch { + port: Some(0), + ..ok.clone() + }, + Switch { + distro: Some("x; rm -rf /".into()), + ..ok.clone() + }, + ] { + assert!(bad.problem().is_some(), "{bad:?}"); + } + } + + #[test] + fn an_old_share_file_does_not_switch_the_agent_on() { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join("share.json"), r#"{"enabled":true}"#).unwrap(); + assert!(!Switch::load(d.path()).enabled); + } + + #[test] + fn wsl_lists_in_utf16() { + let text = "Ubuntu\r\nUbuntu-24.04\r\ndocker-desktop\r\n"; + let utf16: Vec = text.encode_utf16().flat_map(u16::to_le_bytes).collect(); + assert_eq!( + wsl::parse_list(&wsl::decode(&utf16)), + vec!["Ubuntu".to_string(), "Ubuntu-24.04".to_string()] + ); + assert_eq!( + wsl::parse_list(&wsl::decode(b"Debian\n")), + vec!["Debian".to_string()] + ); + } + + #[test] + fn a_distribution_is_judged_by_what_the_agent_needs() { + let probe = wsl::parse_probe( + "mode=mirrored\ndocker=Ubuntu 24.04.5 LTS\nnvidia_runtime=1\ngpus=1\ndevstack=devstack 0.50.0\nmemory=12884901888\n", + ); + let c = wsl::judge("Ubuntu-24.04", true, &probe, Some(true), "0.50.0", 4261); + assert!(c.iter().all(|c| c.ok), "{c:?}"); + + let probe = wsl::parse_probe( + "mode=nat\ndocker=Docker Desktop\nnvidia_runtime=0\ngpus=1\ndevstack=devstack 0.49.4\n", + ); + let c = wsl::judge("Ubuntu", true, &probe, Some(false), "0.50.0", 4261); + let failed: Vec<&str> = c + .iter() + .filter(|c| !c.ok) + .map(|c| c.name.as_str()) + .collect(); + assert_eq!( + failed, + ["networking", "docker", "devstack", "gpu", "firewall"] + ); + let required: Vec<&str> = c + .iter() + .filter(|c| !c.ok && !c.optional) + .map(|c| c.name.as_str()) + .collect(); + assert_eq!(required, ["networking", "docker", "devstack"]); + assert!(c.iter().filter(|c| !c.ok).all(|c| c.fix.is_some())); + let p = wsl::prompt(Some("Ubuntu"), &c, 4261); + assert!( + p.contains("--version 0.50.0") && p.contains("networkingMode=mirrored"), + "{p}" + ); + + let c = wsl::judge("Gone", false, &Default::default(), None, "0.50.0", 4261); + assert_eq!(c.len(), 1); + assert!(!c[0].ok); + } + + #[test] + fn the_address_toward_the_coordinator_is_a_local_one() { + let ip = local_address("https://127.0.0.1:4260").unwrap(); + assert!(ip.is_loopback()); + assert_eq!(local_address("not a url"), None); + } +} diff --git a/crates/devstack-hub/src/share.rs b/crates/devstack-hub/src/share.rs index 69af0bc8..befa5b4c 100644 --- a/crates/devstack-hub/src/share.rs +++ b/crates/devstack-hub/src/share.rs @@ -6,14 +6,14 @@ //! reports the machine then, with its API and its leases, which a report of //! the hub's would drop (#170). //! -//! The hub offers nothing to the pool. A machine runs other members' lanes -//! with a node agent (`devstack node agent`, granted by an admin), and the -//! dashboard's share switch never started one: it only reported capacity -//! nobody could use, and is gone until it does (#171; on Windows, which -//! cannot run the Linux lanes, #168). +//! The hub's own report offers nothing to the pool. A machine runs other +//! members' lanes with a node agent, granted by an admin: started by hand +//! (`devstack node agent`), or by the share switch, which the hub runs +//! (`nodehost.rs`, ADR-0113). While its agent runs, the hub does not report. //! //! - `GET /hub/pool/share?pool=`: what is measured, the last report, the -//! coordinator's devstack, and why nothing is offered (`unavailable`) +//! coordinator's devstack, the switch and its agent (`switch`, `host`) +//! - `PUT /hub/pool/share?pool=`: change the switch (`nodehost::Switch`) use axum::Json; use axum::extract::Query; @@ -29,11 +29,6 @@ use std::time::Duration; const EVERY: Duration = Duration::from_secs(15); -/// Why the hub offers nothing to the pool. -const NOT_SHARED: &str = "A machine runs other members' lanes with a node agent \ - (`devstack node agent`, granted by an admin); the dashboard does not start one yet \ - (#171, on Windows #168)."; - #[derive(Debug, Clone, Default, Serialize)] pub struct Status { /// What the machine has in all. @@ -54,8 +49,10 @@ pub struct Status { /// report; `None` before one, or from an older coordinator. #[serde(skip_serializing_if = "Option::is_none")] pub coordinator: Option, - /// Why this machine offers the pool nothing. - pub unavailable: &'static str, + /// The share switch (ADR-0113), as saved. + pub switch: crate::nodehost::Switch, + /// The node agent the switch runs. + pub host: crate::nodehost::Host, } #[derive(Deserialize, Default)] @@ -91,10 +88,7 @@ fn dir(pool: &str) -> std::path::PathBuf { } fn entry<'a>(map: &'a mut BTreeMap, pool: &str) -> &'a mut Status { - map.entry(pool.to_string()).or_insert_with(|| Status { - unavailable: NOT_SHARED, - ..Status::default() - }) + map.entry(pool.to_string()).or_default() } fn now_ms() -> u128 { @@ -109,6 +103,7 @@ pub fn start() { return; } std::thread::spawn(run); + crate::nodehost::start(state()); } fn run() { @@ -137,7 +132,13 @@ fn run() { let Some(status) = STATUS.get() else { return }; let gpus = devstack_node::share::gpus(); for (pool, _) in devstack_node::member::pools(&state()) { - let result = round(&dir(&pool), total, &gpus); + // The switch's agent reports the machine (in WSL on Windows, + // where the membership's lock is not seen). + let result = if crate::nodehost::runs(&pool) { + Ok(Round::Agent) + } else { + round(&dir(&pool), total, &gpus) + }; let mut map = status.lock().unwrap(); let st = entry(&mut map, &pool); st.total = total; @@ -263,7 +264,11 @@ pub async fn get(Query(q): Query) -> Response { st.total = a.total; st.free = a.free; } - Json(st.clone()).into_response() + let mut out = st.clone(); + drop(map); + out.switch = crate::nodehost::Switch::load(&dir(&pool)); + out.host = crate::nodehost::host(&pool); + Json(out).into_response() } None => ( StatusCode::SERVICE_UNAVAILABLE, @@ -273,6 +278,41 @@ pub async fn get(Query(q): Query) -> Response { } } +/// Change the share switch (ADR-0113): saved, and acted on at once. +pub async fn put(Query(q): Query, Json(new): Json) -> Response { + let bad = |m: String| { + ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": m })), + ) + .into_response() + }; + let Some(pool) = q.name() else { + return bad("pool: a-z, 0-9, `-` and `_`, at most 32".into()); + }; + if let Some(why) = new.problem() { + return bad(why); + } + let d = dir(&pool); + match devstack_node::member::Local::new(&d).membership() { + Ok(Some(m)) if m.state == State::Approved => {} + _ => { + return bad(format!( + "this machine is no approved member of the pool `{pool}`" + )); + } + } + if let Err(e) = new.save(&d) { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": e.to_string() })), + ) + .into_response(); + } + crate::nodehost::poke(&pool, &d); + get(Query(PoolQuery { pool: Some(pool) })).await +} + #[cfg(test)] mod tests { use super::{Round, round}; diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index a8a743be..b40bd659 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -90,7 +90,8 @@ pub struct NodeConfig { pub dir: PathBuf, /// Where requesters reach the node API: `https://host:port`. pub api: String, - /// What the node shares; `enabled` is implied. + /// What the node shares; `enabled: false` takes no new lanes and keeps + /// the running ones (ADR-0113 point 5). pub share: Settings, /// A server its owner never reclaims (ADR-0026). pub dedicated: bool, @@ -3875,11 +3876,9 @@ async fn background(s: Shared) { }) .await; } - let offer = Settings { - enabled: true, - ..s.share.clone() - } - .offer(free, percent); + // An agent that takes no new lanes (`--no-new-lanes`, ADR-0113 + // point 5) offers nothing; its running lanes go on. + let offer = s.share.offer(free, percent); // The caps hold for the lanes together: what they use already is // not on offer again. let offer = Amount { @@ -3978,7 +3977,7 @@ async fn background(s: Shared) { total: Some(total), used: Some(used), gpus, - sharing: true, + sharing: s.share.enabled, cpus: available.cpus, memory: available.memory, api: Some(s.api.clone()), diff --git a/crates/devstack/src/dispatch/pool.rs b/crates/devstack/src/dispatch/pool.rs index 78052203..b5a106d9 100644 --- a/crates/devstack/src/dispatch/pool.rs +++ b/crates/devstack/src/dispatch/pool.rs @@ -107,6 +107,7 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { dedicated, pool, print_unit: true, + .. } => { print!( "{}", @@ -128,8 +129,21 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { max_memory_gib, dedicated, pool, + membership, + no_new_lanes, print_unit: false, - } => poolcmd::agent(&pool, &listen, api, max_cpus, max_memory_gib, dedicated), + } => poolcmd::agent( + &pool, + &listen, + api, + poolcmd::AgentShare { + max_cpus, + max_memory_gib, + new_lanes: !no_new_lanes, + }, + dedicated, + membership, + ), NodeAction::Members { action, dir } => match action.unwrap_or(MembersAction::List) { MembersAction::List => poolcmd::members_list(dir), MembersAction::Approve { member, admin } => { diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index a1209d14..05fc63b2 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -708,6 +708,15 @@ enum NodeAction { /// The pool it runs lanes for (ADR-0034); one agent per pool. #[arg(long, default_value = "default")] pool: String, + /// The membership's directory, instead of this machine's for + /// `--pool`: the hub on Windows runs the agent in a WSL distribution + /// with a copy of the machine's membership there (ADR-0113). + #[arg(long)] + membership: Option, + /// Take no new lanes; those that run keep running (ADR-0113 point 5: + /// the share switch turned off while guest lanes run). + #[arg(long)] + no_new_lanes: bool, /// Print a systemd unit that runs this agent with these arguments /// and starts it again whenever it ends (an update an admin ordered /// included, ADR-0039), instead of running it. diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index 76e051e0..6df0cb20 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -895,13 +895,20 @@ fn pool_one(pool: &str, local: &Local) -> Result<()> { Ok(()) } +/// What a node agent offers: its caps, and whether it takes new lanes. +pub struct AgentShare { + pub max_cpus: Option, + pub max_memory_gib: Option, + pub new_lanes: bool, +} + pub fn agent( pool: &str, listen: &str, api: Option, - max_cpus: Option, - max_memory_gib: Option, + offer: AgentShare, dedicated: bool, + membership: Option, ) -> Result<()> { let addr: std::net::SocketAddr = listen.parse().map_err(|e| { anyhow!("--listen {listen}: {e} (an address and a port, e.g. 10.0.0.5:4261)") @@ -914,11 +921,16 @@ pub fn agent( } let api = api.unwrap_or_else(|| format!("https://{addr}")); let share = devstack_node::share::Settings { - enabled: true, - max_cpus, - max_memory: max_memory_gib.map(|g| (g * f64::from(1u32 << 30)) as u64), + enabled: offer.new_lanes, + max_cpus: offer.max_cpus, + max_memory: offer + .max_memory_gib + .map(|g| (g * f64::from(1u32 << 30)) as u64), + }; + let dir = match membership { + Some(d) => d, + None => member_dir(pool)?, }; - let dir = member_dir(pool)?; let m = Local::new(&dir) .membership()? .filter(|m| m.state == State::Approved) diff --git a/crates/devstack/tests/hub.rs b/crates/devstack/tests/hub.rs index 2fc4a39e..d48da2ad 100644 --- a/crates/devstack/tests/hub.rs +++ b/crates/devstack/tests/hub.rs @@ -1040,31 +1040,35 @@ fn down_then_up_at_once_runs_again() { } } -/// #169: the hub offers the pool nothing and says why; the share switch is -/// gone until it starts a node agent (#171). +/// ADR-0113: the share switch and its agent over the API. A machine in no +/// pool shows the switch off and cannot turn it on; an impossible switch is +/// refused before anything is saved. #[test] -fn the_hub_offers_the_pool_nothing_and_says_why() { +fn the_share_switch_needs_a_membership() { let h = start(); let p = h.port; let bearer = format!("Authorization: Bearer {}\r\n", token(&h)); let (s, _, body) = get(p, "/hub/pool/share", &bearer); assert_eq!(s, 200, "{body}"); let v: serde_json::Value = serde_json::from_str(&body).unwrap(); - let why = v["unavailable"].as_str().unwrap_or(""); - assert!(why.contains("#171") && !why.contains(" "), "{v}"); - assert!( - v.get("settings").is_none() && v.get("offer").is_none(), - "{v}" - ); - let body = r#"{"enabled":true}"#; - let (s, _, _) = http( - p, - &format!( - "PUT /hub/pool/share HTTP/1.1\r\nHost: 127.0.0.1:{p}\r\n{bearer}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ), - ); - assert_eq!(s, 405, "no switch to turn on"); + assert_eq!(v["switch"]["enabled"], false, "{v}"); + assert_eq!(v["host"]["state"], "off", "{v}"); + assert!(v.get("unavailable").is_none(), "{v}"); + let put = |body: &str| { + http( + p, + &format!( + "PUT /hub/pool/share HTTP/1.1\r\nHost: 127.0.0.1:{p}\r\n{bearer}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ), + ) + }; + let (s, _, body) = put(r#"{"enabled":true}"#); + assert_eq!(s, 400, "{body}"); + assert!(body.contains("no approved member"), "{body}"); + let (s, _, body) = put(r#"{"enabled":true,"max_cpus":0}"#); + assert_eq!(s, 400, "{body}"); + assert!(body.contains("max_cpus"), "{body}"); } /// ADR-0045: the settings over the API, and a link from a notification diff --git a/docs/adr/0031-a-coordinator-places-lanes.md b/docs/adr/0031-a-coordinator-places-lanes.md index e9007a82..04b47e73 100644 --- a/docs/adr/0031-a-coordinator-places-lanes.md +++ b/docs/adr/0031-a-coordinator-places-lanes.md @@ -1,6 +1,6 @@ # ADR-0031: A coordinator places lanes and admits members; nodes admit leases; data goes directly -- **Status:** Accepted (2026-10-16), amended 2026-10-16 (one binary: `devstack node`), amended 2026-10-19 (point 8: which devstack each party runs), amended 2026-10-21 (point 3: no share switch) +- **Status:** Accepted (2026-10-16), amended 2026-10-16 (one binary: `devstack node`), amended 2026-10-19 (point 8: which devstack each party runs), amended 2026-10-21 (point 3: no share switch), point 3 amended by ADR-0113 (the switch runs the node agent) - **Date:** 2026-10-16 - **Deciders:** project owner - **Related:** [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0026](0026-placement-by-the-requester-admission-by-the-node.md) (points 1 and 3 replaced here), [ADR-0027](0027-trust-between-nodes.md) (points 1 and 2 replaced here), [ADR-0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md), [ADR-0015](0015-devstack-is-optional.md), [ADR-0032](0032-the-pool-is-administered-in-the-dashboard.md) (point 2 extended there: admins in the dashboard, nodes granted) diff --git a/docs/adr/0113-the-share-switch-runs-the-node-agent.md b/docs/adr/0113-the-share-switch-runs-the-node-agent.md new file mode 100644 index 00000000..196c9064 --- /dev/null +++ b/docs/adr/0113-the-share-switch-runs-the-node-agent.md @@ -0,0 +1,133 @@ +# ADR-0113: The share switch runs the node agent: in the hub on Linux, in WSL2 on Windows + +- **Status:** Accepted (card in the pull request); built +- **Date:** 2026-11-18 +- **Deciders:** project owner +- **Related:** [ADR-0031](0031-a-coordinator-places-lanes.md) (point 3, amended 2026-10-21: the switch removed), [ADR-0032](0032-the-pool-is-administered-in-the-dashboard.md) (admins grant nodes), [ADR-0033](0033-a-node-decides-what-runs-on-it.md), [ADR-0011](0011-platform-windows-native-first.md), [ADR-0112](0112-a-node-gives-a-lane-the-gpus-it-asked-for.md) (GPUs), [#171](https://github.com/nuetzliches/devstack/issues/171), [#168](https://github.com/nuetzliches/devstack/issues/168), [#170](https://github.com/nuetzliches/devstack/issues/170) + +## Context + +The share switch was removed on 2026-10-21 (ADR-0031, amended): it reported +capacity but never started a node agent, so no lane ever ran on a machine +that only switched it on. #171 asked for a switch that makes the machine a +node, and #168 for a way to run the agent on Windows, where lanes (Linux +containers) cannot run natively; #168 leaned to Docker-in-Docker in Docker +Desktop. + +A spike on 2026-11-18 (branch `spike/168-wsl-gpu-node`, its result in +#168) ran the released Linux agent in a WSL2 distribution with Docker Engine +of its own, `networkingMode=mirrored` and a Hyper-V firewall rule, as a +member of its own: another member's lane started on it and its container saw +the machine's NVIDIA GPU. It also showed what made that hard by hand: two +members for one machine, a terminal window that must stay open, `join` run +on the wrong side, and limits above what WSL may take. + +## Decision + +The owner approved the review card in the conversation on **2026-11-18**, +points 1 to 5: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | concept | The share switch makes the machine a node: on Linux the agent runs in the hub (as #171 proposes), on Windows the hub starts it in a WSL2 distribution (`wsl.exe -d -u root -- devstack node agent …`), starts it again when it ends, and ends it when switched off. | Docker-in-Docker (#168): a privileged container and an image of its own; an agent in a terminal window that must stay open | Medium: the hub supervises a process, and the switch depends on it | +| 2 | concept | The agent in WSL serves the machine's membership (the hub's), read from the Windows side: one member per machine; while it runs, the hub does not report (#170). | Two members per machine as in the spike: two grants, the Windows side's taken back by hand | Medium: the agent reads its membership from elsewhere | +| 3 | trust | The hub does not set the distribution up: it checks it (the spike's `check.sh`, in the hub) and shows what is missing, as commands and as a prompt for a coding agent; what needs elevation or ends Docker Desktop (the Hyper-V rule, `wsl --shutdown`) only the user does. | A hub that installs packages, rewrites `.wslconfig` and ends Docker Desktop | Low | +| 4 | contract | The caps come from the switch's settings and stay below what `.wslconfig` gives WSL (`memory=`); a node at a workplace is never `--dedicated`. | Caps above the VM's memory: the node offers more than it has | Low | +| 5 | contract | Off means no new lanes; running lanes go on until their owners stop them, and the switch shows how many still run. | Ending running lanes at once (would need an amendment to ADR-0033) | Low | + +As built: + +1. **The switch** (`crates/devstack-hub/src/nodehost.rs`, `Switch`): per + pool `{enabled, max_cpus?, max_memory?, distro?, port?}` in + `node-host.json` beside the membership. A file of its own: the + `share.json` of the removed switch may still say `enabled` and must not + start an agent after an update. `PUT /hub/pool/share` saves it (an + approved member only, impossible values refused) and acts at once; + `GET` carries it (`switch`) and the agent (`host`). +2. **The supervisor** (`nodehost::round`, every 5 s per pool): from the + switch, what runs and the other members' lanes here (`decide`) it + starts, restarts (other caps, distribution or port), drains or stops + the agent. An agent that ends within 30 s of its start is `failed` and + started again after a minute; its last 40 lines of output are kept. An + agent started by hand for the membership (its `node/lock` held) wins: + `foreign`, the switch starts none. Whether an admin granted the + machine is read from the member list (`granted`). +3. **Linux:** `devstack_node::node::serve` on a thread of the hub, with the + machine's membership and `0.0.0.0:`; its API is the address this + machine reaches the coordinator from (`local_address`, a UDP socket + connected, nothing sent). +4. **Windows:** the membership's files are copied into + `/var/lib/devstack-node/` in the distribution (root only, folders + left out: the Windows side's state), and the agent runs as `wsl.exe -d + -u root -- sh -c 'exec devstack node agent --membership … '`, + with `~/.local/bin` and WSL's GPU tools on `PATH`. A new hub first ends + one an earlier hub left running there (`pkill` on its `--membership`). + The hub knows the agent it runs and reports nothing meanwhile (the + membership's lock is in WSL, not seen on Windows). +5. **The checks** (`nodehost::wsl::judge`): the distribution exists, its + networking mode is `mirrored`, `docker` is an engine of its own (not + Docker Desktop), devstack there is this machine's version: required. + An NVIDIA GPU with the container toolkit and the Hyper-V firewall rule + `devstack-node` (read with `Get-NetFirewallHyperVRule`): shown, not + required. Each missing one has the command for it; together they make + the prompt (`host.prompt`), copied in the dashboard. +6. **Off with guests** (point 5): the agent is started again with + `--no-new-lanes`, which reports `sharing: false` and offers nothing; + once no other member's lane runs here, it ends. The node's report + carries `sharing` from its settings now (it said `true` always). +7. **The agent's CLI:** `devstack node agent --membership ` (point 2) + and `--no-new-lanes` (point 5). +8. **The dashboard** (`ShareSwitch.vue`): the switch in the sidebar and in + **Pool → This machine**, with the distribution (Windows), the caps, the + state, the checks with a copy button per command, the setup prompt and + the agent's last lines. + +Decided while building, not on the card: + +- The prompt is copied from the switch, not handed to an agent the hub + starts (the prompt registry of ADR-0046 is keyed by a stack or a folder; + this one is about the machine). +- Point 4 holds without a check of its own: the agent in WSL measures what + is free inside the VM, so half of it is below `.wslconfig`'s `memory=` + by construction; the caps can only lower it. +- An agent the switch runs takes no update an admin orders (ADR-0039, + `on_update: None`): it runs the hub's devstack, and the hub is updated + with the machine. +- The switch is per pool, like the membership; the default port is 4261, + so two pools switched on need different ports. +- Not on macOS yet (ADR-0054): the switch says so and stays off. + +## Alternatives considered + +- **Docker-in-Docker in Docker Desktop** (#168's direction): a hard cap and + a separate image cache, but a privileged container, an image to build and + pin, and Desktop's VM shared with the user's own containers. WSL2 with an + engine of its own needs none of that and was proven by the spike. +- **A member of its own for the distribution** (the spike's way): works + today, but every machine shows twice and needs two grants. +- **The hub setting the distribution up:** quicker for the user, but it + would install packages as root, rewrite `.wslconfig` and end Docker + Desktop without being asked. + +## Consequences + +- A Windows machine with an NVIDIA GPU can offer it to the pool from the + dashboard, once its distribution is set up. +- The membership's key is copied into the distribution, readable by its + root only; it is the same user's machine. +- The hub on Linux runs other members' lanes in its own process: a hub + restart restarts the agent (the lanes keep running, their leases + persist). +- Verified by unit tests (the step from switch to agent, the agent's + arguments, the distribution's checks and prompt, the WSL list, an old + `share.json`), an API test (no switch without a membership), the + dashboard's tests; not yet on a Windows machine with WSL, which the next + run on the spike's machine does. + +## Enforced by + +`crates/devstack-hub/src/nodehost.rs`, `crates/devstack-hub/src/share.rs` +(no report while the switch's agent runs, `PUT /hub/pool/share`), +`crates/devstack-node/src/node.rs` (`sharing` from the settings), +`crates/devstack/src/poolcmd.rs` (`--membership`, `--no-new-lanes`), +`ui/src/components/ShareSwitch.vue`. diff --git a/docs/adr/README.md b/docs/adr/README.md index f027aedf..e2a236f5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -113,7 +113,7 @@ stay. | [0028](0028-lane-images.md) | A remote lane runs in a stack-provided toolchain image; the node supplies devstack | Accepted, amended (a Dockerfile the node builds); point 3 noted 2026-10-26 (`prepare`'s results are in ADR-0062's store); addendum 2026-10-29 (no lane image: refused before the lease) | | [0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) | A remote lane works on a mirror of the requester's tree; ports and API come back over one connection | Accepted; point 2 amended (`[lanes] sync`); Consequences built by ADR-0038; point 4 extended to UDP by ADR-0056 | | [0030](0030-each-lane-has-its-own-infrastructure.md) | Each lane has its own infrastructure | Accepted; point 2 detailed by ADR-0057 (an announced port moves inside the container too); the main tree's stop while lanes run, ADR-0068; point 5 amended 2026-10-27 (Docker Desktop's VM checked for the containers); point 3 (`shared`) deprecated by ADR-0080 | -| [0031](0031-a-coordinator-places-lanes.md) | A coordinator places lanes and admits members; nodes admit leases; data goes directly | Accepted, amended (one binary: `devstack node`), amended 2026-10-19 (versions in the pool), amended 2026-10-21 (no share switch) | +| [0031](0031-a-coordinator-places-lanes.md) | A coordinator places lanes and admits members; nodes admit leases; data goes directly | Accepted, amended (one binary: `devstack node`), amended 2026-10-19 (versions in the pool), amended 2026-10-21 (no share switch); point 3 amended by ADR-0113 (the switch runs the node agent) | | [0032](0032-the-pool-is-administered-in-the-dashboard.md) | The pool is administered in the dashboard, by members with the admin role | Accepted, amended (admins grant nodes); extended by ADR-0039 (updating a server); point 4 detailed by ADR-0076 (tabs, a machine's page) | | [0033](0033-a-node-decides-what-runs-on-it.md) | A node decides who runs lanes on it, and what a lane there may do | Accepted, amended (what Compose files may ask; limits; the node's own policy; amended 2026-10-20: the node runs the model it checked, known keys only, a lane's projects end with it; noted 2026-10-21: what holds while a lane's containers start under its running daemon; extended by ADR-0092: the policy's `public_links`) | | [0034](0034-a-machine-can-belong-to-several-pools.md) | A machine can belong to several pools; pools do not trust each other | Accepted; noted 2026-10-20 (several agents on one Docker engine) | @@ -195,3 +195,4 @@ stay. | [0110](0110-a-static-service-forwards-paths-to-another-server.md) | A static service forwards paths to another server, as a reverse proxy in front of it would | Accepted (card in the pull request); built; amended 2026-11-17 (connections to the target kept, #556) | | [0111](0111-the-dashboards-advisory-gate-counts-what-the-bundle-holds.md) | The dashboard's advisory gate counts what the bundle holds, not npm's runtime tree | Accepted (card in the pull request); built | | [0112](0112-a-node-gives-a-lane-the-gpus-it-asked-for.md) | A node gives a lane the GPUs it asked for, and no other lane | Accepted (card in the pull request); built | +| [0113](0113-the-share-switch-runs-the-node-agent.md) | The share switch runs the node agent: in the hub on Linux, in WSL2 on Windows | Accepted (card in the pull request); built | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 2b2f0ff5..ca101e41 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -150,7 +150,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/pool/nodes/{id}/policy` (a `NodePolicy` or `null`) | cookie + Origin | admins only: what the node lets run on it, `{allow, repos, memory_headroom?, max_cpus?, share_percent?, network: "lan"\|"internet"\|"none"}`; `null` lifts it | | `POST /hub/pool/join {"coordinator", "fingerprint", "name"?}` | cookie + Origin | ask a pool to admit this machine (`devstack join` without waiting); `GET /hub/pool` shows it pending until an admin approves. `coordinator` is `https://[:]` and nothing more (`400` otherwise). Errors of every `/hub/pool...` route pass on the coordinator's own `{"error"}` only, never the body of whatever else answered | | `POST /hub/pool/members/{id}/role {"role"}` | cookie + Origin | admins only: `member` or `admin`; `409 {"error"}` for the last admin. A member who is no admin gets `403` from all three | -| `GET /hub/pool/share?pool=` | cookie | this machine in the pool, per pool: what it has and what is free (`total`, `free`), whether it is an approved member, the last report (`reported_at`, `error`), whether a node agent of the same membership runs here and reports the machine instead of the hub (`agent`, [#170](https://github.com/nuetzliches/devstack/issues/170)), the `PoolRelease` the coordinator answered it with (`coordinator?`), and why it offers nothing (`unavailable`: a node agent runs lanes, the dashboard does not start one yet, [#171](https://github.com/nuetzliches/devstack/issues/171)). The share switch and its `PUT` are gone (#169) | +| `GET /hub/pool/share?pool=` | cookie | this machine in the pool, per pool: what it has and what is free (`total`, `free`), whether it is an approved member, the last report (`reported_at`, `error`), whether a node agent of the same membership runs here and reports the machine instead of the hub (`agent`, [#170](https://github.com/nuetzliches/devstack/issues/170)), the `PoolRelease` the coordinator answered it with (`coordinator?`), the share switch (`switch`: `{enabled, max_cpus?, max_memory?, distro?, port?}`) and the node agent it runs (`host`: `{state: off\|unsupported\|blocked\|starting\|running\|draining\|failed\|foreign, detail?, api?, granted?, guests, checks?: [{name, ok, detail, fix?, optional?}], distros?, prompt?, output?}`, [ADR-0113](adr/0113-the-share-switch-runs-the-node-agent.md)) | +| `PUT /hub/pool/share?pool= {enabled, max_cpus?, max_memory?, distro?, port?}` | cookie + Origin | change the share switch: saved in `node-host.json` beside the membership and acted on within seconds; answers like `GET`. `400 {"error"}` for a machine that is no approved member, a cap of 0 or less, port 0, or a distribution name `wsl -l` would not show | | `POST /hub/shutdown` | `Authorization: Bearer ` | `202`; the hub exits (`devstack hub stop`) | | `POST /hub/pair` | `Authorization: Bearer ` | `{"code": "...", "url": "http://127.0.0.1:4250/auth?code=..."}` (CLI only) | diff --git a/docs/pool.md b/docs/pool.md index e027d0ac..5db49e11 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -65,17 +65,55 @@ form. `devstack pool` then lists the machines, what each offers, and which lanes run where. A member that only asks for lanes needs nothing else. A machine runs other -members' lanes only with a node agent, below. The dashboard has no switch for -that: the share switch it had only reported capacity, never started an agent, -and is gone until it does -([#171](https://github.com/nuetzliches/devstack/issues/171); on Windows, -which cannot run the Linux lanes yet, -[#168](https://github.com/nuetzliches/devstack/issues/168)). The hub reports -the machine (online, what it has, its devstack) and offers nothing. While a -node agent of the same membership runs on the machine, the hub does not -report for that pool and the agent reports the machine: the agent holds -`node/lock` in the membership's folder while it runs -([#170](https://github.com/nuetzliches/devstack/issues/170)). +members' lanes only with a node agent, which an admin grants. The **share +switch** (the sidebar, **Pool → This machine**) runs one +([ADR-0113](adr/0113-the-share-switch-runs-the-node-agent.md)); a server +runs it by hand ([below](#run-a-node)). The hub reports the machine (online, +what it has, its devstack) and offers nothing itself. While a node agent of +the same membership runs, the hub does not report for that pool and the +agent reports the machine: the agent holds `node/lock` in the membership's +folder while it runs +([#170](https://github.com/nuetzliches/devstack/issues/170)), and the hub +knows the agent it runs itself. + +### The share switch + +On, the hub runs the node agent for the current pool and starts it again +when it ends (after a failed start, a minute later); the switch, its caps, +the WSL distribution and the port are kept in `node-host.json` beside the +membership. The agent offers half of what is free, never more than the caps; +it listens on port 4261 (`port` in the switch) on every address, and +requesters reach it at the address this machine reaches the coordinator +from. Until an admin grants the machine as a node, the switch says it waits +for one. Turned off while other members' lanes run here, the agent takes no +new lanes (`devstack node agent --no-new-lanes`) and ends once the last one +did; their owners stop them, or an admin ends the lease. + +- **Linux:** the agent runs inside the hub, with Docker of the user who runs + it. An agent started by hand for the same membership wins: the switch + says so and starts none. +- **Windows:** lanes are Linux containers, so the agent runs in a WSL2 + distribution you name: one with Docker Engine of its own, not Docker + Desktop's (turn Desktop's WSL integration off for it), with + `networkingMode=mirrored` in `.wslconfig`, and devstack of the same + version installed as root. The hub copies the machine's membership into + it (`/var/lib/devstack-node/`, root only: one member per machine) + and runs `wsl.exe -d -u root -- devstack node agent --membership + …`. It never sets the distribution up: it checks it (the networking mode, + the engine, devstack's version, an NVIDIA GPU and the container toolkit, + the Hyper-V firewall rule `devstack-node` for the port) and shows what is + missing with the command for it, and a prompt a coding agent can work + through. What needs an elevated shell stays with you: + + ```powershell + New-NetFirewallHyperVRule -Name devstack-node -DisplayName "devstack node agent" ` + -Direction Inbound -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' ` + -Protocol TCP -LocalPorts 4261 + ``` + + `.wslconfig`'s `memory=` caps the whole distribution, so what the agent + offers stays below it. +- **macOS:** not yet. Lanes of other members on your machine always show: a banner below the dashboard's top bar (it can be hidden until a lane comes or goes), a tile in @@ -88,8 +126,9 @@ the pool's leases after each share report. ## Run a node A machine that runs lanes for others, typically a server, runs the node -agent. It needs Linux with Docker (lanes run in containers; a Windows machine -asks for lanes but does not run them yet) and must have joined the pool: +agent. It needs Linux with Docker (lanes run in containers; a Windows +machine runs it in WSL2 through the [share switch](#the-share-switch)) and +must have joined the pool: ```sh devstack join https://10.0.0.5:4260 --fingerprint --name build-server @@ -100,7 +139,13 @@ devstack node agent --listen 10.0.0.7:4261 --dedicated --max-cpus 12 --max-memor A machine runs the pool's lanes only once an admin granted it (`devstack node members node on`, or `off` to take it back): until then the coordinator ignores the API its agent reports, places nothing there, and the agent says -why. A member that only shares from the dashboard is no node. +why; so does the share switch. + +- `--no-new-lanes`: take no new lanes; those running go on. The share + switch turned off while others' lanes run uses it. +- `--membership `: the membership's folder instead of this machine's + for `--pool`; the share switch on Windows runs the agent in WSL with a copy + of the machine's. - `--dedicated`: a server its owner never reclaims. The pool shows it as a server, and only a lane on such a node may take the main ports. diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index f7e05a7e..e2a4c601 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -13,7 +13,7 @@ // ?mock=nodocker the Docker engine is stopped; "Start Docker" brings it up after 4 s // ?mock=nopool this machine is in no pool; ?mock=poolmember: a member, not an admin // ?mock=hubdown the hub is unreachable (toggle at runtime: window.devstackMock.hubDown(false)) -import type { AttentionItem, StackGlance, DockerEngine, Guest, HubEvent, PoolFeed, PoolNode, PoolSkillsAdmin, PoolSkillsState, LaneView, McpUpstream, NotifySettings, UpstreamFilter, PoolUpstream, LogStreamEvent, RunLogEvent, StackEvent, StackEntry, StackView, PoolPublicLinksAdmin, PublicLinksState } from '../types'; +import type { AttentionItem, StackGlance, DockerEngine, Guest, HubEvent, PoolFeed, PoolNode, PoolSkillsAdmin, PoolSkillsState, LaneView, McpUpstream, NotifySettings, UpstreamFilter, PoolUpstream, LogStreamEvent, RunLogEvent, StackEvent, StackEntry, StackView, PoolPublicLinksAdmin, PublicLinksState, ShareSwitch } from '../types'; import type { Response, StreamHandlers, Subscription, Transport } from '../transport'; import { Unreachable } from '../transport'; import { persist } from '@/lib/persist'; @@ -821,6 +821,7 @@ export class MockTransport implements Transport { } if (p === '/hub/pool' && method === 'GET') return json(200, hub.pool.overview()); if (p === '/hub/pool/share' && method === 'GET') return json(200, hub.pool.share()); + if (p === '/hub/pool/share' && method === 'PUT') return json(200, hub.pool.setShare(body as unknown as ShareSwitch)); const pn = /^\/hub\/pool\/nodes\/([^/]+)\/(pause|resume)$/.exec(p); if (pn && method === 'POST') { const r = hub.pool.pause(decodeURIComponent(pn[1]), pn[2] === 'pause'); diff --git a/ui/src/api/mock/pool.ts b/ui/src/api/mock/pool.ts index eab0ebdd..0a12f4b9 100644 --- a/ui/src/api/mock/pool.ts +++ b/ui/src/api/mock/pool.ts @@ -3,7 +3,7 @@ // no pool, `?mock=poolmember` one without the admin role. A provisioner made // two nodes (ADR-0051): one runs a lane, one waits for an admin to confirm it; // a third machine's enrolment token was used twice (an alarm). -import type { PoolAuditEntry, PoolLease, PoolMember, PoolNode, PoolOverview, PoolRole, Provisioning, ShareStatus } from '../types'; +import type { PoolAuditEntry, PoolLease, PoolMember, PoolNode, PoolOverview, PoolRole, Provisioning, ShareHost, ShareStatus, ShareSwitch } from '../types'; type R = { status: number; body: unknown }; @@ -18,6 +18,9 @@ export class MockPool { /** This machine keeps its lanes off provisioned nodes. */ noProvisioned = false; private me = 'a1b2c3d4e5f60718'; + /** The share switch (ADR-0113), as on Windows: `Ubuntu-24.04` is set up, `Ubuntu` is Docker Desktop's. */ + switch: ShareSwitch = { enabled: false }; + /** `GET /hub/pool/share`: a machine with 16 cores and 64 GiB, about a third busy. */ share(): ShareStatus { const free = { cpus: 10.4 + Math.random(), memory: 38 * 2 ** 30 }; @@ -27,10 +30,61 @@ export class MockPool { member: this.joined, reported_at: this.joined ? Date.now() - 4000 : null, error: null, - unavailable: "A machine runs other members' lanes with a node agent (`devstack node agent`, granted by an admin); the dashboard does not start one yet (#171, on Windows #168).", + switch: this.switch, + host: this.host(), + }; + } + + private host(): ShareHost { + const distros = ['Ubuntu', 'Ubuntu-24.04']; + const sw = this.switch; + if (!sw.enabled) return { state: 'off', guests: 0, distros }; + if (!sw.distro) + return { + state: 'blocked', + detail: 'Choose the WSL distribution the node agent runs in (one with Docker Engine of its own, not Docker Desktop\'s).', + guests: 0, + distros, + prompt: 'Set up a WSL2 distribution on this Windows machine so that devstack can run its node agent there…', + }; + if (sw.distro === 'Ubuntu') + return { + state: 'blocked', + detail: 'The WSL distribution `Ubuntu` lacks what the node agent needs: see the checks.', + guests: 0, + distros, + checks: [ + { name: 'distribution', ok: true, detail: '`Ubuntu` is there' }, + { name: 'networking', ok: true, detail: 'networking mode: mirrored' }, + { name: 'docker', ok: false, detail: '`docker` talks to Docker Desktop', fix: "Turn Docker Desktop's WSL integration off for `Ubuntu`, then in it as root: curl -fsSL https://get.docker.com | sh" }, + { name: 'devstack', ok: false, detail: 'devstack is not installed in the distribution', fix: 'In `Ubuntu` as root: curl -fsSL https://github.com/nuetzliches/devstack/releases/latest/download/install.sh | sh -s -- --version 0.50.0' }, + { name: 'gpu', ok: true, detail: '1 NVIDIA GPU(s), the container toolkit is set up', optional: true }, + { name: 'firewall', ok: true, detail: 'Hyper-V firewall rule `devstack-node` is there', optional: true }, + ], + prompt: 'Set up a WSL2 distribution on this Windows machine so that devstack can run its node agent there…', + }; + return { + state: 'running', + api: 'https://10.0.0.21:4261', + granted: true, + guests: 0, + distros, + checks: [ + { name: 'distribution', ok: true, detail: `\`${sw.distro}\` is there` }, + { name: 'networking', ok: true, detail: 'networking mode: mirrored' }, + { name: 'docker', ok: true, detail: 'Docker Engine: Ubuntu 24.04.5 LTS' }, + { name: 'devstack', ok: true, detail: 'devstack 0.50.0 (this machine: 0.50.0)' }, + { name: 'gpu', ok: true, detail: '1 NVIDIA GPU(s), the container toolkit is set up', optional: true }, + { name: 'firewall', ok: true, detail: 'Hyper-V firewall rule `devstack-node` is there', optional: true }, + ], }; } + setShare(next: ShareSwitch): ShareStatus { + this.switch = next; + return this.share(); + } + constructor(q: string) { const s = Math.floor(Date.now() / 1000); this.joined = !q.includes('nopool'); diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 2daeff32..5cc624ff 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -927,8 +927,31 @@ export type ShareStatus = { agent?: boolean; /** The devstack the coordinator runs, from its answer to the last report; absent from an older one. */ coordinator?: PoolRelease; - /** Why this machine offers the pool nothing (a node agent runs lanes; #171, on Windows #168). */ - unavailable: string; + /** The share switch (ADR-0113); absent from an older hub. */ + switch?: ShareSwitch; + /** The node agent the switch runs; absent from an older hub. */ + host?: ShareHost; +}; +/** The share switch of one pool: `PUT /hub/pool/share`. `distro` is the WSL distribution on Windows. */ +export type ShareSwitch = { enabled: boolean; max_cpus?: number; max_memory?: number; distro?: string; port?: number }; +/** One thing the node agent needs, and whether this machine has it; `optional`: it starts without. */ +export type ShareCheck = { name: string; ok: boolean; detail: string; fix?: string; optional?: boolean }; +/** The node agent the share switch runs, as the hub last saw it. */ +export type ShareHost = { + state: 'off' | 'unsupported' | 'blocked' | 'starting' | 'running' | 'draining' | 'failed' | 'foreign'; + detail?: string; + api?: string; + /** An admin granted this machine to run lanes; absent when not asked. */ + granted?: boolean; + /** Other members' lanes running here. */ + guests: number; + checks?: ShareCheck[]; + /** Windows: the WSL distributions there are. */ + distros?: string[]; + /** For a coding agent: how to set up what the checks miss. */ + prompt?: string; + /** The agent's last lines of output. */ + output?: string[]; }; /** A pool this machine belongs to or asked to join (ADR-0034), `GET /hub/pools`. */ diff --git a/ui/src/components/ShareSwitch.test.ts b/ui/src/components/ShareSwitch.test.ts new file mode 100644 index 00000000..b15c8e35 --- /dev/null +++ b/ui/src/components/ShareSwitch.test.ts @@ -0,0 +1,103 @@ +// The share switch (ADR-0113): what the node agent's state says, the checks +// with their commands, and the switch sent with the form's distribution. +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createApp, h, nextTick } from 'vue'; +import { createPinia, setActivePinia } from 'pinia'; +import type { ShareStatus } from '@/api/types'; +import { FakeTransport, ok } from '@/test/fake'; + +const t = vi.hoisted(() => ({ current: null as FakeTransport | null })); + +vi.mock('@/api', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + api: () => { + if (!t.current) throw new Error('no fake transport'); + return t.current; + }, + }; +}); + +const { usePool } = await import('@/stores/pool'); +const ShareSwitch = (await import('./ShareSwitch.vue')).default; + +const status = (over: Partial): ShareStatus => ({ + total: { cpus: 16, memory: 64 * 2 ** 30 }, + free: { cpus: 8, memory: 32 * 2 ** 30 }, + member: true, + reported_at: null, + error: null, + ...over, +}); + +beforeEach(() => { + document.body.innerHTML = ''; + setActivePinia(createPinia()); + t.current = new FakeTransport(); +}); + +async function mounted(s: ShareStatus) { + usePool().share = s; + const el = document.createElement('div'); + document.body.appendChild(el); + createApp({ render: () => h(ShareSwitch) }).mount(el); + await nextTick(); + return el; +} + +describe('the share switch', () => { + it('shows what the distribution lacks, with the command for each', async () => { + const el = await mounted( + status({ + switch: { enabled: true, distro: 'Ubuntu' }, + host: { + state: 'blocked', + detail: 'The WSL distribution `Ubuntu` lacks what the node agent needs: see the checks.', + guests: 0, + distros: ['Ubuntu', 'Ubuntu-24.04'], + checks: [ + { name: 'networking', ok: true, detail: 'networking mode: mirrored' }, + { name: 'docker', ok: false, detail: '`docker` talks to Docker Desktop', fix: 'curl -fsSL https://get.docker.com | sh' }, + { name: 'firewall', ok: false, detail: 'no Hyper-V firewall rule', fix: 'New-NetFirewallHyperVRule …', optional: true }, + ], + prompt: 'Set up a WSL2 distribution …', + }, + }), + ); + expect(el.querySelector('[data-testid="share-state"]')?.textContent).toContain('Not ready yet'); + const checks = el.querySelector('[data-testid="share-checks"]')!; + expect(checks.querySelectorAll('li.warn')).toHaveLength(1); + expect(checks.textContent).toContain('curl -fsSL https://get.docker.com | sh'); + expect(el.querySelector('[data-testid="share-prompt"]')).not.toBeNull(); + const select = el.querySelector('[data-testid="share-distro"]')!; + expect([...select.options].map((o) => o.value)).toEqual(['', 'Ubuntu', 'Ubuntu-24.04']); + expect(select.value).toBe('Ubuntu'); + }); + + it('says that others still run lanes while it drains', async () => { + const el = await mounted(status({ switch: { enabled: false }, host: { state: 'draining', guests: 2 } })); + expect(el.querySelector('[data-testid="share-state"]')?.textContent).toBe('No new lanes; 2 of others still run here'); + expect(el.querySelector('[data-testid="share-distro"]')).toBeNull(); + }); + + it('waits for an admin while the machine is not granted', async () => { + const el = await mounted(status({ switch: { enabled: true }, host: { state: 'running', granted: false, guests: 0 } })); + expect(el.querySelector('[data-testid="share-state"]')?.textContent).toContain('Waiting for an admin'); + }); + + it('sends the switch with the chosen distribution', async () => { + const el = await mounted(status({ switch: { enabled: false }, host: { state: 'off', guests: 0, distros: ['Ubuntu-24.04'] } })); + const fake = t.current!; + let sent: unknown = null; + fake.on('/hub/pool/share', (method, _path, body) => { + if (method === 'PUT') sent = body; + return ok(status({ switch: { enabled: true, distro: 'Ubuntu-24.04' }, host: { state: 'starting', guests: 0 } })); + }); + const select = el.querySelector('[data-testid="share-distro"]')!; + select.value = 'Ubuntu-24.04'; + select.dispatchEvent(new Event('change')); + el.querySelector('[data-testid="share-switch"]')!.click(); + await vi.waitFor(() => expect(sent).toEqual({ enabled: true, distro: 'Ubuntu-24.04' })); + }); +}); diff --git a/ui/src/components/ShareSwitch.vue b/ui/src/components/ShareSwitch.vue new file mode 100644 index 00000000..293e618f --- /dev/null +++ b/ui/src/components/ShareSwitch.vue @@ -0,0 +1,309 @@ + + + + + diff --git a/ui/src/components/Sidebar.vue b/ui/src/components/Sidebar.vue index 41483582..27b87038 100644 --- a/ui/src/components/Sidebar.vue +++ b/ui/src/components/Sidebar.vue @@ -41,6 +41,7 @@ import { useStack } from '@/stores/stack'; import { SHIFT_SKIP_HINT, useUi } from '@/stores/ui'; import AddStackDialog from './AddStackDialog.vue'; import GuestTile from './GuestTile.vue'; +import ShareSwitch from './ShareSwitch.vue'; import Icon from './icons/Icon.vue'; import ShiftHint from './ShiftHint.vue'; import StackOrderMenu from './StackOrderMenu.vue'; @@ -673,6 +674,7 @@ function toggleFavourite(s: StackEntry) {
+