Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions crates/devstack-daemon/src/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<ExternalGpu>>,
}

/// 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)]
Expand Down
106 changes: 103 additions & 3 deletions crates/devstack-daemon/src/usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,28 @@ pub struct LaneEntry {
pub load: Load,
#[serde(skip_serializing_if = "Option::is_none")]
pub disk: Option<Disk>,
/// 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<LaneGpu>,
}

/// 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,
Expand Down Expand Up @@ -221,8 +241,11 @@ impl Series {

#[derive(Default)]
struct Inner {
/// `service:<name>`, `build`, `container:<group>/<service>`.
/// `service:<name>`, `build`, `container:<group>/<service>`, `gpu`.
series: BTreeMap<String, Series>,
/// 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<String>,
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Load>) -> Option<LaneGpu> {
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]) {
Expand Down Expand Up @@ -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();
Expand Down
22 changes: 19 additions & 3 deletions crates/devstack-hub/src/nodehost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -71,6 +72,9 @@ pub struct Switch {
pub max_cpus: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_memory: Option<u64>,
/// The most GPUs they hold together; `0`: the owner keeps them all.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_gpus: Option<u32>,
/// Windows: the WSL distribution the agent runs in.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub distro: Option<String>,
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
};
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions crates/devstack-hub/src/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 36 additions & 9 deletions crates/devstack-node/src/laneinfra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
}
}
Expand Down Expand Up @@ -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<String, Vec<Container>>,
load: &BTreeMap<String, Load>,
gpus: Option<&[crate::share::Gpu]>,
at: u128,
) -> serde_json::Value {
let mut out = base.clone();
Expand Down Expand Up @@ -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
};
Expand Down Expand Up @@ -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(&current(&base, &found, &load, now)).expect("infra serialises");
let json = serde_json::to_vec_pretty(&current(&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)
})
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down
Loading
Loading