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
251 changes: 244 additions & 7 deletions crates/axe-core/src/node_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
//! previous sample ([`crate::admission::cpu_busy_percent`]); the first sample
//! has none;
//! - memory: used is `MemTotal - MemAvailable`;
//! - capacity ([`Cgroup`]): cores are the host's online CPUs, or the
//! tightest cgroup v2 `cpu.max` quota on the node's own cgroup path (a pod
//! with a CPU limit). Under a CPU limit, cores used are that cgroup's
//! `cpu.stat` `usage_usec` per wall second and the CPU percent is of the
//! limit; otherwise cores used are the busy share times the host cores.
//! Under the tightest `memory.max`, memory total is that limit and used is
//! its `memory.current` less `inactive_file` (the working set);
//! - load: the 1, 5 and 15 minute averages of `/proc/loadavg`;
//! - disk: free (`f_bavail`) and total of the filesystem holding the run
//! workspaces (`Config::run_root`, or its nearest existing parent).
Expand Down Expand Up @@ -130,8 +137,16 @@ impl Runs {
pub struct Sample {
#[serde(default)]
pub at: i64,
/// Busy CPU percent since the previous sample; null on the first.
/// Busy CPU percent of `cpu_cores` since the previous sample; null on
/// the first.
pub cpu_percent: Option<f64>,
/// CPU capacity in cores: a cgroup CPU limit, else the host's online
/// CPUs. Null from an older node.
#[serde(default)]
pub cpu_cores: Option<f64>,
/// Cores in use since the previous sample; null on the first.
#[serde(default)]
pub cpu_used_cores: Option<f64>,
pub mem_used_bytes: Option<u64>,
pub mem_total_bytes: Option<u64>,
pub load1: Option<f64>,
Expand Down Expand Up @@ -160,6 +175,26 @@ pub struct Readings {
pub load: Option<[f64; 3]>,
/// Free and total bytes.
pub disk: Option<(u64, u64)>,
/// The host's online CPUs.
pub host_cores: Option<u32>,
/// Limits on the node's own cgroup path.
pub cgroup: Cgroup,
/// When the readings were taken, for the cgroup CPU window.
pub at: Option<std::time::Instant>,
}

/// The tightest cgroup v2 limits on the node's own cgroup path and the
/// usage of the cgroup that sets each; `None` where unlimited or unreadable.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Cgroup {
/// `cpu.max` quota over period, in cores.
pub cpu_limit_cores: Option<f64>,
/// `cpu.stat` `usage_usec` of the limiting cgroup.
pub cpu_usage_usec: Option<u64>,
/// `memory.max`, bytes.
pub mem_limit_bytes: Option<u64>,
/// `memory.current` less `inactive_file` of the limiting cgroup, bytes.
pub mem_used_bytes: Option<u64>,
}

/// How often the node re-reads the host CLI's version.
Expand All @@ -171,6 +206,8 @@ pub const CLI_VERSION_EVERY: std::time::Duration = std::time::Duration::from_sec
pub struct Sampler {
disk_path: PathBuf,
prev_cpu: Option<CpuTimes>,
/// The cgroup CPU usage and when it was read.
prev_cg: Option<(u64, std::time::Instant)>,
cli: Option<(std::time::Instant, Option<String>)>,
}

Expand All @@ -179,6 +216,7 @@ impl Sampler {
Sampler {
disk_path,
prev_cpu: None,
prev_cg: None,
cli: None,
}
}
Expand All @@ -202,23 +240,54 @@ impl Sampler {
s
}

/// A sample from `r`: CPU is the busy share since the previous readings.
/// A sample from `r`: CPU is the busy share since the previous readings,
/// of the cgroup CPU limit when there is one.
pub fn build(&mut self, r: Readings, runs: Runs) -> Sample {
let cpu_percent = match (self.prev_cpu, r.cpu) {
let busy = match (self.prev_cpu, r.cpu) {
(Some(from), Some(to)) => admission::cpu_busy_percent(&from, &to),
_ => None,
};
if r.cpu.is_some() {
self.prev_cpu = r.cpu;
}
let cg = r.cgroup;
let (cpu_cores, cpu_used_cores) = match cg.cpu_limit_cores {
Some(limit) => {
let used = match (self.prev_cg, cg.cpu_usage_usec, r.at) {
(Some((u0, t0)), Some(u1), Some(t1)) if t1 > t0 && u1 >= u0 => {
let wall = t1.duration_since(t0).as_micros() as f64;
Some(((u1 - u0) as f64 / wall).min(limit))
}
_ => None,
};
(Some(limit), used)
}
None => {
let host = r.host_cores.map(f64::from);
(host, busy.zip(host).map(|(b, h)| b / 100.0 * h))
}
};
self.prev_cg = cg.cpu_usage_usec.zip(r.at);
let cpu_percent = match cg.cpu_limit_cores {
Some(limit) => cpu_used_cores.map(|u| 100.0 * u / limit),
None => busy,
};
let kib = |v: u64| v.saturating_mul(1024);
let (mem_used_bytes, mem_total_bytes) = match cg.mem_limit_bytes {
Some(limit) => (cg.mem_used_bytes, Some(limit)),
None => (
r.memory
.map(|m| kib(m.total_kib.saturating_sub(m.available_kib))),
r.memory.map(|m| kib(m.total_kib)),
),
};
Sample {
at: crate::remote::epoch(),
cpu_percent,
mem_used_bytes: r
.memory
.map(|m| kib(m.total_kib.saturating_sub(m.available_kib))),
mem_total_bytes: r.memory.map(|m| kib(m.total_kib)),
cpu_cores,
cpu_used_cores,
mem_used_bytes,
mem_total_bytes,
load1: r.load.map(|l| l[0]),
load5: r.load.map(|l| l[1]),
load15: r.load.map(|l| l[2]),
Expand Down Expand Up @@ -270,7 +339,90 @@ pub fn read_host(disk_path: &Path) -> Readings {
memory: read("/proc/meminfo").and_then(|t| admission::parse_meminfo(&t).ok()),
load: read("/proc/loadavg").and_then(|t| parse_loadavg(&t).ok()),
disk: disk_stats(disk_path).ok(),
host_cores: host_cores(),
cgroup: read_cgroup(),
at: Some(std::time::Instant::now()),
}
}

/// Online CPUs (`sysconf(_SC_NPROCESSORS_ONLN)`).
fn host_cores() -> Option<u32> {
// SAFETY: sysconf has no preconditions.
let n = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) };
(n > 0).then(|| n.min(u32::MAX as libc::c_long) as u32)
}

/// The tightest limits on this process's cgroup v2 path (`/proc/self/cgroup`
/// `0::<path>` under `/sys/fs/cgroup`), walking up to the root.
pub fn read_cgroup() -> Cgroup {
let Some(own) = std::fs::read_to_string("/proc/self/cgroup")
.ok()
.and_then(|t| parse_self_cgroup(&t))
else {
return Cgroup::default();
};
let root = Path::new("/sys/fs/cgroup");
let read = |dir: &Path, f: &str| std::fs::read_to_string(dir.join(f)).ok();
let mut out = Cgroup::default();
let mut cpu_dir: Option<PathBuf> = None;
let mut mem_dir: Option<PathBuf> = None;
for rel in Path::new(own.trim_start_matches('/')).ancestors() {
let dir = root.join(rel);
if let Some(c) = read(&dir, "cpu.max").and_then(|t| parse_cpu_max(&t)) {
if out.cpu_limit_cores.is_none_or(|l| c < l) {
out.cpu_limit_cores = Some(c);
cpu_dir = Some(dir.clone());
}
}
if let Some(m) = read(&dir, "memory.max").and_then(|t| parse_memory_max(&t)) {
if out.mem_limit_bytes.is_none_or(|l| m < l) {
out.mem_limit_bytes = Some(m);
mem_dir = Some(dir.clone());
}
}
}
if let Some(dir) = cpu_dir {
out.cpu_usage_usec = read(&dir, "cpu.stat").and_then(|t| stat_field(&t, "usage_usec"));
}
if let Some(dir) = mem_dir {
out.mem_used_bytes = read(&dir, "memory.current")
.and_then(|t| t.trim().parse::<u64>().ok())
.map(|cur| {
let inactive = read(&dir, "memory.stat")
.and_then(|t| stat_field(&t, "inactive_file"))
.unwrap_or(0);
cur.saturating_sub(inactive)
});
}
out
}

/// The cgroup v2 path of a `/proc/self/cgroup` (`0::/a/b`).
pub fn parse_self_cgroup(text: &str) -> Option<String> {
text.lines()
.find_map(|l| l.strip_prefix("0::"))
.map(|p| p.trim().to_string())
}

/// Cores a `cpu.max` (`<quota|max> <period>`) allows; `None` when unlimited.
pub fn parse_cpu_max(text: &str) -> Option<f64> {
let mut it = text.split_whitespace();
let quota: f64 = it.next()?.parse().ok()?;
let period: f64 = it.next().unwrap_or("100000").parse().ok()?;
(quota > 0.0 && period > 0.0).then(|| quota / period)
}

/// A `memory.max` in bytes; `None` when `max`.
pub fn parse_memory_max(text: &str) -> Option<u64> {
text.trim().parse().ok().filter(|v| *v > 0)
}

/// A `<key> <value>` line of `cpu.stat` or `memory.stat`.
pub fn stat_field(text: &str, key: &str) -> Option<u64> {
text.lines().find_map(|l| {
let (k, v) = l.split_once(' ')?;
(k == key).then(|| v.trim().parse().ok()).flatten()
})
}

/// The three load averages of `/proc/loadavg`.
Expand Down Expand Up @@ -317,9 +469,12 @@ fn finite(v: Option<f64>) -> Option<f64> {
/// Stores `s` from node `node` at server time `at` and recomputes its
/// rollup bucket.
pub fn record(conn: &Connection, node: &str, at: i64, s: Sample, cfg: &Cfg) -> Result<()> {
let cpu_cores = finite(s.cpu_cores).filter(|c| *c > 0.0 && *c <= 65536.0);
let mut s = Sample {
at,
cpu_percent: finite(s.cpu_percent).map(|v| v.min(100.0)),
cpu_used_cores: finite(s.cpu_used_cores).map(|v| cpu_cores.map_or(v, |c| v.min(c))),
cpu_cores,
load1: finite(s.load1),
load5: finite(s.load5),
load15: finite(s.load15),
Expand Down Expand Up @@ -622,6 +777,7 @@ mod tests {
memory: Some(mem),
load: Some([1.0, 2.0, 3.0]),
disk: Some((10, 20)),
..Readings::default()
},
runs(&[("harvis", 2)], &[]),
);
Expand Down Expand Up @@ -661,6 +817,74 @@ mod tests {
assert_eq!(fourth.cpu_percent, Some(50.0));
}

#[test]
fn host_cpu_is_busy_share_times_host_cores() {
let mut s = Sampler::new("/".into());
let r = |c| Readings {
cpu: Some(c),
host_cores: Some(8),
..Readings::default()
};
let first = s.build(r(cpu(100, 100)), Runs::default());
assert_eq!((first.cpu_cores, first.cpu_used_cores), (Some(8.0), None));
// 30 busy of 40 ticks: 6 of 8 cores.
let second = s.build(r(cpu(130, 110)), Runs::default());
assert_eq!(second.cpu_percent, Some(75.0));
assert_eq!(second.cpu_used_cores, Some(6.0));
}

#[test]
fn cgroup_limits_set_capacity_and_usage() {
let mut s = Sampler::new("/".into());
let t0 = std::time::Instant::now();
let r = |usage: u64, secs: u64| Readings {
cpu: Some(cpu(100 + secs, 100)),
memory: Some(Memory {
available_kib: 1024,
total_kib: 64 * 1024 * 1024,
}),
host_cores: Some(32),
cgroup: Cgroup {
cpu_limit_cores: Some(2.0),
cpu_usage_usec: Some(usage),
mem_limit_bytes: Some(4 << 30),
mem_used_bytes: Some(1 << 30),
},
at: Some(t0 + std::time::Duration::from_secs(secs)),
..Readings::default()
};
let first = s.build(r(5_000_000, 0), Runs::default());
assert_eq!((first.cpu_cores, first.cpu_used_cores), (Some(2.0), None));
assert_eq!(first.cpu_percent, None);
assert_eq!(
(first.mem_used_bytes, first.mem_total_bytes),
(Some(1 << 30), Some(4 << 30)),
"the cgroup's working set of its limit, not the host's"
);
// 15 s of CPU over 10 s of wall: 1.5 of 2 cores.
let second = s.build(r(20_000_000, 10), Runs::default());
assert_eq!(second.cpu_used_cores, Some(1.5));
assert_eq!(second.cpu_percent, Some(75.0));
}

#[test]
fn cgroup_files_parse() {
assert_eq!(
parse_self_cgroup("0::/kubepods/burstable/pod1/abc\n").as_deref(),
Some("/kubepods/burstable/pod1/abc")
);
assert_eq!(parse_self_cgroup("1:cpu:/x\n"), None, "cgroup v1");
assert_eq!(parse_cpu_max("max 100000\n"), None);
assert_eq!(parse_cpu_max("250000 100000\n"), Some(2.5));
assert_eq!(parse_cpu_max("50000\n"), Some(0.5));
assert_eq!(parse_memory_max("max\n"), None);
assert_eq!(parse_memory_max("4294967296\n"), Some(4 << 30));
let stat = "usage_usec 189328\nuser_usec 17432\ninactive_file 4096\n";
assert_eq!(stat_field(stat, "usage_usec"), Some(189328));
assert_eq!(stat_field(stat, "inactive_file"), Some(4096));
assert_eq!(stat_field(stat, "user"), None);
}

#[test]
fn disk_stats_walks_up_to_an_existing_parent() {
let dir = tempfile::tempdir().unwrap();
Expand Down Expand Up @@ -737,6 +961,19 @@ mod tests {
let last = latest(&c).unwrap().unwrap();
assert_eq!(last.cpu_percent, Some(100.0));
assert_eq!((last.load1, last.load5), (None, None));
let mut s = sample(50.0, 1);
s.cpu_cores = Some(4.0);
s.cpu_used_cores = Some(9.0);
record(&c, "n1", 1001, s, &cfg()).unwrap();
let last = latest(&c).unwrap().unwrap();
assert_eq!(
(last.cpu_cores, last.cpu_used_cores),
(Some(4.0), Some(4.0))
);
let mut s = sample(50.0, 1);
s.cpu_cores = Some(f64::INFINITY);
record(&c, "n1", 1002, s, &cfg()).unwrap();
assert_eq!(latest(&c).unwrap().unwrap().cpu_cores, None);
}

#[test]
Expand Down
6 changes: 4 additions & 2 deletions docs/user/concepts/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,14 @@ episode, naming the cause (`server.rs` `watch_pause`). A draining node reports
waits one CPU window, reported as `node restarting`, which is not a pressure
pause and wakes no bot.

**Node observability.** The node samples host CPU, memory, load, the run
**Node observability.** The node samples CPU (cores in use of its capacity:
a cgroup CPU limit, as in a pod, else the host's cores), memory (used of a
cgroup memory limit when set, else of the host total), load, the run
volume's free disk and its running runs by kind (task runs per project, bot
runs per bot, services and scheduled service runs per bot) and sends them
with its admission report; the server keeps raw samples and 5-minute rollups,
pruned hourly (`[node_metrics]`, `node_metrics.rs`). The web Node view
charts them in the viewer's local time (`GET /api/node/metrics`) and the Telegram owner command `/node`
shows CPU in cores and memory in GiB and charts them in the viewer's local time (`GET /api/node/metrics`) and the Telegram owner command `/node`
shows the latest sample.

**Rollouts.** SIGUSR1 starts a bounded drain: nothing new is admitted, and
Expand Down
Loading
Loading