From 29462685be877820ea9e6bfc5a74d6d7c513f807 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Sat, 21 Nov 2026 01:22:35 +0100 Subject: [PATCH] fix: findings of the reviews before 0.52.0 (NTLM binding, GPU cap, asks) - connpool: a connection that carried a Windows login (Negotiate, NTLM, Kerberos, CredSSP; several schemes in one value) stays with its client connection (`Bound`, one per accepted connection in the service proxy, the static forward and the public link router) instead of being dropped: #603 broke NTLM, whose handshake needs one connection. Proxy login headers are stripped as hop-by-hop. - GPUs: the cap counts what the leases hold, offers the largest free GPUs, and lets the admission give any free GPU that fits within it; `nvidia-smi` runs with a 5 s limit; `--max-gpus` goes only to an agent that takes new lanes. - asks (#599): no notice about the admin's own machine, no baseline (and burst) for a non-admin, at most one notice per machine in 30 min; the Admin tab says "same address" or "similar name, not checked" with the other's id; the coordinator drops invisible characters from a machine's name; the Machines pill shows to admins only. - watcher: the relist thread lists what came meanwhile once. - share switch and setup dialog say when the GPU cap is no whole number. Bug-Class: connection-bound-state-shared Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 21 +- crates/devstack-daemon/src/proxy.rs | 118 ++++++++- crates/devstack-daemon/src/staticsrv.rs | 47 +++- crates/devstack-daemon/src/watch.rs | 13 +- crates/devstack-hub/src/asks.rs | 92 +++++-- crates/devstack-hub/src/nodehost.rs | 14 +- crates/devstack-hub/src/share.rs | 21 +- crates/devstack-node/src/connpool.rs | 226 ++++++++++++++---- crates/devstack-node/src/coordinator.rs | 36 ++- crates/devstack-node/src/linkrouter.rs | 31 ++- crates/devstack-node/src/node.rs | 13 +- crates/devstack-node/src/share.rs | 154 +++++++----- ...keeps-its-gpus-and-a-lane-shows-its-own.md | 28 ++- ...ns-see-a-machine-that-asks-to-run-lanes.md | 30 ++- ui/src/components/ShareSetupDialog.vue | 16 +- ui/src/components/ShareSwitch.vue | 14 +- ui/src/lib/asks.test.ts | 16 +- ui/src/lib/asks.ts | 26 +- ui/src/lib/gpus.test.ts | 12 +- ui/src/lib/gpus.ts | 11 + ui/src/views/pool/PoolAdmin.vue | 6 +- ui/src/views/pool/PoolMachines.vue | 4 +- 22 files changed, 706 insertions(+), 243 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7bab713..988b3139 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,9 @@ and listed with their assets on the - **A shared machine keeps the GPUs its owner wants.** The share switch takes a GPU cap (`max_gpus`, the agent's `--max-gpus`): the most GPUs - other members' lanes hold here, `0` none. A GPU whose memory is more than - a quarter used by processes on the machine is not offered either; the + other members' lanes hold here, `0` none; a lane gets any free GPU that + fits, as long as the cap allows. A GPU whose memory is more than a + quarter used by processes on the machine is not offered either; the pool shows it as "in use on the machine" (ADR-0115). - **A lane shows its GPUs.** A lane on a node that holds GPUs gets a GPU tile on its card and usage page: load, its last ten minutes, and memory @@ -25,9 +26,11 @@ and listed with their assets on the shows under Admin in the pool area now ("Asks to run lanes", with what it offers and a Grant button), counts in the pool's badge, is marked in Machines, and an admin's hub notifies the desktop when one starts asking - (`machine_asks`, on by default). A second member entry of the same machine - (the same address, or a name such as `-wsl`) is pointed out - (ADR-0116, #599). + (`machine_asks`, on by default; at most once in half an hour per + machine). Another member entry with the same address, or a similar name + such as `-wsl`, is pointed out with its id (a name is not checked). + A machine's name keeps no invisible characters (bidi overrides, + zero-width marks) (ADR-0116, #599). ### Fixed @@ -63,8 +66,12 @@ and listed with their assets on the keep their connections to a service (#556, #559). A service that ties its login to the connection (Windows Negotiate or NTLM, Kestrel's and HTTP.sys's default) took the next visitor's request on such a connection - as the first visitor's. A connection whose request or answer carries - Negotiate or NTLM is closed after its answer now, as YARP does (#569). + as the first visitor's. A connection whose request or answer carries a + Windows login (Negotiate, NTLM, Kerberos, CredSSP) now stays with the + visitor's connection, for the handshake and what follows, and is never + given to anyone else, as YARP does; it closes with the visitor's + connection. A visitor's `Proxy-Authorization` no longer reaches the + service (#569). ## [0.51.0] - 2026-11-19 diff --git a/crates/devstack-daemon/src/proxy.rs b/crates/devstack-daemon/src/proxy.rs index 5c4ae1c6..3ecee584 100644 --- a/crates/devstack-daemon/src/proxy.rs +++ b/crates/devstack-daemon/src/proxy.rs @@ -18,7 +18,7 @@ //! request), and hop-by-hop headers stay on their hop (RFC 9110 §7.6.1). use bytes::Bytes; -use devstack_node::connpool::Pool; +use devstack_node::connpool::{Bound, Pool}; use http_body_util::{BodyExt, Full, StreamBody, combinators::BoxBody}; use hyper::body::{Frame, Incoming}; use hyper::{Request, Response, StatusCode}; @@ -158,8 +158,12 @@ impl Proxy { continue; }; let sh = sh.clone(); + // The upstream connection a login binds to this client's (#569). + let client = Arc::new(Bound::default()); tokio::spawn(async move { - let service = hyper::service::service_fn(move |r| handle(sh.clone(), r)); + let service = hyper::service::service_fn(move |r| { + handle(sh.clone(), client.clone(), r) + }); let _ = hyper::server::conn::http1::Builder::new() .serve_connection(TokioIo::new(stream), service) .with_upgrades() @@ -312,9 +316,13 @@ pub fn strip_hop_by_hop(h: &mut hyper::HeaderMap, upgrade: bool) { h.remove(n); } } + // The proxy login headers are this hop's too: a visitor's never reaches + // the service (review before 0.52.0). for n in [ "keep-alive", "proxy-connection", + "proxy-authenticate", + "proxy-authorization", "te", "trailer", "transfer-encoding", @@ -355,7 +363,11 @@ async fn connect(port: u16) -> std::io::Result { Ok(s) } -async fn handle(sh: Arc, mut req: Request) -> Result, Infallible> { +async fn handle( + sh: Arc, + client: Arc>, + mut req: Request, +) -> Result, Infallible> { let up = match wait_upstream(&sh).await { Ok(u) => u, Err((state, reason)) => { @@ -387,7 +399,9 @@ async fn handle(sh: Arc, mut req: Request) -> Result r, @@ -517,7 +531,17 @@ mod tests { /// One request on a kept-alive connection; returns (status, headers, body). fn get(conn: &mut std::net::TcpStream, path: &str) -> (u16, String, String) { - write!(conn, "GET {path} HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); + get_as(conn, path, None) + } + + /// The same, with an `Authorization` header. + fn get_as( + conn: &mut std::net::TcpStream, + path: &str, + auth: Option<&str>, + ) -> (u16, String, String) { + let auth = auth.map_or(String::new(), |a| format!("Authorization: {a}\r\n")); + write!(conn, "GET {path} HTTP/1.1\r\nHost: x\r\n{auth}\r\n").unwrap(); let mut r = BufReader::new(conn.try_clone().unwrap()); let mut head = String::new(); loop { @@ -586,6 +610,90 @@ mod tests { ); } + /// An upstream that logs a connection in as Kestrel does with NTLM: + /// `NTLM t1` gets the challenge `NTLM t2`, `NTLM t3` on the same + /// connection after it logs the connection in, and a logged-in + /// connection answers 200 without credentials; anything else is 401. + fn ntlm_upstream(rt: &tokio::runtime::Runtime) -> u16 { + use std::sync::atomic::AtomicU8; + let l = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = l.local_addr().unwrap().port(); + l.set_nonblocking(true).unwrap(); + rt.spawn(async move { + let l = tokio::net::TcpListener::from_std(l).unwrap(); + loop { + let (s, _) = l.accept().await.unwrap(); + let login = Arc::new(AtomicU8::new(0)); + tokio::spawn(async move { + let svc = hyper::service::service_fn(move |r: Request| { + let login = login.clone(); + async move { + let auth = r + .headers() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string(); + let (status, challenge) = match auth.as_str() { + "NTLM t1" => { + login.store(1, Ordering::SeqCst); + (401, Some("NTLM t2")) + } + "NTLM t3" if login.load(Ordering::SeqCst) == 1 => { + login.store(2, Ordering::SeqCst); + (200, None) + } + "" if login.load(Ordering::SeqCst) == 2 => (200, None), + _ => (401, Some("NTLM")), + }; + let mut resp = Response::new(Full::new(Bytes::from("ok")).boxed()); + *resp.status_mut() = StatusCode::from_u16(status).unwrap(); + if let Some(c) = challenge { + resp.headers_mut() + .insert("www-authenticate", c.parse().unwrap()); + } + Ok::<_, Infallible>(resp) + } + }); + let _ = hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(s), svc) + .await; + }); + } + }); + port + } + + /// #569 and the review before 0.52.0, through the proxy: a client + /// connection logs in over its handshake and stays logged in; another + /// client connection is not. + #[test] + fn a_windows_login_through_the_proxy_stays_with_its_client() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let up = ntlm_upstream(&rt); + let port = free_port(); + let p = Proxy::bind("api", port, rt.handle()).unwrap(); + p.set_upstream(Some(Upstream { + port: up, + build: None, + })); + let mut anna = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + assert_eq!(get_as(&mut anna, "/", Some("NTLM t1")).0, 401); + assert_eq!( + get_as(&mut anna, "/", Some("NTLM t3")).0, + 200, + "the handshake did not stay on one connection" + ); + assert_eq!( + get(&mut anna, "/").0, + 200, + "anna's connection is not logged in" + ); + let mut ben = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + assert_eq!(get(&mut ben, "/").0, 401, "ben got anna's login"); + assert_eq!(get(&mut anna, "/").0, 200); + } + #[test] fn hop_by_hop_headers_stay_on_their_hop() { let mut h = hyper::HeaderMap::new(); diff --git a/crates/devstack-daemon/src/staticsrv.rs b/crates/devstack-daemon/src/staticsrv.rs index 2c8caf45..89d74d3b 100644 --- a/crates/devstack-daemon/src/staticsrv.rs +++ b/crates/devstack-daemon/src/staticsrv.rs @@ -91,7 +91,38 @@ fn percent_decode(s: &str) -> String { String::from_utf8_lossy(&out).into_owned() } -use devstack_node::connpool::{GiveBack, IDLE_MAX, Pool}; +use devstack_node::connpool::{Bound, GiveBack, IDLE_MAX, Pool}; + +/// One client connection: where it comes from, and the connection to each +/// forward's target a login bound to it (#569). axum makes one per +/// connection it accepts and hands a copy to each of its requests. +#[derive(Clone)] +struct Client { + peer: SocketAddr, + bound: Arc>, +} + +/// A client connection's bindings, by the port of the forward's target. +type Bindings = std::collections::HashMap>>; + +impl Client { + /// Its binding to the target on `port` (one per forward). + fn to(&self, port: u16) -> Arc> { + self.bound.lock().unwrap().entry(port).or_default().clone() + } +} + +impl + axum::extract::connect_info::Connected> + for Client +{ + fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::TcpListener>) -> Self { + Client { + peer: *stream.remote_addr(), + bound: Arc::default(), + } + } +} /// Where a forward sends its requests: `http://host:port`, with the /// connections to it that are idle now. They are reused, as a reverse proxy @@ -156,7 +187,7 @@ pub fn serve(root: PathBuf, port: u16, spa: bool, forward: &[String]) -> Result< .map_err(|e| format!("port {port}: {e}"))?; axum::serve( listener, - app(root, spa, forwards).into_make_service_with_connect_info::(), + app(root, spa, forwards).into_make_service_with_connect_info::(), ) .await .map_err(|e| e.to_string()) @@ -166,13 +197,13 @@ pub fn serve(root: PathBuf, port: u16, spa: bool, forward: &[String]) -> Result< fn app(root: PathBuf, spa: bool, forwards: Vec<(String, Target)>) -> axum::Router { let forwards = Arc::new(forwards); axum::Router::new().fallback( - move |ConnectInfo(peer): ConnectInfo, req: Request| { + move |ConnectInfo(client): ConnectInfo, req: Request| { let root = root.clone(); let forwards = forwards.clone(); async move { // A forwarded prefix never falls back to a file. if let Some((_, to)) = devstack_config::forward::pick(&forwards, req.uri().path()) { - return pass(to, peer, req).await; + return pass(to, &client, req).await; } let tag = req .headers() @@ -191,7 +222,8 @@ fn app(root: PathBuf, spa: bool, forwards: Vec<(String, Target)>) -> axum::Route /// their hop, the answer streamed (SSE, a download) and an upgrade /// (WebSocket) joined. An unreachable target is a 502 at once: nothing here /// knows whether it is starting. -async fn pass(to: &Target, peer: SocketAddr, mut req: Request) -> Response { +async fn pass(to: &Target, client: &Client, mut req: Request) -> Response { + let peer = client.peer; let fail = |e: String| { Response::builder() .status(StatusCode::BAD_GATEWAY) @@ -238,7 +270,8 @@ async fn pass(to: &Target, peer: SocketAddr, mut req: Request) -> Response *req.uri_mut() = path.parse().unwrap_or_else(|_| Uri::from_static("/")); *req.version_mut() = Version::HTTP_11; - let (sender, mut resp) = match to.pool.send(&(), req, || to.connect()).await { + let bound = client.to(to.port); + let (sender, mut resp) = match to.pool.send(&(), &bound, req, || to.connect()).await { Ok(r) => r, Err(e) => return fail(e), }; @@ -454,7 +487,7 @@ mod tests { let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = l.local_addr().unwrap().port(); tokio::spawn(async move { - axum::serve(l, app.into_make_service_with_connect_info::()).await + axum::serve(l, app.into_make_service_with_connect_info::()).await }); port } diff --git a/crates/devstack-daemon/src/watch.rs b/crates/devstack-daemon/src/watch.rs index 6a3ec78e..7ef4a281 100644 --- a/crates/devstack-daemon/src/watch.rs +++ b/crates/devstack-daemon/src/watch.rs @@ -247,6 +247,8 @@ const RELIST_AFTER: std::time::Duration = std::time::Duration::from_millis(200); /// directory is listed again [`RELIST_AFTER`] later, on a thread of its own /// that ends with the watcher; what it finds again is delivered again, /// which costs nothing (a candidate or a restart waits for its debounce). +/// The directories that came while it waited are listed with it, each once +/// (a burst of new directories is one more listing, not one per event). fn feed(repo: PathBuf, deliver: Deliver) -> impl FnMut(notify::Event) + Send + 'static { let (tx, rx) = std::sync::mpsc::channel::<(Instant, Vec)>(); if LIST_NEW_DIRS { @@ -254,8 +256,17 @@ fn feed(repo: PathBuf, deliver: Deliver) -> impl FnMut(notify::Event) + Send + ' let _ = std::thread::Builder::new() .name("watch-relist".into()) .spawn(move || { - while let Ok((due, dirs)) = rx.recv() { + while let Ok((mut due, mut dirs)) = rx.recv() { std::thread::sleep(due.saturating_duration_since(Instant::now())); + // What came meanwhile, its own wait included (each one + // only once its directory's watch is surely in place). + while let Ok((d, more)) = rx.try_recv() { + due = due.max(d); + dirs.extend(more); + } + std::thread::sleep(due.saturating_duration_since(Instant::now())); + dirs.sort(); + dirs.dedup(); let ev = dirs.into_iter().fold( notify::Event::new(EventKind::Create(notify::event::CreateKind::Folder)), notify::Event::add_path, diff --git a/crates/devstack-hub/src/asks.rs b/crates/devstack-hub/src/asks.rs index 0ef8052c..5b81113d 100644 --- a/crates/devstack-hub/src/asks.rs +++ b/crates/devstack-hub/src/asks.rs @@ -8,8 +8,14 @@ use devstack_node::coordinator::{MemberView, NodeView}; use devstack_node::store::{Role, State}; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// A machine that asks again within this time after it was told is not +/// told again: switching sharing on and off, or going on- and offline, +/// would otherwise notify every admin each time (review before 0.52.0). +const TELL_AGAIN_AFTER: Duration = Duration::from_secs(30 * 60); #[derive(Debug, Clone, PartialEq)] pub struct Ask { @@ -22,9 +28,11 @@ pub struct Ask { type Started = Box; struct Asks { - /// Per pool, the machines already told (or asking when the hub first - /// read the pool). + /// Per pool, the machines asking now, told or there when the hub first + /// read the pool as its admin. told: Mutex>>, + /// When each machine (`pool`, member) was told last. + last: Mutex>, started: OnceLock, } @@ -32,6 +40,7 @@ fn asks() -> &'static Asks { static ASKS: OnceLock = OnceLock::new(); ASKS.get_or_init(|| Asks { told: Mutex::new(BTreeMap::new()), + last: Mutex::new(HashMap::new()), started: OnceLock::new(), }) } @@ -41,19 +50,21 @@ pub fn on_started(f: impl Fn(&Ask) + Send + Sync + 'static) { let _ = asks().started.set(Box::new(f)); } -/// The machines of `pool` that ask, as the member `me` sees them: none -/// unless `me` is an admin there. A machine asks while its agent reports -/// sharing, online, and the member has no grant to run lanes. -pub fn of(pool: &str, me: &str, members: &[MemberView], nodes: &[NodeView]) -> Vec { +/// The machines of `pool` that ask, as the member `me` sees them; `None` +/// unless `me` is an admin there (no baseline then: what asks when it +/// becomes one is its baseline, not a burst of notices). A machine asks +/// while its agent reports sharing, online, and the member has no grant to +/// run lanes; `me` itself is never told about. +pub fn of(pool: &str, me: &str, members: &[MemberView], nodes: &[NodeView]) -> Option> { let admin = members .iter() .any(|m| m.id == me && m.role == Role::Admin && m.state == State::Approved); if !admin { - return Vec::new(); + return None; } - members + let asking = members .iter() - .filter(|m| m.state == State::Approved && !m.node) + .filter(|m| m.id != me && m.state == State::Approved && !m.node) .filter(|m| { nodes .iter() @@ -64,13 +75,20 @@ pub fn of(pool: &str, me: &str, members: &[MemberView], nodes: &[NodeView]) -> V id: m.id.clone(), name: m.name.clone(), }) - .collect() + .collect(); + Some(asking) } /// The machines of `pool` that ask, as just read (`None`: it could not be -/// asked, nothing changes). A pool's first reading is its baseline: what -/// asked then is not told; a machine that stops asking and asks again is. +/// asked, or this machine is no admin there; nothing changes). A pool's +/// first reading is its baseline: what asked then is not told; a machine +/// that stops asking and asks again is, unless it was told within +/// [`TELL_AGAIN_AFTER`]. pub fn seen(pool: &str, now: Option>) { + seen_at(pool, now, Instant::now()); +} + +fn seen_at(pool: &str, now: Option>, at: Instant) { let a = asks(); let Some(list) = now else { return }; let fresh: Vec = { @@ -85,8 +103,19 @@ pub fn seen(pool: &str, now: Option>) { } Some(set) => { set.retain(|id| list.iter().any(|x| &x.id == id)); + let mut last = a.last.lock().unwrap(); list.iter() .filter(|x| set.insert(x.id.clone())) + .filter(|x| { + let key = (pool.to_string(), x.id.clone()); + let due = last + .get(&key) + .is_none_or(|t| at.saturating_duration_since(*t) >= TELL_AGAIN_AFTER); + if due { + last.insert(key, at); + } + due + }) .cloned() .collect() } @@ -134,14 +163,19 @@ mod tests { node("carl", true, false), // not sharing node("dora", false, true), // offline ]; - let a = of("default", "me", &members, &nodes); + let a = of("default", "me", &members, &nodes).unwrap(); assert_eq!( a.iter().map(|x| x.id.as_str()).collect::>(), ["anna"] ); assert_eq!(a[0].name, "ANNA"); - // A member who is no admin is told nothing. - assert!(of("default", "anna", &members, &nodes).is_empty()); + // A member who is no admin has no reading at all (no baseline). + assert!(of("default", "anna", &members, &nodes).is_none()); + // An admin's own machine that asks is not told about. + let mut mine = members.to_vec(); + mine.push(member("boss", "admin", false)); + let nodes2 = [node("boss", true, true)]; + assert!(of("default", "boss", &mine, &nodes2).unwrap().is_empty()); } #[test] @@ -153,14 +187,24 @@ mod tests { id: id.into(), name: id.into(), }; - seen("t", Some(vec![ask("anna")])); + let t0 = Instant::now(); + let at = |m: u64| t0 + Duration::from_secs(m * 60); + seen_at("t", Some(vec![ask("anna")]), at(0)); assert!(TOLD.lock().unwrap().is_empty(), "the baseline is not told"); - seen("t", Some(vec![ask("anna"), ask("ben")])); - seen("t", Some(vec![ask("anna"), ask("ben")])); - seen("t", None); - // Granted (or switched off), then asking again: told again. - seen("t", Some(vec![ask("ben")])); - seen("t", Some(vec![ask("anna"), ask("ben")])); - assert_eq!(*TOLD.lock().unwrap(), ["ben", "anna"]); + seen_at("t", Some(vec![ask("anna"), ask("ben")]), at(1)); + seen_at("t", Some(vec![ask("anna"), ask("ben")]), at(2)); + seen_at("t", None, at(3)); + // Switched off and on again soon after: not told again. + seen_at("t", Some(vec![ask("anna")]), at(4)); + seen_at("t", Some(vec![ask("anna"), ask("ben")]), at(5)); + assert_eq!(*TOLD.lock().unwrap(), ["ben"]); + // Granted (or switched off), then asking again much later: told again. + seen_at("t", Some(vec![ask("anna")]), at(40)); + seen_at("t", Some(vec![ask("anna"), ask("ben")]), at(41)); + assert_eq!(*TOLD.lock().unwrap(), ["ben", "ben"]); + // anna was part of the baseline: told once she asks anew. + seen_at("t", Some(vec![ask("ben")]), at(42)); + seen_at("t", Some(vec![ask("anna"), ask("ben")]), at(43)); + assert_eq!(*TOLD.lock().unwrap(), ["ben", "ben", "anna"]); } } diff --git a/crates/devstack-hub/src/nodehost.rs b/crates/devstack-hub/src/nodehost.rs index 9b6b34ef..0d56f43a 100644 --- a/crates/devstack-hub/src/nodehost.rs +++ b/crates/devstack-hub/src/nodehost.rs @@ -287,9 +287,11 @@ pub fn agent_args( format!("{:.2}", m as f64 / f64::from(1u32 << 30)), ]); } - // Only when set: an agent of an earlier release in the distribution - // does not know it. - if let Some(g) = sw.max_gpus { + // Only when set, and only for an agent that takes new lanes: one of an + // earlier release in the distribution does not know it, and an agent + // that only lets the running lanes finish (whose release is not checked + // first) has no use for it (review before 0.52.0). + if let Some(g) = sw.max_gpus.filter(|_| new_lanes) { a.extend(["--max-gpus".into(), g.to_string()]); } if !new_lanes { @@ -1510,8 +1512,12 @@ mod tests { 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 --max-gpus 0 --no-new-lanes" + "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" ); + // The GPU cap goes to an agent that takes new lanes only: one that + // lets running lanes finish may be of an earlier release. + let taking = agent_args("default", &sw, "https://x:4261", None, true).join(" "); + assert!(taking.contains("--max-gpus 0"), "{taking}"); // Not set: not passed, for an agent that does not know it. assert!( !agent_args("default", &Switch::default(), "https://x:4261", None, true) diff --git a/crates/devstack-hub/src/share.rs b/crates/devstack-hub/src/share.rs index 8d8d8aaa..3627578d 100644 --- a/crates/devstack-hub/src/share.rs +++ b/crates/devstack-hub/src/share.rs @@ -192,25 +192,26 @@ pub(crate) fn guests(pool: &str) -> Option> { Some(crate::guests::of(pool, &m.id, &leases, &nodes)) } -/// The machines that ask an admin of `pool` to run its lanes (#599); none -/// where this machine is no admin. `None` when the coordinator could not be -/// asked. Read when the pool's stream says its members or nodes changed. +/// The machines that ask an admin of `pool` to run its lanes (#599). +/// `None` where this machine is no admin, or the coordinator could not be +/// asked: no reading then (`asks::seen`). Read when the pool's stream says +/// its members or nodes changed. pub(crate) fn asks(pool: &str) -> Option> { let local = devstack_node::member::Local::new(&dir(pool)); - let m = match local.membership() { - Ok(Some(m)) if m.state == State::Approved => m, - Ok(_) => return Some(Vec::new()), - Err(_) => return None, - }; + let m = local + .membership() + .ok() + .flatten() + .filter(|m| m.state == State::Approved)?; let members = local.members().ok()?; if !members .iter() .any(|x| x.id == m.id && x.role == devstack_node::store::Role::Admin) { - return Some(Vec::new()); + return None; } let nodes = local.nodes().ok()?; - Some(crate::asks::of(pool, &m.id, &members, &nodes)) + crate::asks::of(pool, &m.id, &members, &nodes) } /// What one round did for a pool. diff --git a/crates/devstack-node/src/connpool.rs b/crates/devstack-node/src/connpool.rs index 065e9871..81a5719b 100644 --- a/crates/devstack-node/src/connpool.rs +++ b/crates/devstack-node/src/connpool.rs @@ -133,12 +133,17 @@ where /// ([`replay`]) and the error is that close ([`closed_unanswered`]). /// A new connection is never tried twice: its failure is the upstream's. /// + /// `client` is the client connection the request came on: a connection + /// a login bound to it ([`Bound`]) takes the request first, and a + /// connection whose request or answer binds a login becomes its. + /// /// The connection comes back with the answer, to give back once that is - /// read; `None` when it must serve no other request ([`binds_connection`]). + /// read; `None` when it is bound to `client` and serves no one else. pub async fn send( &self, key: &K, - req: Request, + client: &Bound, + mut req: Request, connect: F, ) -> Result<(Option>, Response), String> where @@ -146,9 +151,32 @@ where F: FnOnce() -> Fut, Fut: std::future::Future, String>>, { + // Every later request of a client connection a login bound goes + // over that connection, credentials or not: the login is the + // connection's. Closed meanwhile, the binding ends. + if let Some(mut s) = client.take(key) + && s.ready().await.is_ok() + { + let copy = replay(&req); + match s.try_send_request(req).await { + Ok(r) => { + client.put(key.clone(), s); + return Ok((None, r)); + } + Err(e) => match again(e, copy) { + Ok(back) => req = back, + Err(e) => return Err(e.to_string()), + }, + } + } let credentials = req.headers().clone(); let reusable = |s: SendRequest, r: &Response| { - (!binds_connection(&credentials, r.headers())).then_some(s) + if binds_connection(&credentials, r.headers()) { + client.put(key.clone(), s); + None + } else { + Some(s) + } }; let req = match self.kept(key) { None => req, @@ -169,19 +197,52 @@ where } } +/// The connection to an upstream that one client connection is bound to, +/// once a login tied to the connection went over it ([`binds_connection`], +/// #569): every later request of that client connection goes over it, as +/// Windows Negotiate/NTLM needs its handshake and what follows on one +/// connection, and it never goes back to the pool, so no other client gets +/// the login. It closes with the client connection (dropping this). One per +/// client connection, which each proxy creates as it accepts one. +pub struct Bound(Mutex)>>); + +impl Default for Bound { + fn default() -> Self { + Self(Mutex::new(None)) + } +} + +impl Bound { + /// The bound connection, if it is to `key`; one to another key (the + /// upstream changed) is dropped. + fn take(&self, key: &K) -> Option> { + let (k, s) = self.0.lock().unwrap().take()?; + (k == *key).then_some(s) + } + + fn put(&self, key: K, s: SendRequest) { + *self.0.lock().unwrap() = Some((key, s)); + } + + /// Whether a connection is bound (for tests and views). + pub fn is_bound(&self) -> bool { + self.0.lock().unwrap().is_some() + } +} + /// Whether a request (`request`, its headers) or its answer (`answer`) ties -/// a login to the connection: Windows Negotiate or NTLM, which Kestrel and -/// HTTP.sys authenticate per connection. Such a connection serves no other -/// request, whoever sends it (#569), as YARP does. +/// a login to the connection: the Windows schemes (Negotiate, NTLM, +/// Kerberos, CredSSP), which Kestrel and HTTP.sys authenticate per +/// connection. Such a connection stays with its client connection +/// ([`Bound`], #569), as YARP keeps it with the client's. A challenge may +/// offer several schemes in one value (`Negotiate, NTLM`). pub fn binds_connection(request: &hyper::HeaderMap, answer: &hyper::HeaderMap) -> bool { + const SCHEMES: [&str; 4] = ["negotiate", "ntlm", "kerberos", "credssp"]; let bound = |v: &hyper::header::HeaderValue| { - let scheme = v - .to_str() - .unwrap_or("") - .split_whitespace() - .next() - .unwrap_or(""); - scheme.eq_ignore_ascii_case("negotiate") || scheme.eq_ignore_ascii_case("ntlm") + v.to_str().unwrap_or("").split(',').any(|part| { + let scheme = part.split_whitespace().next().unwrap_or(""); + SCHEMES.iter().any(|s| scheme.eq_ignore_ascii_case(s)) + }) }; request .get_all(hyper::header::AUTHORIZATION) @@ -354,9 +415,12 @@ mod tests { ClosesKept, /// Closes on every request without an answer. ClosesAll, - /// Answers a request without credentials with a Negotiate challenge - /// (401), one with them with 200, and keeps the connection open. - Challenges, + /// Windows NTLM as Kestrel does it, per connection: a request without + /// credentials gets the challenge (401 `NTLM`), `NTLM t1` the second + /// leg (401 `NTLM t2`), `NTLM t3` on the same connection after it + /// 200, and from then on the connection is logged in: a request + /// without credentials on it gets 200 too. `Basic` gets 200. + Ntlm, } /// A raw HTTP/1.1 upstream; counts the connections it accepted. @@ -373,6 +437,8 @@ mod tests { c.fetch_add(1, Ordering::SeqCst); tokio::spawn(async move { let mut served = 0; + // `Ntlm`: 0 nothing, 1 challenged (t2 sent), 2 logged in. + let mut login = 0; loop { // One request head (the tests' bodies are tiny). let mut head = Vec::new(); @@ -386,20 +452,32 @@ mod tests { let close = match mode { Upstream::ClosesKept => served > 0, Upstream::ClosesAll => true, - Upstream::Challenges => false, + Upstream::Ntlm => false, }; if close { return; // dropped: closed, no answer } served += 1; - let credentials = String::from_utf8_lossy(&head) - .to_ascii_lowercase() - .contains("\r\nauthorization:"); - let answer: &[u8] = if matches!(mode, Upstream::Challenges) && !credentials - { - b"HTTP/1.1 401 Unauthorized\r\nwww-authenticate: Negotiate\r\nwww-authenticate: NTLM\r\ncontent-length: 0\r\n\r\n" - } else { - b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok" + let head = String::from_utf8_lossy(&head).to_ascii_lowercase(); + const OK: &[u8] = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok"; + const CHALLENGE: &[u8] = b"HTTP/1.1 401 Unauthorized\r\nwww-authenticate: NTLM\r\ncontent-length: 0\r\n\r\n"; + let answer: &[u8] = match mode { + Upstream::Ntlm if head.contains("\r\nauthorization: ntlm t1") => { + login = 1; + b"HTTP/1.1 401 Unauthorized\r\nwww-authenticate: NTLM t2\r\ncontent-length: 0\r\n\r\n" + } + Upstream::Ntlm if head.contains("\r\nauthorization: ntlm t3") => { + if login == 1 { + login = 2; + OK + } else { + CHALLENGE + } + } + Upstream::Ntlm if head.contains("\r\nauthorization: basic") => OK, + Upstream::Ntlm if login == 2 => OK, + Upstream::Ntlm => CHALLENGE, + _ => OK, }; if s.write_all(answer).await.is_err() { return; @@ -434,7 +512,17 @@ mod tests { /// A request through `pool`, its answer read to its end; the status or /// the error the proxy would turn into a 502. async fn through(pool: &Arc>, port: u16, req: Request) -> Result { - let (sender, resp) = pool.send(&(), req, || connect(port)).await?; + through_on(pool, &Bound::default(), port, req).await + } + + /// The same, as a request of the client connection `client`. + async fn through_on( + pool: &Arc>, + client: &Bound<(), B>, + port: u16, + req: Request, + ) -> Result { + let (sender, resp) = pool.send(&(), client, req, || connect(port)).await?; let status = resp.status().as_u16(); let body = GiveBack::wrap(pool.clone(), (), sender, resp); body.into_body() @@ -508,34 +596,82 @@ mod tests { assert_eq!(conns.load(Ordering::SeqCst), 2); } - /// #569: a service that ties its login to the connection (Windows - /// Negotiate/NTLM, Kestrel's and HTTP.sys's default) takes the next - /// request on it as the first visitor's. Neither the challenge's - /// connection nor the one that carried the credentials goes back. + fn with_auth(value: &'static str) -> Request { + let mut r = request("GET", ""); + r.headers_mut() + .insert("authorization", value.parse().unwrap()); + r + } + + /// #569 and the review before 0.52.0: a service that ties its login to + /// the connection (Windows NTLM, Kestrel's and HTTP.sys's default) + /// needs the whole handshake, and what follows, on one connection, and + /// must never take another client's request on it as the first one's. #[tokio::test] - async fn a_connection_bound_login_is_never_given_to_another_request() { - let (port, conns) = upstream(Upstream::Challenges).await; + async fn a_connection_bound_login_stays_with_its_client_and_no_other() { + let (port, conns) = upstream(Upstream::Ntlm).await; let pool = Pool::new(IDLE_MAX); - // The challenge: `WWW-Authenticate: Negotiate`. - assert_eq!(through(&pool, port, request("GET", "")).await, Ok(401)); - // The credentials, on whatever connection. - let mut auth = request("GET", ""); - auth.headers_mut() - .insert("authorization", "NTLM TlRMTVNTUAAB".parse().unwrap()); - assert_eq!(through(&pool, port, auth).await, Ok(200)); + let anna = Bound::default(); + // The challenge, then the handshake's three legs, then a request + // without credentials on the logged-in connection. + assert_eq!( + through_on(&pool, &anna, port, request("GET", "")).await, + Ok(401) + ); + assert_eq!( + through_on(&pool, &anna, port, with_auth("NTLM t1")).await, + Ok(401) + ); + assert_eq!( + through_on(&pool, &anna, port, with_auth("NTLM t3")).await, + Ok(200), + "the handshake went over two connections" + ); + assert_eq!( + through_on(&pool, &anna, port, request("GET", "")).await, + Ok(200) + ); + assert!(anna.is_bound()); tokio::time::sleep(Duration::from_millis(100)).await; + // Another client never gets anna's connection. assert_eq!( pool.idle(&()), 0, "a connection with a bound login was kept" ); - assert_eq!(conns.load(Ordering::SeqCst), 2); + let ben = Bound::default(); + assert_eq!( + through_on(&pool, &ben, port, request("GET", "")).await, + Ok(401), + "ben got anna's login" + ); // Any other answer keeps its connection, as before. - let mut basic = request("GET", ""); - basic - .headers_mut() - .insert("authorization", "Basic dTpw".parse().unwrap()); - assert_eq!(through(&pool, port, basic).await, Ok(200)); + let before = conns.load(Ordering::SeqCst); + assert_eq!(through(&pool, port, with_auth("Basic dTpw")).await, Ok(200)); kept_again(&pool).await; + assert!(conns.load(Ordering::SeqCst) <= before + 1); + } + + #[test] + fn the_windows_schemes_bind_a_connection_however_they_are_written() { + let h = |name: &'static str, v: &'static str| { + let mut m = hyper::HeaderMap::new(); + m.append(name, v.parse().unwrap()); + m + }; + let none = hyper::HeaderMap::new(); + for v in [ + "Negotiate, NTLM", + "Basic realm=\"x\", NTLM", + "kerberos", + "CredSSP abc", + ] { + assert!(binds_connection(&none, &h("www-authenticate", v)), "{v}"); + } + assert!(binds_connection(&h("authorization", "ntlm TlRM"), &none)); + assert!(!binds_connection( + &h("authorization", "Bearer x"), + &h("www-authenticate", "Basic realm=\"ntlm\"") + )); } } diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index b16d8a85..865a05ab 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -1457,12 +1457,7 @@ async fn join( "too many requests wait for an admin already".into(), )); } - let name: String = r - .name - .chars() - .filter(|c| !c.is_control()) - .take(64) - .collect(); + let name = member_name(&r.name); let m = s .store .request(&id, name.trim(), &r.csr, Some(&peer.addr.ip().to_string())) @@ -1470,6 +1465,18 @@ async fn join( Ok(Json(answer(&m))) } +/// The name a machine gives itself as the pool keeps it: no control +/// characters, and none that change how a name looks without being seen +/// (bidi overrides, zero-width marks; review before 0.52.0: a name could +/// pass for another one in an admin's list); at most 64 characters. +fn member_name(raw: &str) -> String { + let invisible = |c: char| matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{206F}' | '\u{FEFF}'); + raw.chars() + .filter(|&c| !c.is_control() && !invisible(c)) + .take(64) + .collect() +} + /// A few joins (and enrolments) a minute per address. fn throttle(s: &Inner, peer: &Peer) -> ApiResult<()> { let mut joins = s.joins.lock().unwrap(); @@ -3406,12 +3413,7 @@ async fn enrol( if m.state != MachineState::Provisioning || store::now() > m.deadline { return Err((StatusCode::FORBIDDEN, "this enrolment has expired".into())); } - let name: String = r - .name - .chars() - .filter(|c| !c.is_control()) - .take(64) - .collect(); + let name = member_name(&r.name); let ca = ca(&s.dir).map_err(internal)?; let joined = s .store @@ -4477,6 +4479,16 @@ mod placement_tests { assert!(order(&[("d", "roomy", &roomy)], need)[0].1); } + #[test] + fn a_member_name_keeps_no_hidden_characters() { + // A name that would read "anna-wsl" right to left, and one with a + // zero-width space, as an admin would see them. + assert_eq!(member_name("lsw-\u{202E}anna"), "lsw-anna"); + assert_eq!(member_name("an\u{200B}na\tbox\u{FEFF}"), "annabox"); + assert_eq!(member_name("Büro-PC (Anna)"), "Büro-PC (Anna)"); + assert_eq!(member_name(&"x".repeat(80)).len(), 64); + } + #[test] fn gpus_asked_for_are_gpus_offered() { let need = Need { diff --git a/crates/devstack-node/src/linkrouter.rs b/crates/devstack-node/src/linkrouter.rs index 3ac001d3..5ded9ddf 100644 --- a/crates/devstack-node/src/linkrouter.rs +++ b/crates/devstack-node/src/linkrouter.rs @@ -58,6 +58,8 @@ pub type Dial = Arc Result + Send + Sync>; /// Idle connections to services, by [`Way::key`]. type Kept = Arc>; +/// One visitor connection's service connection, once a login bound it. +type Client = Arc>; // ------------------------------------------------------- the connector @@ -251,9 +253,12 @@ pub async fn serve(listener: tokio::net::TcpListener, dial: Dial) { let _ = stream.set_nodelay(true); let dial = dial.clone(); let kept = kept.clone(); + // The service connection a login binds to this visitor's (#569). + let client: Client = Arc::new(crate::connpool::Bound::default()); tokio::spawn(async move { - let service = - hyper::service::service_fn(move |r| handle(dial.clone(), kept.clone(), r)); + let service = hyper::service::service_fn(move |r| { + handle(dial.clone(), kept.clone(), client.clone(), r) + }); let _ = hyper::server::conn::http1::Builder::new() .serve_connection(TokioIo::new(stream), service) .with_upgrades() @@ -275,6 +280,7 @@ fn text(status: StatusCode, body: String) -> hyper::Response { async fn handle( dial: Dial, kept: Kept, + client: Client, req: Request, ) -> Result, std::convert::Infallible> { let host = req @@ -291,12 +297,14 @@ async fn handle( return Ok(text(status, format!("devstack: {why}\n"))); } }; - Ok(forward(req, &host, way, kept).await.unwrap_or_else(|e| { - text( - StatusCode::BAD_GATEWAY, - format!("devstack: the service does not answer: {e}\n"), - ) - })) + Ok(forward(req, &host, way, kept, &client) + .await + .unwrap_or_else(|e| { + text( + StatusCode::BAD_GATEWAY, + format!("devstack: the service does not answer: {e}\n"), + ) + })) } /// The way to `port` on this machine's loopback (IPv4, else IPv6: a dev @@ -354,6 +362,7 @@ async fn forward( host: &str, way: Way, kept: Kept, + client: &Client, ) -> Result, String> { let port = way.port; let client_upgrade = req @@ -378,7 +387,7 @@ async fn forward( // goes out once more on a new one where that is safe (`connpool`). let Way { key, tls, open, .. } = way; let (sender, mut resp) = kept - .send(&key, req.map(BodyExt::boxed), || connect(open, tls)) + .send(&key, client, req.map(BodyExt::boxed), || connect(open, tls)) .await?; let upgraded = resp.status() == StatusCode::SWITCHING_PROTOCOLS && client_upgrade.is_some(); strip_hop_by_hop(resp.headers_mut(), upgraded); @@ -415,9 +424,13 @@ fn strip_hop_by_hop(h: &mut hyper::HeaderMap, upgrade: bool) { h.remove(n); } } + // The proxy login headers are this hop's too: a visitor's never reaches + // the service (review before 0.52.0). for n in [ "keep-alive", "proxy-connection", + "proxy-authenticate", + "proxy-authorization", "te", "trailer", "transfer-encoding", diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index 546fce31..f118f86c 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -160,7 +160,7 @@ pub struct NodeLease { /// The machine's GPUs as a node reports them: one a lease holds names its /// lane (ADR-0112 point 5); what is offered of the rest says -/// [`crate::share::offered_gpus`] with the owner's cap. +/// [`crate::share::offered_gpus`] with the room the owner's cap leaves. fn held_gpus( gpus: Vec, leases: &HashMap, @@ -174,10 +174,16 @@ fn held_gpus( .find(|l| l.gpus.iter().any(|g| g == id)) .map(|l| format!("{}/{}", l.repo, l.lane)) }, - max, + gpu_room(leases, max), ) } +/// How many more GPUs the node's lanes may hold under the owner's cap: +/// what the leases hold counts, listed by the vendor's tool now or not. +fn gpu_room(leases: &HashMap, max: Option) -> usize { + crate::share::gpu_room(max, leases.values().map(|l| l.gpus.len()).sum()) +} + /// What a slot keeps about itself (`slots//slot.json`). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SlotInfo { @@ -1795,7 +1801,8 @@ async fn admit( let mut leases = s.leases.lock().unwrap(); if let Some(g) = gpu_need { let offered = held_gpus(machine_gpus, &leases, s.share.max_gpus); - l.gpus = crate::share::assign_gpus(&offered, g).map_err(|fit| { + let room = gpu_room(&leases, s.share.max_gpus); + l.gpus = crate::share::assign_gpus(&offered, g, room).map_err(|fit| { err( StatusCode::CONFLICT, format!( diff --git a/crates/devstack-node/src/share.rs b/crates/devstack-node/src/share.rs index 904da2a6..7ee65670 100644 --- a/crates/devstack-node/src/share.rs +++ b/crates/devstack-node/src/share.rs @@ -222,51 +222,62 @@ impl Gpu { } } +/// How many more GPUs the node's lanes may hold: the owner's cap `max` +/// less the GPUs its leases hold (`held`, counted from the leases, not from +/// what the vendor's tool lists now); no cap: any number. +pub fn gpu_room(max: Option, held: usize) -> usize { + max.map_or(usize::MAX, |m| (m as usize).saturating_sub(held)) +} + /// The machine's GPUs as a node offers them (ADR-0112 point 5): one a lease /// holds (`holder` names its lane) is not offered, nor one in use on the -/// machine, nor one beyond `max` held and offered together; every other is. +/// machine; of the others, as many as `room` ([`gpu_room`]) leaves, the ones +/// with the most memory, so that the pool places on what fits best. The cap +/// is a number of GPUs: the admission ([`assign_gpus`]) may give any free one. pub fn offered_gpus( gpus: Vec, holder: impl Fn(&str) -> Option, - max: Option, + room: usize, ) -> Vec { let lanes: Vec> = gpus.iter().map(|g| holder(&g.id)).collect(); - let held = lanes.iter().filter(|l| l.is_some()).count() as u32; - let mut room = max.map_or(u32::MAX, |m| m.saturating_sub(held)); + let free = |i: usize| lanes[i].is_none() && !gpus[i].in_use(); + // The free ones by memory, most first (a stable sort keeps the tool's + // order among equals); the first `room` of them are offered. + let mut order: Vec = (0..gpus.len()).filter(|&i| free(i)).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(gpus[i].memory)); + let offered: std::collections::HashSet = order.into_iter().take(room).collect(); gpus.into_iter() .zip(lanes) - .map(|(g, lane)| { - let busy = lane.is_none() && g.in_use(); - let offered = lane.is_none() && !busy && room > 0; - if offered { - room -= 1; - } - Gpu { - offered, - busy, - lane, - ..g - } + .enumerate() + .map(|(i, (g, lane))| Gpu { + offered: offered.contains(&i), + busy: lane.is_none() && g.in_use(), + lane, + ..g }) .collect() } +/// How long `nvidia-smi` may take. It hangs at times (a driver fault, an +/// Xid error), and its callers report every lane's containers too (review +/// before 0.52.0); it normally answers in well under a second. +const NVIDIA_SMI_WITHIN: std::time::Duration = std::time::Duration::from_secs(5); + /// The machine's GPUs, as the vendor's tool reports them (`nvidia-smi`, on -/// Linux and Windows); none without one. +/// Linux and Windows); none without one, or when it does not answer within +/// [`NVIDIA_SMI_WITHIN`]. pub fn gpus() -> Vec { - let Ok(out) = std::process::Command::new("nvidia-smi") - .args([ - "--query-gpu=name,memory.total,memory.used,utilization.gpu,uuid", - "--format=csv,noheader,nounits", - ]) - .output() - else { - return Vec::new(); - }; - if !out.status.success() { - return Vec::new(); + let mut cmd = std::process::Command::new("nvidia-smi"); + cmd.args([ + "--query-gpu=name,memory.total,memory.used,utilization.gpu,uuid", + "--format=csv,noheader,nounits", + ]); + match devstack_compose::output_within(cmd, NVIDIA_SMI_WITHIN) { + Ok(Some(out)) if out.status.success() => { + parse_nvidia_smi(&String::from_utf8_lossy(&out.stdout)) + } + _ => Vec::new(), } - parse_nvidia_smi(&String::from_utf8_lossy(&out.stdout)) } /// `name, memory.total, memory.used, utilization.gpu, uuid` per line, MiB @@ -294,16 +305,19 @@ pub fn parse_nvidia_smi(text: &str) -> Vec { } /// The GPUs a lane that needs `need` is given (ADR-0112 point 2): the first -/// offered ones ([`offered_gpus`]) with the memory it asks for, in the -/// vendor tool's order. `Err`: how many there are, fewer than it asks for. -pub fn assign_gpus(gpus: &[Gpu], need: GpuNeed) -> Result, usize> { +/// free ones (held by no lease, not in use on the machine, as +/// [`offered_gpus`] marks them) with the memory it asks for, in the vendor +/// tool's order, as long as `room` ([`gpu_room`]) allows that many. `Err`: +/// how many it could have, fewer than it asks for. +pub fn assign_gpus(gpus: &[Gpu], need: GpuNeed, room: usize) -> Result, usize> { let fit: Vec = gpus .iter() - .filter(|g| g.offered && !g.id.is_empty() && g.memory >= need.memory) + .filter(|g| g.lane.is_none() && !g.busy && !g.id.is_empty() && g.memory >= need.memory) .map(|g| g.id.clone()) .collect(); - if (fit.len() as u32) < need.count { - return Err(fit.len()); + let can = fit.len().min(room); + if can < need.count as usize { + return Err(can); } Ok(fit.into_iter().take(need.count as usize).collect()) } @@ -359,33 +373,33 @@ mod tests { count, memory: gib * GIB, }; - let offer = |held: &[&str], max| { - let held: Vec = held.iter().map(|h| h.to_string()).collect(); - offered_gpus( + // `held`: the GPUs the leases hold, `max` the owner's cap. + let assign = |held: &[&str], max: Option, n: GpuNeed| { + let ids: Vec = held.iter().map(|h| h.to_string()).collect(); + let room = gpu_room(max, held.len()); + let view = offered_gpus( gpus.to_vec(), - |id| held.iter().any(|h| h == id).then(|| "shop/x".into()), - max, - ) + |id| ids.iter().any(|h| h == id).then(|| "shop/x".into()), + room, + ); + assign_gpus(&view, n, room) }; - assert_eq!( - assign_gpus(&offer(&[], None), need(1, 0)), - Ok(vec!["a".into()]) - ); - assert_eq!( - assign_gpus(&offer(&[], None), need(1, 16)), - Ok(vec!["b".into()]) - ); - assert_eq!( - assign_gpus(&offer(&["b"], None), need(1, 16)), - Ok(vec!["c".into()]) - ); - assert_eq!(assign_gpus(&offer(&["b"], None), need(2, 16)), Err(1)); + assert_eq!(assign(&[], None, need(1, 0)), Ok(vec!["a".into()])); + assert_eq!(assign(&[], None, need(1, 16)), Ok(vec!["b".into()])); + assert_eq!(assign(&["b"], None, need(1, 16)), Ok(vec!["c".into()])); + assert_eq!(assign(&["b"], None, need(2, 16)), Err(1)); // The owner's cap counts what lanes hold already. - assert_eq!(assign_gpus(&offer(&["b"], Some(1)), need(1, 0)), Err(0)); - assert_eq!(assign_gpus(&offer(&[], Some(0)), need(1, 0)), Err(0)); + assert_eq!(assign(&["b"], Some(1), need(1, 0)), Err(0)); + assert_eq!(assign(&[], Some(0), need(1, 0)), Err(0)); + // The cap is a number of GPUs: a lane gets one that fits, not the + // first one (review before 0.52.0). + assert_eq!(assign(&[], Some(1), need(1, 16)), Ok(vec!["b".into()])); + // What a lease holds counts even when the tool does not list it now + // (a GPU off the bus): no GPU beyond the cap. + assert_eq!(assign(&["gone"], Some(1), need(1, 0)), Err(0)); // A GPU whose id the tool did not say cannot be given to a container. - let unnamed = offered_gpus(vec![gpu("", 24)], |_| None, None); - assert_eq!(assign_gpus(&unnamed, need(1, 0)), Err(0)); + let unnamed = offered_gpus(vec![gpu("", 24)], |_| None, usize::MAX); + assert_eq!(assign_gpus(&unnamed, need(1, 0), usize::MAX), Err(0)); } #[test] @@ -402,7 +416,7 @@ mod tests { let all = offered_gpus( gpus.clone(), |id| (id == "d").then(|| "shop/x".into()), - None, + usize::MAX, ); let state: Vec<(bool, bool, bool)> = all .iter() @@ -417,16 +431,28 @@ mod tests { (false, false, true) ] ); - // At most two: `d`, held, and the first free one. - let capped = offered_gpus(gpus, |id| (id == "d").then(|| "shop/x".into()), Some(2)); - let offered: Vec<&str> = capped + // At most two: `d`, held, and one free one. + let capped = offered_gpus( + gpus, + |id| (id == "d").then(|| "shop/x".into()), + gpu_room(Some(2), 1), + ); + assert_eq!(capped.iter().filter(|g| g.offered).count(), 1); + // With room for fewer than are free, the largest are offered. + let sized = |id: &str, gib: u64| Gpu { + id: id.into(), + memory: gib * GIB, + ..Gpu::default() + }; + let mixed = offered_gpus(vec![sized("s", 8), sized("l", 24)], |_| None, 1); + let offered: Vec<&str> = mixed .iter() .filter(|g| g.offered) .map(|g| g.id.as_str()) .collect(); - assert_eq!(offered, ["a"]); + assert_eq!(offered, ["l"]); // A GPU a lane holds is never busy, whatever it uses. - let held = offered_gpus(vec![gpu("a", 15)], |_| Some("shop/x".into()), None); + let held = offered_gpus(vec![gpu("a", 15)], |_| Some("shop/x".into()), usize::MAX); assert!(!held[0].busy && !held[0].offered); } diff --git a/docs/adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md b/docs/adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md index c87e93f5..4b023d99 100644 --- a/docs/adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md +++ b/docs/adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md @@ -31,18 +31,28 @@ As built: 1. **The offer** (`share::offered_gpus`, `node.rs` `held_gpus`): a GPU a lease holds names its lane; of the others, one with more than a quarter of its memory used (`IN_USE`) is `busy` and not offered, and of the rest - only as many are offered as `max_gpus` leaves beside the held ones, in - the vendor tool's order. The admission assigns from this view - (`assign_gpus` takes offered GPUs only), so the cap and a busy GPU hold - there too, and the coordinator, which counts offered GPUs only, places - by it without a change. + only as many are offered as the cap leaves (`gpu_room`: `max_gpus` less + the GPUs the leases hold, counted from the leases, not from what + `nvidia-smi` lists now), the ones with the most memory first. The + coordinator, which counts offered GPUs only, places by it without a + change. The cap is a number of GPUs: the admission (`assign_gpus`) gives + any free GPU that is not busy and has the memory asked for, as long as + the room allows (amended after the reviews before 0.52.0: the first + build offered and gave the first GPUs in the tool's order, so a lane + that needed the second, larger one was refused, and a GPU missing from + the tool's list did not count against the cap). 2. **The cap:** `share::Settings::max_gpus`, the agent's `--max-gpus`, the switch's `max_gpus` in `node-host.json` (`PUT /hub/pool/share`). The hub - passes `--max-gpus` only when it is set, so an agent of an earlier - release in a WSL distribution starts as before. The dashboard's switch - and setup dialog show a "GPU cap" where the machine has a GPU. + passes `--max-gpus` only when it is set and the agent takes new lanes, + so an agent of an earlier release in a WSL distribution starts as + before, also one that only lets running lanes finish. The dashboard's + switch and setup dialog show a "GPU cap" where the machine has a GPU, + and say when what is typed is no whole number instead of saving it as + no cap. 3. **A lane's GPUs** (`laneinfra::refresh`, `node.rs` `lane-infra` thread): - once a round, where a lease holds GPUs, the node asks `nvidia-smi` and + once a round, where a lease holds GPUs, the node asks `nvidia-smi` (at + most 5 s: it hangs at times, and the same thread reports every lane's + containers) and writes the lease's GPUs (name, memory, used, load; no id) into the lane's file beside its containers' load. The lane's daemon (`usage.rs` `sample_external`) keeps them as a series of its own and reports them as diff --git a/docs/adr/0116-admins-see-a-machine-that-asks-to-run-lanes.md b/docs/adr/0116-admins-see-a-machine-that-asks-to-run-lanes.md index d9aafd80..72e8436b 100644 --- a/docs/adr/0116-admins-see-a-machine-that-asks-to-run-lanes.md +++ b/docs/adr/0116-admins-see-a-machine-that-asks-to-run-lanes.md @@ -42,17 +42,29 @@ As built: The offer is the report's CPU, memory and GPUs (`sharedText`). 3. **Badges and Machines** (`stores/pool.ts` `due`, `PoolMachines.vue`): asking machines add to `admin`, which the pool tab and the sidebar's - "Pools" count; the row's Role column shows "asks to run lanes" (warn) - where "runs lanes" would stand. + "Pools" count; for an admin, the row's Role column shows "asks to run + lanes" (warn) where "runs lanes" would stand. 4. **The notification** (`asks.rs`, `share::asks`, `poolfeed.rs`, `notify` `machine_asks`): read when the pool's stream says its members - or nodes changed, as the guest lanes are; a pool's first reading is the - baseline; a machine is told once each time it starts asking (granted or - switched off, then asking again, is told again). A click opens the pool - area. -5. **Same machine** (`asks.ts`, `sameMachine`): another approved member with - the same `address` (admins see it), or the same name once a suffix such - as `-wsl`, `-ubuntu…`, `-linux` is taken off. + or nodes changed, as the guest lanes are; a pool's first reading as its + admin is the baseline (a member who becomes admin gets no burst); a + machine is told when it starts asking, again after it stopped, but at + most once in 30 minutes; an admin's own machine is never told about. A + click opens the pool area. +5. **Same machine** (`asks.ts`, `related`): another approved member with + the same `address` (admins see it), else one with the same name once a + suffix such as `-wsl`, `-ubuntu…`, `-linux` is taken off. The Admin tab + says which it is and names the other's id: "asked from the same address + as X (id)", or "a similar name to X (id), not checked". A member picks + its own name, so a name alone is no evidence; the coordinator keeps no + invisible characters (bidi overrides, zero-width marks) in a name a + machine gives itself (`member_name`). + +The points 3 to 5 got their last form after the reviews before 0.52.0, +which found the first build told an admin about their own machine, a +member who became admin about every machine asking already, and every +switch on and off again; and called a name match "same machine as X?", +which a member could use to pass for a known machine. Decided while building, not on the card: diff --git a/ui/src/components/ShareSetupDialog.vue b/ui/src/components/ShareSetupDialog.vue index 1de3c60b..29a3e79e 100644 --- a/ui/src/components/ShareSetupDialog.vue +++ b/ui/src/components/ShareSetupDialog.vue @@ -7,6 +7,7 @@ import { computed, ref, watch } from 'vue'; import type { SharePreflight, ShareSwitch } from '@/api/types'; import { bytes } from '@/lib/format'; +import { parseCap } from '@/lib/gpus'; import { usePool } from '@/stores/pool'; import Modal from './Modal.vue'; import ShareChecks from './ShareChecks.vue'; @@ -43,11 +44,7 @@ function num(v: string): number | undefined { const n = Number(v.replace(',', '.')); return v.trim() && Number.isFinite(n) && n > 0 ? n : undefined; } -/** A count, 0 included (no GPU for the pool). */ -function count(v: string): number | undefined { - const n = Number(v); - return v.trim() && Number.isInteger(n) && n >= 0 ? n : undefined; -} +const gpuParsed = computed(() => parseCap(gpuCap.value)); /** The machine's GPUs. */ const gpus = computed(() => s.value?.gpus?.length ?? 0); function form(enabled: boolean): ShareSwitch { @@ -56,7 +53,7 @@ function form(enabled: boolean): ShareSwitch { enabled, max_cpus: num(cpuCap.value), max_memory: m === undefined ? undefined : Math.round(m * GIB), - max_gpus: count(gpuCap.value), + max_gpus: gpuParsed.value.cap, distro: distro.value || undefined, port: sw.value.port, }; @@ -187,7 +184,8 @@ function close() {

Checking what the node agent needs…

@@ -213,7 +211,7 @@ function close() { @@ -233,7 +231,7 @@ function close() { diff --git a/ui/src/components/ShareSwitch.vue b/ui/src/components/ShareSwitch.vue index 0e3d5b7a..91ada694 100644 --- a/ui/src/components/ShareSwitch.vue +++ b/ui/src/components/ShareSwitch.vue @@ -9,6 +9,7 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue'; import type { ShareHost, ShareSwitch } from '@/api/types'; import { bytes } from '@/lib/format'; +import { parseCap } from '@/lib/gpus'; import { usePool } from '@/stores/pool'; import ShareChecks from './ShareChecks.vue'; @@ -46,11 +47,7 @@ function num(v: string): number | undefined { const n = Number(v.replace(',', '.')); return v.trim() && Number.isFinite(n) && n > 0 ? n : undefined; } -/** A count, 0 included (no GPU for the pool). */ -function count(v: string): number | undefined { - const n = Number(v); - return v.trim() && Number.isInteger(n) && n >= 0 ? n : undefined; -} +const gpuParsed = computed(() => parseCap(gpuCap.value)); /** The switch as the form says it, `enabled` as given. */ function form(enabled: boolean): ShareSwitch { const m = num(memCap.value); @@ -58,7 +55,7 @@ function form(enabled: boolean): ShareSwitch { enabled, max_cpus: num(cpuCap.value), max_memory: m === undefined ? undefined : Math.round(m * GIB), - max_gpus: count(gpuCap.value), + max_gpus: gpuParsed.value.cap, distro: distro.value || undefined, port: sw.value.port, }; @@ -178,9 +175,10 @@ const windows = computed(() => !!host.value?.distros?.length || !!sw.value.distr - +

{{ host.detail }}

diff --git a/ui/src/lib/asks.test.ts b/ui/src/lib/asks.test.ts index 3631c4d2..0bb29c7f 100644 --- a/ui/src/lib/asks.test.ts +++ b/ui/src/lib/asks.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { PoolMember, PoolNode, PoolOverview } from '@/api/types'; -import { asking, sameMachine } from './asks'; +import { asking, related, relatedText } from './asks'; const member = (id: string, extra: Partial = {}): PoolMember => ({ id, name: id, state: 'approved', role: 'member', requested_at: 1, ...extra }); const node = (id: string, online: boolean, sharing: boolean): PoolNode => ({ id, name: id, online, report: { sharing, cpus: 4, memory: 8 } }) as PoolNode; @@ -22,8 +22,16 @@ describe('machines that ask to run lanes', () => { members: [member('a1', { name: 'DESKTOP-42' }), member('a2', { name: 'DESKTOP-42-wsl', node: true }), member('b1', { name: 'build', address: '10.0.0.7' }), member('b2', { name: 'other', address: '10.0.0.7' }), member('c', { name: 'lonely' })], }; const m = (id: string) => o.members!.find((x) => x.id === id)!; - expect(sameMachine(m('a1'), o)?.id).toBe('a2'); - expect(sameMachine(m('b1'), o)?.id).toBe('b2'); - expect(sameMachine(m('c'), o)).toBeNull(); + expect(related(m('a1'), o)).toMatchObject({ member: { id: 'a2' }, by: 'name' }); + expect(related(m('b1'), o)).toMatchObject({ member: { id: 'b2' }, by: 'address' }); + expect(related(m('c'), o)).toBeNull(); + }); + + it('say a name match proves nothing, and name the other id', () => { + // A member picks its own name: one granted already could call itself + // after another machine (review before 0.52.0). + const granted = member('5d1e8a77c0ffee00', { name: 'anna-wsl', node: true }); + expect(relatedText({ member: granted, by: 'name' })).toBe('a similar name to anna-wsl (5d1e8a77), not checked; that one may run lanes already'); + expect(relatedText({ member: member('b2', { name: 'other' }), by: 'address' })).toBe('asked from the same address as other (b2)'); }); }); diff --git a/ui/src/lib/asks.ts b/ui/src/lib/asks.ts index 05e69928..8b280af5 100644 --- a/ui/src/lib/asks.ts +++ b/ui/src/lib/asks.ts @@ -20,13 +20,27 @@ function stem(name: string): string { return name.toLowerCase().replace(/[-_.](wsl\d*|ubuntu[\w.-]*|debian|linux|node\d*)$/, ''); } +export type Related = { member: PoolMember; by: 'address' | 'name' }; + /** - * Another approved member that looks like the same machine as `m`: the same - * address it asked from, or the same name up to a suffix such as `-wsl` (a - * setup by hand in WSL before the share switch). Only a hint: the pool has no - * id of a machine beside its members. + * Another approved member that may be the same machine as `m`: one that asked + * from the same address, else one with the same name up to a suffix such as + * `-wsl` (a setup by hand in WSL before the share switch). Only a hint: the + * pool has no id of a machine beside its members, and a member picks its own + * name, so a name alone proves nothing (review before 0.52.0); the page says + * which it is and names the other's id. */ -export function sameMachine(m: PoolMember, o: PoolOverview | null | undefined): PoolMember | null { +export function related(m: PoolMember, o: PoolOverview | null | undefined): Related | null { const others = (o?.members ?? []).filter((x) => x.id !== m.id && x.state === 'approved'); - return others.find((x) => (m.address && x.address === m.address) || stem(x.name) === stem(m.name)) ?? null; + const byAddress = m.address ? others.find((x) => x.address === m.address) : undefined; + if (byAddress) return { member: byAddress, by: 'address' }; + const byName = others.find((x) => stem(x.name) === stem(m.name)); + return byName ? { member: byName, by: 'name' } : null; +} + +/** The hint as the Admin tab shows it. */ +export function relatedText(r: Related): string { + const who = `${r.member.name} (${r.member.id.slice(0, 8)})`; + const runs = r.member.node ? '; that one may run lanes already' : ''; + return r.by === 'address' ? `asked from the same address as ${who}${runs}` : `a similar name to ${who}, not checked${runs}`; } diff --git a/ui/src/lib/gpus.test.ts b/ui/src/lib/gpus.test.ts index fe894380..7390d434 100644 --- a/ui/src/lib/gpus.test.ts +++ b/ui/src/lib/gpus.test.ts @@ -1,5 +1,15 @@ import { describe, expect, it } from 'vitest'; -import { sharedText, summarise } from './gpus'; +import { parseCap, sharedText, summarise } from './gpus'; + +describe('the GPU cap as typed', () => { + it('is no cap when empty, a cap from 0 up, and invalid otherwise', () => { + expect(parseCap('')).toEqual({ invalid: false }); + expect(parseCap(' 0 ')).toEqual({ cap: 0, invalid: false }); + expect(parseCap('2')).toEqual({ cap: 2, invalid: false }); + // Taken for "no cap" before (review before 0.52.0). + for (const v of ['zwei', '1.5', '-1']) expect(parseCap(v)).toEqual({ invalid: true }); + }); +}); const GIB = 2 ** 30; const gpu = (offered: boolean, lane?: string) => ({ name: 'NVIDIA L4', memory: 24 * GIB, memory_used: 2 * GIB, load: 10, offered, lane }); diff --git a/ui/src/lib/gpus.ts b/ui/src/lib/gpus.ts index b9367639..c6c422bb 100644 --- a/ui/src/lib/gpus.ts +++ b/ui/src/lib/gpus.ts @@ -49,6 +49,17 @@ export function gpuState(g: Gpu): string { return g.busy ? 'in use on the machine' : 'not offered'; } +/** + * The GPU cap as typed in the share switch's form: empty is no cap, a whole + * number from 0 up a cap (0: none for the pool); anything else is `invalid`, + * which the form says and does not save (it was taken for "no cap" before). + */ +export function parseCap(v: string): { cap?: number; invalid: boolean } { + if (!v.trim()) return { invalid: false }; + const n = Number(v.trim()); + return Number.isInteger(n) && n >= 0 ? { cap: n, invalid: false } : { invalid: true }; +} + /** A shared machine's GPUs in its row: `1 GPU free`, `1 GPU held`, `2 GPUs (1 free)`; none offered: `GPU in use` or `GPU not offered`. */ export function sharedText(gpus: Gpu[] | undefined): string | null { const s = summarise(gpus); diff --git a/ui/src/views/pool/PoolAdmin.vue b/ui/src/views/pool/PoolAdmin.vue index 71a1d79f..1559772f 100644 --- a/ui/src/views/pool/PoolAdmin.vue +++ b/ui/src/views/pool/PoolAdmin.vue @@ -7,7 +7,7 @@ import { computed, watchEffect } from 'vue'; import { useRouter } from 'vue-router'; import { ago, bytes, useNow } from '@/lib/format'; import { actionText } from '@/lib/poolText'; -import { sameMachine } from '@/lib/asks'; +import { related, relatedText } from '@/lib/asks'; import { sharedText } from '@/lib/gpus'; import { usePool } from '@/stores/pool'; import Icon from '@/components/icons/Icon.vue'; @@ -85,9 +85,7 @@ watchEffect(() => { {{ a.member.name }} -

- same machine as {{ sameMachine(a.member, o)!.name }}? -
+
{{ relatedText(related(a.member, o)!) }}
{{ a.node.report!.cpus.toFixed(1) }} CPU · {{ bytes(a.node.report!.memory) }} diff --git a/ui/src/views/pool/PoolMachines.vue b/ui/src/views/pool/PoolMachines.vue index cee546dc..4396e797 100644 --- a/ui/src/views/pool/PoolMachines.vue +++ b/ui/src/views/pool/PoolMachines.vue @@ -18,8 +18,8 @@ const isMe = (id: string) => o.value?.me?.id === id; const lanesOn = (id: string) => (o.value?.leases ?? []).filter((l) => l.node === id).length; const removed = computed(() => (o.value?.members ?? []).filter((m) => m.state === 'removed')); const showRemoved = ref(false); -/** Machines that share and wait for their grant (#599). */ -const asks = computed(() => new Set(pool.asks.map((a) => a.member.id))); +/** Machines that share and wait for their grant (#599): an admin's to act on, shown to admins. */ +const asks = computed(() => new Set(pool.isAdmin ? pool.asks.map((a) => a.member.id) : []));