diff --git a/CHANGELOG.md b/CHANGELOG.md index bfe1506c..314fc850 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **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 + 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 + used, measured by the node. The machines table's "Shares" column says the + GPUs a machine offers (`· 1 GPU free`). + ### Fixed - **Sharing on Windows finds devstack installed as the setup says.** The diff --git a/crates/devstack-daemon/src/external.rs b/crates/devstack-daemon/src/external.rs index d47c04ed..ff75a578 100644 --- a/crates/devstack-daemon/src/external.rs +++ b/crates/devstack-daemon/src/external.rs @@ -26,6 +26,25 @@ pub struct ExternalInfra { /// requester or agent leaves it out, and the ports stay not forwarded. #[serde(default)] pub udp: bool, + /// The GPUs the node gave the lane, as the agent measured them with its + /// containers; an agent of an earlier release, or a lane without a GPU, + /// leaves it out. + #[serde(default)] + pub gpus: Option>, +} + +/// One GPU of the lane: its name, memory and what is used of it (bytes), +/// its load (percent). +#[derive(Debug, Clone, Deserialize, Default)] +pub struct ExternalGpu { + #[serde(default)] + pub name: String, + #[serde(default)] + pub memory: u64, + #[serde(default)] + pub memory_used: u64, + #[serde(default)] + pub load: f64, } #[derive(Debug, Clone, Deserialize, Default)] diff --git a/crates/devstack-daemon/src/usage.rs b/crates/devstack-daemon/src/usage.rs index 2bbb5600..a126c217 100644 --- a/crates/devstack-daemon/src/usage.rs +++ b/crates/devstack-daemon/src/usage.rs @@ -97,8 +97,28 @@ pub struct LaneEntry { pub load: Load, #[serde(skip_serializing_if = "Option::is_none")] pub disk: Option, + /// The GPUs its node gave it, while they are measured: only a lane on a + /// node holds GPUs of its own (ADR-0112). + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu: Option, } +/// A lane's GPUs together. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct LaneGpu { + pub count: u32, + /// Their names, one per kind (`NVIDIA GeForce RTX 4090`). + pub name: String, + /// Their memory, and what of it is used now, bytes. + pub memory: u64, + pub memory_used: u64, + /// Their load now, percent of one GPU summed (may exceed 100, as CPU). + pub load: f64, +} + +/// The series of a lane's GPUs: load as `cpu`, used memory as `memory`. +const GPU_KEY: &str = "gpu"; + #[derive(Debug, Clone, Serialize)] pub struct UsageReport { pub at: u128, @@ -221,8 +241,11 @@ impl Series { #[derive(Default)] struct Inner { - /// `service:`, `build`, `container:/`. + /// `service:`, `build`, `container:/`, `gpu`. series: BTreeMap, + /// What the lane's GPUs are: count, names, memory (their series is + /// [`GPU_KEY`]). + gpus: Option<(u32, String, u64)>, disk: Disk, disk_measured: bool, docker_error: Option, @@ -389,6 +412,26 @@ impl Sampler { } } unmeasured(&mut inner, &seen, running); + match ext.gpus.filter(|g| fresh && !g.is_empty()) { + Some(gpus) => { + let mut names: Vec<&str> = gpus.iter().map(|g| g.name.as_str()).collect(); + names.dedup(); + inner.gpus = Some(( + gpus.len() as u32, + names.join(", "), + gpus.iter().map(|g| g.memory).sum(), + )); + inner.series.entry(GPU_KEY.into()).or_default().push(Load { + cpu: gpus.iter().map(|g| g.load).sum(), + memory: gpus.iter().map(|g| g.memory_used).sum(), + }); + } + None => { + if let Some(s) = inner.series.get_mut(GPU_KEY) { + s.missed(); + } + } + } } fn sample_volumes(&self, sup: &Supervisor) { @@ -446,10 +489,12 @@ impl Sampler { sup.docker().project_images(&projects).unwrap_or(0) }; let inner = self.inner.lock().unwrap(); + // A GPU's memory is not the lane's memory. let (cpus, memory) = inner .series - .values() - .map(Series::peak) + .iter() + .filter(|(k, _)| *k != GPU_KEY) + .map(|(_, s)| s.peak()) .fold((0.0, 0), |(c, m), (pc, pm)| (c + pc, m + pm)); let d = &inner.disk; Estimate { @@ -543,12 +588,26 @@ impl Sampler { }, load: lane, disk: inner.disk_measured.then(|| inner.disk.clone()), + gpu: lane_gpu(inner.gpus.as_ref(), get(GPU_KEY).current), }], docker_error: inner.docker_error.clone(), } } } +/// The lane's GPUs as reported: what they are, and their load now; none +/// while they are not measured. +fn lane_gpu(gpus: Option<&(u32, String, u64)>, now: Option) -> Option { + let ((count, name, memory), now) = gpus.zip(now)?; + Some(LaneGpu { + count: *count, + name: name.clone(), + memory: *memory, + memory_used: now.memory, + load: now.cpu, + }) +} + /// The containers this round measured no number for: a running one keeps its /// last for a few rounds ([`MISS_GRACE`]), any other is idle. fn unmeasured(inner: &mut Inner, seen: &[String], running: &[String]) { @@ -644,6 +703,47 @@ mod tests { assert_eq!(s.history.len(), 3, "history survives a stop"); } + #[test] + fn a_lanes_gpus_come_from_its_nodes_file_and_not_into_its_memory() { + let sampler = Sampler { + inner: Mutex::new(Inner::default()), + tree: Mutex::new(None), + }; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("external-infra.json"); + let write = |gpus: serde_json::Value| { + let v = serde_json::json!({ "groups": {}, "at": now_ms() as u64, "gpus": gpus }); + std::fs::write(&file, v.to_string()).unwrap(); + }; + let gpu = |load: f64| serde_json::json!({ "name": "RTX", "memory": 8u64 << 30, "memory_used": 2u64 << 30, "load": load, "offered": false }); + write(serde_json::json!([gpu(90.0), gpu(30.0)])); + sampler.sample_external(&file, &[]); + let inner = sampler.inner.lock().unwrap(); + let g = lane_gpu(inner.gpus.as_ref(), inner.series[GPU_KEY].current).unwrap(); + assert_eq!( + g, + LaneGpu { + count: 2, + name: "RTX".into(), + memory: 16 << 30, + memory_used: 4 << 30, + load: 120.0, + } + ); + drop(inner); + // A round without them keeps the last for a few, then there are none. + std::fs::write( + &file, + serde_json::json!({ "groups": {}, "at": now_ms() as u64 }).to_string(), + ) + .unwrap(); + for _ in 0..=MISS_GRACE { + sampler.sample_external(&file, &[]); + } + let inner = sampler.inner.lock().unwrap(); + assert!(lane_gpu(inner.gpus.as_ref(), inner.series[GPU_KEY].current).is_none()); + } + #[test] fn a_running_container_without_a_number_keeps_its_last_for_a_few_rounds() { let mut inner = Inner::default(); diff --git a/crates/devstack-hub/src/nodehost.rs b/crates/devstack-hub/src/nodehost.rs index 3932dd84..0921ef84 100644 --- a/crates/devstack-hub/src/nodehost.rs +++ b/crates/devstack-hub/src/nodehost.rs @@ -19,8 +19,9 @@ //! //! - `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 +//! - `PUT /hub/pool/share?pool=` `{enabled, max_cpus?, max_memory?, +//! max_gpus?, distro?, port?}`: change the switch; acted on within a few +//! seconds use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -71,6 +72,9 @@ pub struct Switch { pub max_cpus: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub max_memory: Option, + /// The most GPUs they hold together; `0`: the owner keeps them all. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_gpus: Option, /// Windows: the WSL distribution the agent runs in. #[serde(default, skip_serializing_if = "Option::is_none")] pub distro: Option, @@ -283,6 +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 { + a.extend(["--max-gpus".into(), g.to_string()]); + } if !new_lanes { a.push("--no-new-lanes".into()); } @@ -840,6 +849,7 @@ fn launch( enabled: new_lanes, max_cpus: sw.max_cpus, max_memory: sw.max_memory, + max_gpus: sw.max_gpus, }, dedicated: false, free: None, @@ -1484,6 +1494,7 @@ mod tests { enabled: true, max_cpus: Some(8.0), max_memory: Some(8 << 30), + max_gpus: Some(0), distro: Some("Ubuntu-24.04".into()), port: None, }; @@ -1497,7 +1508,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 --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 --max-gpus 0 --no-new-lanes" + ); + // Not set: not passed, for an agent that does not know it. + assert!( + !agent_args("default", &Switch::default(), "https://x:4261", None, true) + .contains(&"--max-gpus".to_string()) ); 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 889e4cfc..0f188eda 100644 --- a/crates/devstack-hub/src/share.rs +++ b/crates/devstack-hub/src/share.rs @@ -457,6 +457,7 @@ mod tests { enabled: true, max_cpus: Some(4.0), max_memory: Some(4 << 30), + max_gpus: None, }, dedicated: false, // Fixed, so that a busy machine running the test does not diff --git a/crates/devstack-node/src/laneinfra.rs b/crates/devstack-node/src/laneinfra.rs index e0c5bd5d..5b5b70e7 100644 --- a/crates/devstack-node/src/laneinfra.rs +++ b/crates/devstack-node/src/laneinfra.rs @@ -73,7 +73,7 @@ pub fn set_group( with_group(&mut infra, group, state, error); let json = serde_json::to_vec_pretty(&infra).expect("infra serialises"); write_agent_file(dir, &json).map_err(|e| e.to_string())?; - refresh(dir, src) + refresh(dir, src, None) } /// What the agent says of a group it was bringing up when it ended. @@ -111,7 +111,7 @@ pub fn interrupted(dir: &Path, src: &Path) { if interrupted_in(&mut infra) { let json = serde_json::to_vec_pretty(&infra).expect("infra serialises"); if write_agent_file(dir, &json).is_ok() { - let _ = refresh(dir, src); + let _ = refresh(dir, src, None); } } } @@ -360,11 +360,13 @@ struct Load { /// The daemon's file with the states, health and load of now written into /// it: `base` is the agent's own copy (what it wrote at start), `found` what -/// `docker ps` sees per group, `load` what `docker stats` measured. +/// `docker ps` sees per group, `load` what `docker stats` measured, `gpus` +/// what the lane's GPUs do (`None`: not measured this time, left out). fn current( base: &serde_json::Value, found: &BTreeMap>, load: &BTreeMap, + gpus: Option<&[crate::share::Gpu]>, at: u128, ) -> serde_json::Value { let mut out = base.clone(); @@ -400,13 +402,18 @@ fn current( } } } + // Name, memory, what is used of it, load: the vendor's id stays here. + if let Some(g) = gpus { + out["gpus"] = serde_json::to_value(g).expect("gpus serialise"); + } out["at"] = serde_json::Value::from(at as u64); out } /// Write the states and load of the lease's containers into the daemon's -/// file (`src` the mirror, `dir` the lease's directory beside it). -pub fn refresh(dir: &Path, src: &Path) -> Result<(), String> { +/// file (`src` the mirror, `dir` the lease's directory beside it), and the +/// GPUs it holds when `gpus` measured them. +pub fn refresh(dir: &Path, src: &Path, gpus: Option<&[crate::share::Gpu]>) -> Result<(), String> { let Ok(text) = std::fs::read(dir.join(AGENT_FILE)) else { return Ok(()); // started by an older agent }; @@ -444,8 +451,8 @@ pub fn refresh(dir: &Path, src: &Path) -> Result<(), String> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_millis()); - let json = - serde_json::to_vec_pretty(¤t(&base, &found, &load, now)).expect("infra serialises"); + let json = serde_json::to_vec_pretty(¤t(&base, &found, &load, gpus, now)) + .expect("infra serialises"); crate::safefs::write_beneath(src, Path::new(LANE_FILE), 0o644, |f| { std::io::Write::write_all(f, &json) }) @@ -569,7 +576,27 @@ members = ["compose.app.db", "compose.app.web", "api"] memory: 1 << 20, }, )]); - let v = current(&base, &found, &load, 42); + let gpu = crate::share::Gpu { + id: "GPU-5b7c".into(), + name: "RTX".into(), + memory: 8 << 30, + memory_used: 2 << 30, + load: 93.0, + lane: Some("shop/x".into()), + ..crate::share::Gpu::default() + }; + let v = current(&base, &found, &load, Some(std::slice::from_ref(&gpu)), 42); + assert_eq!(v["gpus"][0]["load"], 93.0); + assert_eq!(v["gpus"][0]["memory_used"], 2u64 << 30); + assert!( + v["gpus"][0].get("id").is_none(), + "the vendor's id stays on the node" + ); + assert!( + current(&base, &found, &load, None, 42) + .get("gpus") + .is_none() + ); let s = &v["groups"]["app"]["services"]; assert_eq!(s["db"]["health"], "healthy"); assert_eq!(s["db"]["cpu"], 12.5); @@ -598,7 +625,7 @@ members = ["compose.app.db", "compose.app.web", "api"] with_group(&mut infra, "nope", UP, None); assert!(infra["groups"].get("nope").is_none(), "no group is made up"); // The refresh writes what the agent's file says of each group. - let v = current(&infra, &BTreeMap::new(), &BTreeMap::new(), 1); + let v = current(&infra, &BTreeMap::new(), &BTreeMap::new(), None, 1); assert_eq!(v["groups"]["app"]["state"], UP); assert_eq!(v["groups"]["tools"]["state"], CREATED); } diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index 235c179e..546fce31 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -159,24 +159,23 @@ pub struct NodeLease { } /// The machine's GPUs as a node reports them: one a lease holds names its -/// lane and is not offered, every other one is (ADR-0112 point 5). +/// lane (ADR-0112 point 5); what is offered of the rest says +/// [`crate::share::offered_gpus`] with the owner's cap. fn held_gpus( gpus: Vec, leases: &HashMap, + max: Option, ) -> Vec { - gpus.into_iter() - .map(|g| { - let lane = leases + crate::share::offered_gpus( + gpus, + |id| { + leases .values() - .find(|l| l.gpus.contains(&g.id)) - .map(|l| format!("{}/{}", l.repo, l.lane)); - crate::share::Gpu { - offered: lane.is_none(), - lane, - ..g - } - }) - .collect() + .find(|l| l.gpus.iter().any(|g| g == id)) + .map(|l| format!("{}/{}", l.repo, l.lane)) + }, + max, + ) } /// What a slot keeps about itself (`slots//slot.json`). @@ -1795,11 +1794,8 @@ async fn admit( }; let mut leases = s.leases.lock().unwrap(); if let Some(g) = gpu_need { - let taken: HashSet<&str> = leases - .values() - .flat_map(|x| x.gpus.iter().map(String::as_str)) - .collect(); - l.gpus = crate::share::assign_gpus(&machine_gpus, &taken, g).map_err(|fit| { + let offered = held_gpus(machine_gpus, &leases, s.share.max_gpus); + l.gpus = crate::share::assign_gpus(&offered, g).map_err(|fit| { err( StatusCode::CONFLICT, format!( @@ -2792,7 +2788,7 @@ fn act_named( } } // The new states, for the lane's dashboard at once. - let _ = laneinfra::refresh(&run.dir, &run.src()); + let _ = laneinfra::refresh(&run.dir, &run.src(), None); Some(Acted { single, failed }) } @@ -2972,7 +2968,7 @@ async fn infra( crate::laneinfra::may_act(&stack, &group, &service, &action)?; let r = crate::laneinfra::act(&name, &action); // The new state, for the lane's dashboard at once. - let _ = crate::laneinfra::refresh(&dir, &dir.join("src")); + let _ = crate::laneinfra::refresh(&dir, &dir.join("src"), None); r }) .await; @@ -3950,7 +3946,7 @@ async fn background(s: Shared) { let gpus: Vec = tokio::task::spawn_blocking(crate::share::gpus) .await .unwrap_or_default(); - let gpus = held_gpus(gpus, &s.leases.lock().unwrap()); + let gpus = held_gpus(gpus, &s.leases.lock().unwrap(), s.share.max_gpus); // A node sends what concerns the pool's lanes with the coordinator's // setting alone (ADR-0037 point 3): its capacity, every minute. if sent.elapsed() >= Duration::from_secs(60) { @@ -4279,12 +4275,33 @@ pub async fn serve( std::thread::sleep(crate::laneinfra::EVERY); let Some(s) = weak.upgrade() else { return }; let ids: Vec = s.daemons.lock().unwrap().keys().cloned().collect(); + // What the GPUs do, for the lanes holding one (its usage + // page shows them): asked once a round, and only then. + let machine_gpus = if ids.iter().any(|id| { + s.leases + .lock() + .unwrap() + .get(id) + .is_some_and(|l| !l.gpus.is_empty()) + }) { + crate::share::gpus() + } else { + Vec::new() + }; for id in ids { let Some(l) = s.leases.lock().unwrap().get(&id).cloned() else { continue; }; let dir = s.dir_of(&l); - if let Err(e) = crate::laneinfra::refresh(&dir, &dir.join("src")) { + let gpus: Vec = machine_gpus + .iter() + .filter(|g| l.gpus.contains(&g.id)) + .cloned() + .collect(); + // A lane without a GPU, or whose GPUs the tool did not + // name this time, gets none written. + let gpus = (!gpus.is_empty()).then_some(gpus.as_slice()); + if let Err(e) = crate::laneinfra::refresh(&dir, &dir.join("src"), gpus) { eprintln!("lane {id}: its containers: {e}"); } } @@ -4441,7 +4458,7 @@ mod tests { let mut held = lease("train", true); held.gpus = vec!["b".into()]; let leases: HashMap = [("train".to_string(), held)].into(); - let r = held_gpus(vec![gpu("a"), gpu("b")], &leases); + let r = held_gpus(vec![gpu("a"), gpu("b")], &leases, None); assert!(r[0].offered && r[0].lane.is_none()); assert!(!r[1].offered); assert_eq!(r[1].lane.as_deref(), Some("r/train")); diff --git a/crates/devstack-node/src/share.rs b/crates/devstack-node/src/share.rs index dc4562b7..904da2a6 100644 --- a/crates/devstack-node/src/share.rs +++ b/crates/devstack-node/src/share.rs @@ -17,6 +17,10 @@ pub struct Settings { /// The most memory it ever offers, bytes. #[serde(default, skip_serializing_if = "Option::is_none")] pub max_memory: Option, + /// The most GPUs its lanes hold together; `None`: every one, `0`: none + /// (the owner keeps them). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_gpus: Option, } /// CPU cores and memory (bytes). @@ -200,6 +204,51 @@ pub struct Gpu { /// The lane that holds it (`/`). #[serde(default, skip_serializing_if = "Option::is_none")] pub lane: Option, + /// Not offered because a process outside the pool's lanes uses it: more + /// than [`IN_USE`] of its memory, with no lane holding it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub busy: bool, +} + +/// The part of a free GPU's memory that, used by other processes, keeps it +/// from the pool: its owner works on it. +pub const IN_USE: f64 = 0.25; + +impl Gpu { + /// Whether processes on the machine use more than [`IN_USE`] of its + /// memory. + pub fn in_use(&self) -> bool { + self.memory > 0 && self.memory_used as f64 > self.memory as f64 * IN_USE + } +} + +/// 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. +pub fn offered_gpus( + gpus: Vec, + holder: impl Fn(&str) -> Option, + max: Option, +) -> 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)); + 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 + } + }) + .collect() } /// The machine's GPUs, as the vendor's tool reports them (`nvidia-smi`, on @@ -238,22 +287,19 @@ pub fn parse_nvidia_smi(text: &str) -> Vec { load: load.parse().unwrap_or(0.0), offered: false, lane: None, + busy: false, }) }) .collect() } /// The GPUs a lane that needs `need` is given (ADR-0112 point 2): the first -/// ones not `taken` by another lease with the memory it asks for, in the +/// 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], - taken: &std::collections::HashSet<&str>, - need: GpuNeed, -) -> Result, usize> { +pub fn assign_gpus(gpus: &[Gpu], need: GpuNeed) -> Result, usize> { let fit: Vec = gpus .iter() - .filter(|g| !g.id.is_empty() && !taken.contains(g.id.as_str()) && g.memory >= need.memory) + .filter(|g| g.offered && !g.id.is_empty() && g.memory >= need.memory) .map(|g| g.id.clone()) .collect(); if (fit.len() as u32) < need.count { @@ -313,17 +359,75 @@ mod tests { count, memory: gib * GIB, }; - let none = std::collections::HashSet::new(); - assert_eq!(assign_gpus(&gpus, &none, need(1, 0)), Ok(vec!["a".into()])); - assert_eq!(assign_gpus(&gpus, &none, need(1, 16)), Ok(vec!["b".into()])); - let taken: std::collections::HashSet<&str> = ["b"].into(); + let offer = |held: &[&str], max| { + let held: Vec = held.iter().map(|h| h.to_string()).collect(); + offered_gpus( + gpus.to_vec(), + |id| held.iter().any(|h| h == id).then(|| "shop/x".into()), + max, + ) + }; assert_eq!( - assign_gpus(&gpus, &taken, need(1, 16)), + 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(&gpus, &taken, need(2, 16)), Err(1)); + assert_eq!(assign_gpus(&offer(&["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)); // A GPU whose id the tool did not say cannot be given to a container. - assert_eq!(assign_gpus(&[gpu("", 24)], &none, need(1, 0)), Err(0)); + let unnamed = offered_gpus(vec![gpu("", 24)], |_| None, None); + assert_eq!(assign_gpus(&unnamed, need(1, 0)), Err(0)); + } + + #[test] + fn a_node_offers_no_gpu_beyond_its_cap_or_in_use_on_the_machine() { + let gpu = |id: &str, used_gib: u64| Gpu { + id: id.into(), + memory: 16 * GIB, + memory_used: used_gib * GIB, + ..Gpu::default() + }; + // `b`: a quarter of its memory is still free to take; `c` is the + // owner's training. + let gpus = vec![gpu("a", 0), gpu("b", 4), gpu("c", 5), gpu("d", 0)]; + let all = offered_gpus( + gpus.clone(), + |id| (id == "d").then(|| "shop/x".into()), + None, + ); + let state: Vec<(bool, bool, bool)> = all + .iter() + .map(|g| (g.offered, g.busy, g.lane.is_some())) + .collect(); + assert_eq!( + state, + [ + (true, false, false), + (true, false, false), + (false, true, false), + (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 + .iter() + .filter(|g| g.offered) + .map(|g| g.id.as_str()) + .collect(); + assert_eq!(offered, ["a"]); + // A GPU a lane holds is never busy, whatever it uses. + let held = offered_gpus(vec![gpu("a", 15)], |_| Some("shop/x".into()), None); + assert!(!held[0].busy && !held[0].offered); } const GIB: u64 = 1 << 30; @@ -355,6 +459,7 @@ mod tests { enabled: true, max_cpus: Some(2.0), max_memory: Some(4 * GIB), + max_gpus: None, }; assert_eq!( capped.offer(free, None), @@ -437,6 +542,7 @@ mod tests { enabled: true, max_cpus: Some(3.0), max_memory: None, + max_gpus: Some(0), }; s.save(dir.path()).unwrap(); assert_eq!(Settings::load(dir.path()), s); diff --git a/crates/devstack-node/tests/node.rs b/crates/devstack-node/tests/node.rs index cd251d67..9548105c 100644 --- a/crates/devstack-node/tests/node.rs +++ b/crates/devstack-node/tests/node.rs @@ -113,6 +113,7 @@ fn a_lane_is_leased_admitted_and_synced() { enabled: true, max_cpus: Some(4.0), max_memory: Some(4 << 30), + max_gpus: None, }, dedicated: true, free: Some(FREE), @@ -619,6 +620,7 @@ fn an_admin_pauses_a_node_and_ends_a_lease() { enabled: true, max_cpus: Some(4.0), max_memory: Some(4 << 30), + max_gpus: None, }, dedicated: true, free: Some(FREE), diff --git a/crates/devstack/src/dispatch/pool.rs b/crates/devstack/src/dispatch/pool.rs index b5a106d9..9d7c9a32 100644 --- a/crates/devstack/src/dispatch/pool.rs +++ b/crates/devstack/src/dispatch/pool.rs @@ -104,6 +104,7 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { api, max_cpus, max_memory_gib, + max_gpus, dedicated, pool, print_unit: true, @@ -115,8 +116,12 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { &pool, &listen, api.as_deref(), - max_cpus, - max_memory_gib, + poolcmd::AgentShare { + max_cpus, + max_memory_gib, + max_gpus, + new_lanes: true, + }, dedicated )? ); @@ -127,6 +132,7 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { api, max_cpus, max_memory_gib, + max_gpus, dedicated, pool, membership, @@ -139,6 +145,7 @@ fn node(file: &Path, action: NodeAction) -> Result<()> { poolcmd::AgentShare { max_cpus, max_memory_gib, + max_gpus, new_lanes: !no_new_lanes, }, dedicated, diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index 4ef1d102..b710768b 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -710,6 +710,10 @@ enum NodeAction { /// The most memory it offers, in GiB. #[arg(long)] max_memory_gib: Option, + /// The most GPUs its lanes hold together (default: every one; 0: + /// none). + #[arg(long)] + max_gpus: Option, /// A server its owner never reclaims (ADR-0026): the pool shows it as /// one; a developer's machine leaves it out. #[arg(long)] diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index 6df0cb20..9b610795 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -899,6 +899,7 @@ fn pool_one(pool: &str, local: &Local) -> Result<()> { pub struct AgentShare { pub max_cpus: Option, pub max_memory_gib: Option, + pub max_gpus: Option, pub new_lanes: bool, } @@ -926,6 +927,7 @@ pub fn agent( max_memory: offer .max_memory_gib .map(|g| (g * f64::from(1u32 << 30)) as u64), + max_gpus: offer.max_gpus, }; let dir = match membership { Some(d) => d, @@ -965,8 +967,7 @@ pub fn agent_unit( pool: &str, listen: &str, api: Option<&str>, - max_cpus: Option, - max_memory_gib: Option, + offer: AgentShare, dedicated: bool, ) -> Result { let exe = std::env::current_exe()?; @@ -981,12 +982,15 @@ pub fn agent_unit( if let Some(a) = api { args.extend(["--api".into(), a.into()]); } - if let Some(c) = max_cpus { + if let Some(c) = offer.max_cpus { args.extend(["--max-cpus".into(), c.to_string()]); } - if let Some(m) = max_memory_gib { + if let Some(m) = offer.max_memory_gib { args.extend(["--max-memory-gib".into(), m.to_string()]); } + if let Some(g) = offer.max_gpus { + args.extend(["--max-gpus".into(), g.to_string()]); + } if dedicated { args.push("--dedicated".into()); } 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 new file mode 100644 index 00000000..c87e93f5 --- /dev/null +++ b/docs/adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md @@ -0,0 +1,88 @@ +# ADR-0115: A machine keeps the GPUs its owner wants, and a lane shows its own + +- **Status:** Accepted (card in the pull request); built +- **Date:** 2026-11-20 +- **Deciders:** project owner +- **Related:** [ADR-0112](0112-a-node-gives-a-lane-the-gpus-it-asked-for.md) (a node gives a lane its GPUs; "no policy key for GPUs" left for when a node owner asks), [ADR-0113](0113-the-share-switch-runs-the-node-agent.md) (the share switch and its caps), [ADR-0114](0114-a-start-in-the-pool-can-ask-for-gpus.md) (the machine cards' GPU line), [ADR-0031](0031-a-coordinator-places-lanes.md) (point 3: what a machine shares) + +## Context + +The share switch capped CPU and memory; a shared machine offered every GPU +no lane held. Its owner could not keep a GPU for themselves, and a lane of +the pool got a GPU the owner was using right then (a training of their +own), since the node checked only the GPU's total memory. And a lane's +usage showed CPU, memory and disk, never the GPU it ran on; the machines +table showed a GPU at most as a badge. + +## Decision + +The owner approved the review card in the conversation on **2026-11-20**, +points 1 to 4: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | term | The machines table's "Shares" column says the GPUs too: `14.2 CPU · 6.7 GB · 1 GPU free` or `held`. | A "GPU" badge with a tooltip | Low: display only | +| 2 | contract | A lane holding GPUs shows a fourth tile "GPU" on its lane card and usage page: their load and memory, with their history; the values come from its node. | No GPU in a lane's usage | Medium: a field in the usage API | +| 3 | trust | The share switch takes `max_gpus`: the most GPUs it offers the pool; `0` keeps them for its owner; not set, as before, all. | Every GPU of a shared machine free for the pool | Low: an optional key; old files load as before | +| 4 | trust | A GPU whose memory processes outside the pool's lanes use for more than a quarter is not offered; it shows as "in use on the machine". | A pool lane given a GPU its owner is using | Low; the threshold is an assumption | + +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. +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. +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 + 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 + the lane's `gpu` (`count`, `name`, `memory`, `memory_used`, `load`, the + load summed in percent of one GPU, as CPU); a round without them keeps + the last for a few rounds. Their memory does not count into the lane's + expected memory need. +4. **The dashboard:** the lane card's GPU tile (load, sparkline, memory + used of all), the machines table's `· 1 GPU free`, and "in use on the + machine" beside such a GPU on a machine's page and in its title. + +Decided while building, not on the card: + +- No GPU tile for a lane on this machine: it holds no GPU of its own, and + the machine's GPU shows under "This machine". +- No GPU column per process in the usage table: in a container the process + ids do not match those `nvidia-smi` names. +- No `share_percent` for GPUs: a GPU goes to one lane whole. +- A GPU a lane holds is never `busy`, whatever it uses; a held GPU above the + cap stays held (lowering the cap takes nothing from a running lane). +- The node measures a lane's GPUs only while one of its leases holds a GPU. + +## Alternatives considered + +- **A policy key for GPUs** (the coordinator's or the node's + `policy.json`): the policy is the admin's; keeping a GPU is the owner's + choice, like the CPU and memory caps on the switch. +- **`nvidia-smi` inside the lane container:** it sees only the lane's GPUs, + but needs the toolkit's utilities in every lane image; the node measures + them already. +- **Offering a GPU in use when it has room** (by free memory): a lane would + share the GPU with the owner's process, which ADR-0112 ruled out between + lanes. + +## Consequences + +- An owner shares CPU and memory and keeps the GPU with a GPU cap of 0, or + shares it and gets it back from the pool while they use it themselves. +- On a desktop the display uses some GPU memory; a GPU with less than four + times that is never offered. The threshold can move if a node owner asks. +- Verified by unit tests (offer, cap and busy, assignment, the lane file, + the daemon's series, the hub's agent arguments, the dashboard's texts) and + in the mock dashboard; with a real GPU on the WSL node of #168. diff --git a/docs/adr/README.md b/docs/adr/README.md index 42b0adaa..c4086d68 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -194,6 +194,7 @@ stay. | [0109](0109-the-order-of-the-stacks-is-one-choice-for-the-sidebar-and-the-start-page.md) | The order of the stacks is one choice for the sidebar and the start page | Accepted (card in the pull request); built; amended 2026-11-19 (a setup dialog before the switch) | | [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; amended 2026-11-19 (a setup dialog before the switch) | -| [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 | +| [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; the owner's GPU cap and a GPU in use, ADR-0115 | | [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; amended 2026-11-19 (a setup dialog before the switch) | | [0114](0114-a-start-in-the-pool-can-ask-for-gpus.md) | A start in the pool can ask for GPUs, and the dashboard shows where they are | Accepted (card in the pull request); built | +| [0115](0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md) | A machine keeps the GPUs its owner wants, and a lane shows its own | Accepted (card in the pull request); built | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 2e4c81dc..f017898c 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -150,9 +150,9 @@ 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?`), the machine's GPUs as measured (`gpus?`: `[{name, memory, memory_used, load, offered}]`), 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?, fix_note?, optional?}], distros?, prompt?, output?}`, [ADR-0113](adr/0113-the-share-switch-runs-the-node-agent.md)); `fix` is the command alone, `fix_note` where it runs ("In `Ubuntu` as root"; since 0.51.0, before that `fix` said both) | -| `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/pool/share/check?pool= {enabled, max_cpus?, max_memory?, distro?, port?}` | cookie + Origin | what the node agent would find with that switch, without saving or starting anything (since 0.51.0): `{ready, problem?, checks?, distros?, prompt?}` as in `host` above; `ready` is false while a required check fails, the switch is impossible, no address of this machine reaches the coordinator, or on macOS. Runs the checks (on Windows `wsl.exe` and PowerShell, seconds). `400 {"error"}` for a machine that is no approved member. The setup dialog asks it before the switch goes on | +| `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 machine's GPUs as measured (`gpus?`: `[{name, memory, memory_used, load, offered}]`; the switch's `max_gpus`: the most GPUs other members' lanes hold, `0` none, since ADR-0115), the share switch (`switch`: `{enabled, max_cpus?, max_memory?, max_gpus?, 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?, fix_note?, optional?}], distros?, prompt?, output?}`, [ADR-0113](adr/0113-the-share-switch-runs-the-node-agent.md)); `fix` is the command alone, `fix_note` where it runs ("In `Ubuntu` as root"; since 0.51.0, before that `fix` said both) | +| `PUT /hub/pool/share?pool= {enabled, max_cpus?, max_memory?, max_gpus?, 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/pool/share/check?pool= {enabled, max_cpus?, max_memory?, max_gpus?, distro?, port?}` | cookie + Origin | what the node agent would find with that switch, without saving or starting anything (since 0.51.0): `{ready, problem?, checks?, distros?, prompt?}` as in `host` above; `ready` is false while a required check fails, the switch is impossible, no address of this machine reaches the coordinator, or on macOS. Runs the checks (on Windows `wsl.exe` and PowerShell, seconds). `400 {"error"}` for a machine that is no approved member. The setup dialog asks it before the switch goes on | | `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) | @@ -190,7 +190,7 @@ type PoolOverview = { leases?: { id: string; member: string; repo: string; lane: string; expires_in: number }[]; total?: { cpus: number; memory: number }; // what the machine has (ADR-0036) used?: { cpus: number; memory: number }; // what its lanes use - gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean; lane?: string }[]; // `lane` (`/`): the lane holding it, not offered then (ADR-0112) + gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean; lane?: string; busy?: boolean }[]; // `lane` (`/`): the lane holding it, not offered then (ADR-0112); `busy`: in use on the machine, not offered (ADR-0115) kept?: { lanes: number; bytes: number; store_bytes?: number }; // stopped lanes it keeps (ADR-0038) and the members' stores of what `prepare` makes (ADR-0062), together in `bytes`; `store_bytes` the stores' part (older nodes omit it) devstack?: PoolRelease; // what it runs; absent from a release before version reporting }; @@ -385,7 +385,12 @@ type UsageReport = { builds: { name: "builds"; cpu_time_ms?: number; processes?: number; history?: Point[] } & Load; containers: ({ group: string; service: string; history?: Point[] } & Load)[]; groups: ({ name: string } & Load)[]; - lanes: ({ name: string; disk?: { snapshot: number; artifacts: number; logs: number; volumes: number | null } } & Load)[]; + lanes: ({ + name: string; + disk?: { snapshot: number; artifacts: number; logs: number; volumes: number | null }; + /** A lane on a node holding GPUs (ADR-0115), while its node measures them: load in % of one GPU, summed. */ + gpu?: { count: number; name: string; memory: number; memory_used: number; load: number }; + } & Load)[]; docker_error?: string; }; ``` diff --git a/docs/pool.md b/docs/pool.md index 840d5dcc..098bed9b 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -161,6 +161,9 @@ why; so does the share switch. - `--max-cpus`, `--max-memory-gib`: caps on what its lanes take together; below them, half of what is free right now, or the part its policy says (`share_percent`). +- `--max-gpus`: the most GPUs its lanes hold together; `0` offers none. A + GPU a process on the machine uses (more than a quarter of its memory) is + never offered. - `--api https://host:port`: where requesters reach it, when `--listen` is every address (`0.0.0.0:4261`). - `--pool `: the pool it serves (one agent per pool, see [Several @@ -604,8 +607,15 @@ that asks for a GPU (`gpus`, or a `deploy.resources.reservations.devices` entry with the `nvidia` driver) gets those too: `count: n` the first n, `all` every one, `device_ids` only ids among them. A lane that holds no GPU may ask for none: the start says to set `[lanes.need] gpus`. A warm lease -holds none. The node reports each GPU as free, held by a lane, or not -offered; the pool area shows which. The node needs `nvidia-smi` and the +holds none. What a node offers of its GPUs +([ADR-0115](adr/0115-a-machine-keeps-its-gpus-and-a-lane-shows-its-own.md)): +at most `--max-gpus` held and offered together (the share switch's GPU +cap; `0` keeps them all for the owner, not set: every one), and none whose +memory is more than a quarter used by processes on the machine (its owner +works on it). The node reports each GPU as free, held by a lane, in use on +the machine, or not offered; the pool area shows which, and the lane's +usage shows its GPUs' load and memory, measured by the node and written +into the lane's file with its containers. The node needs `nvidia-smi` and the NVIDIA Container Toolkit. A GPU reaches a lane only this way: `runtime: nvidia` is refused, and every container of the lane (its own included) is told exactly its GPUs, or none, in `NVIDIA_VISIBLE_DEVICES`, whatever diff --git a/ui/src/api/mock/data.ts b/ui/src/api/mock/data.ts index f7921966..b963059f 100644 --- a/ui/src/api/mock/data.ts +++ b/ui/src/api/mock/data.ts @@ -45,6 +45,8 @@ export type MockStackSeed = { view: StackView; /** Previous build per service, for rollback. */ previous: Record; + /** The GPUs its lane holds, as a lane on a node does (ADR-0112). */ + gpu?: { count: number; name: string; memory: number }; }; export function shopSeed(now: number): MockStackSeed { @@ -227,6 +229,7 @@ export function crmSeed(now: number): MockStackSeed { }, view: { name: 'crm', repo, version: '0.2.0', services, infra, groups, commands }, previous, + gpu: { count: 1, name: 'NVIDIA GeForce RTX 4070', memory: 12 * 2 ** 30 }, }; } diff --git a/ui/src/api/mock/pool.ts b/ui/src/api/mock/pool.ts index 1bdc3548..46374fcf 100644 --- a/ui/src/api/mock/pool.ts +++ b/ui/src/api/mock/pool.ts @@ -30,6 +30,7 @@ export class MockPool { member: this.joined, reported_at: this.joined ? Date.now() - 4000 : null, error: null, + gpus: [{ name: 'NVIDIA GeForce RTX 4070', memory: 12 * 2 ** 30, memory_used: 1.1 * 2 ** 30, load: 4, offered: false }], switch: this.switch, host: this.host(), }; @@ -101,7 +102,7 @@ export class MockPool { this.members[0].provision = true; this.nodes = [ { id: this.me, name: 'dev-pc', online: true, seen: 4, report: { sharing: false, cpus: 0, memory: 0 }, kind: 'machine' }, - { id: '9f8e7d6c5b4a3921', name: 'build-server', online: true, seen: 7, report: { sharing: true, cpus: 12, memory: 48 * 2 ** 30, api: 'https://10.0.0.14:4261', devstack: { version: '0.10.0', protocol: 1 }, total: { cpus: 32, memory: 128 * 2 ** 30 }, used: { cpus: 6.5, memory: 22 * 2 ** 30 }, kept: { lanes: 1, bytes: 5 * 2 ** 30, store_bytes: 2 * 2 ** 30 }, gpus: [{ name: 'NVIDIA L4', memory: 24 * 2 ** 30, memory_used: 3 * 2 ** 30, load: 18, offered: true }, { name: 'NVIDIA L4', memory: 24 * 2 ** 30, memory_used: 14 * 2 ** 30, load: 71, offered: false, lane: 'shop/train-model' }] }, kind: 'server' }, + { id: '9f8e7d6c5b4a3921', name: 'build-server', online: true, seen: 7, report: { sharing: true, cpus: 12, memory: 48 * 2 ** 30, api: 'https://10.0.0.14:4261', devstack: { version: '0.10.0', protocol: 1 }, total: { cpus: 32, memory: 128 * 2 ** 30 }, used: { cpus: 6.5, memory: 22 * 2 ** 30 }, kept: { lanes: 1, bytes: 5 * 2 ** 30, store_bytes: 2 * 2 ** 30 }, gpus: [{ name: 'NVIDIA L4', memory: 24 * 2 ** 30, memory_used: 3 * 2 ** 30, load: 18, offered: true }, { name: 'NVIDIA L4', memory: 24 * 2 ** 30, memory_used: 14 * 2 ** 30, load: 71, offered: false, lane: 'shop/train-model' }, { name: 'NVIDIA L4', memory: 24 * 2 ** 30, memory_used: 9 * 2 ** 30, load: 64, offered: false, busy: true }] }, kind: 'server' }, { id: '1122334455667788', name: 'laptop-anna', online: false, seen: 7200, kind: 'machine' }, { id: 'c0ffee0011223344', name: 'cloud-1', online: true, seen: 3, kind: 'server', diff --git a/ui/src/api/mock/stack.ts b/ui/src/api/mock/stack.ts index a7f9d0e4..9c8f02ad 100644 --- a/ui/src/api/mock/stack.ts +++ b/ui/src/api/mock/stack.ts @@ -73,12 +73,14 @@ export class MockStack { buildsActive = 0; failedBuild = new Set(); private lastUsage: UsageReport | null = null; + private gpu?: MockStackSeed['gpu']; onEntryChange: () => void = () => {}; constructor(seed: MockStackSeed) { this.entry = seed.entry; this.view = seed.view; this.previous = seed.previous; + this.gpu = seed.gpu; for (const s of this.view.services) { const lines: string[] = []; if (s.status.state !== 'stopped') { @@ -448,7 +450,10 @@ export class MockStack { const cpu = Math.round(all.reduce((a, b) => a + b.cpu, 0) * 100) / 100; const memory = all.reduce((a, b) => a + b.memory, 0); const logBytes = [...this.logs.values()].reduce((a, b) => a + b.length * 110, 0); - const lanes = [{ name: 'main', cpu, memory, disk: { snapshot: 48_502_117, artifacts: 312_880_640, logs: 1_204_311 + logBytes, volumes: 734_003_200 } }]; + const g = this.gpu; + const gl = g && this.entry.running ? this.step(this.walk('gpu', 45, g.memory * 0.6), true) : undefined; + const gpu = g && gl ? { ...g, load: Math.min(100 * g.count, gl.cpu), memory_used: Math.min(g.memory, gl.memory) } : undefined; + const lanes = [{ name: 'main', cpu, memory, disk: { snapshot: 48_502_117, artifacts: 312_880_640, logs: 1_204_311 + logBytes, volumes: 734_003_200 }, gpu }]; return { at, services, builds, containers, groups, lanes }; } diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 97c6f213..9c43a83e 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -688,7 +688,9 @@ export type BuildsUsage = { name: 'builds'; cpu_time_ms?: number; processes?: nu export type ContainerUsage = { group: string; service: string; history?: Point[] } & Load; export type GroupUsage = { name: string; history?: Point[] } & Load; export type LaneDisk = { snapshot: number; artifacts: number; logs: number; volumes: number | null }; -export type LaneUsage = { name: string; disk?: LaneDisk; history?: Point[] } & Load; +/** A lane's GPUs together (only a lane on a node holds its own): load in percent of one GPU, summed. */ +export type LaneGpu = { count: number; name: string; memory: number; memory_used: number; load: number }; +export type LaneUsage = { name: string; disk?: LaneDisk; gpu?: LaneGpu; history?: Point[] } & Load; export type UsageReport = { at: number; @@ -804,8 +806,8 @@ export type PoolNode = { /** What the machine has, what its lanes use (ADR-0036). */ total?: PoolAmount; used?: PoolAmount; - /** `lane` (`/`): the lane that holds it, then not offered (ADR-0112); older nodes omit it. */ - gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean; lane?: string }[]; + /** `lane` (`/`): the lane that holds it, then not offered (ADR-0112); `busy`: in use on the machine, not offered; older nodes omit them. */ + gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean; lane?: string; busy?: boolean }[]; /** Stopped lanes it keeps for their next start (ADR-0038); older nodes omit it. */ kept?: { lanes: number; bytes: number; /** Of `bytes`, the members' stores of what `prepare` makes (ADR-0062); older nodes omit it. */ store_bytes?: number }; /** How the last update an admin ordered goes (ADR-0039). */ @@ -928,14 +930,14 @@ export type ShareStatus = { /** The devstack the coordinator runs, from its answer to the last report; absent from an older one. */ coordinator?: PoolRelease; /** The machine's GPUs as measured; absent without one, or from an older hub. */ - gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean }[]; + gpus?: { name: string; memory: number; memory_used: number; load: number; offered: boolean; busy?: boolean }[]; /** 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 }; +export type ShareSwitch = { enabled: boolean; max_cpus?: number; max_memory?: number; max_gpus?: number; distro?: string; port?: number }; /** One thing the node agent needs, and whether this machine has it; `optional`: it starts without. `fix` is the command alone, `fix_note` where it runs (absent from an older hub, whose `fix` says both). */ export type ShareCheck = { name: string; ok: boolean; detail: string; fix?: string; fix_note?: string; optional?: boolean }; /** `POST /hub/pool/share/check`: what the node agent would find with a switch, before it is on. */ diff --git a/ui/src/components/LaneUsage.vue b/ui/src/components/LaneUsage.vue index f63633bc..1454d3fc 100644 --- a/ui/src/components/LaneUsage.vue +++ b/ui/src/components/LaneUsage.vue @@ -1,6 +1,7 @@