Stats: report cgroup CPU throttling periods and time in container stats (#537)

Co-authored-by: grvwy <147989282+grvwy@users.noreply.github.com>
This commit is contained in:
Precious Okwuandgrvwy authored and Precious Okwu committed 2026-11-23 19:43:17 +01:00
1 parent 41c775597f
commit 3aa0e208c8
7 files changed
+128 -4

No files matched your search

+31 -1
View File
@@ -67,8 +67,20 @@ pub fn freeze(dir: &Path, frozen: bool) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::TimedOut, "the container did not freeze in time"))
}
fn keyed_opt(text: &str, key: &str) -> Option<u64> {
text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok())
}
fn keyed(text: &str, key: &str) -> u64 {
text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok()).unwrap_or(0)
keyed_opt(text, key).unwrap_or(0)
}
/// CPU throttling counters from `cpu.stat`: `(nr_periods, nr_throttled, throttled_usec)`.
/// cgroup v2 reports `throttled_usec` in microseconds; cgroup v1 reports
/// `throttled_time` in nanoseconds.
fn cpu_throttling(cpu_stat: &str) -> (u64, u64, u64) {
let throttled_usec = keyed_opt(cpu_stat, "throttled_usec").unwrap_or_else(|| keyed(cpu_stat, "throttled_time") / 1000);
(keyed(cpu_stat, "nr_periods"), keyed(cpu_stat, "nr_throttled"), throttled_usec)
}
/// What the cgroup holds and cannot give back, in bytes: anonymous, shared
@@ -114,6 +126,7 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result<ContainerStats> {
let read = |f: &str| fs::read_to_string(dir.join(f)).unwrap_or_default();
let cpu = read("cpu.stat");
let mem_stat = read("memory.stat");
let (cpu_periods, cpu_throttled_periods, cpu_throttled_usec) = cpu_throttling(&cpu);
let mut s = ContainerStats {
read_ns: sys::boottime_ns(),
mem_current: read("memory.current").trim().parse().unwrap_or(0),
@@ -122,6 +135,9 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result<ContainerStats> {
cpu_usage_usec: keyed(&cpu, "usage_usec"),
cpu_user_usec: keyed(&cpu, "user_usec"),
cpu_system_usec: keyed(&cpu, "system_usec"),
cpu_periods,
cpu_throttled_periods,
cpu_throttled_usec,
pids: read("pids.current").trim().parse().unwrap_or(0),
// SAFETY: sysconf has no preconditions.
online_cpus: unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }.max(1) as u32,
@@ -349,6 +365,20 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn cpu_throttling_reads_v2_and_v1_formats() {
let v2 = "usage_usec 12345\nuser_usec 10000\nsystem_usec 2345\nnr_periods 12\nnr_throttled 5\nthrottled_usec 43210\n";
assert_eq!(cpu_throttling(v2), (12, 5, 43_210));
let v2_zero = "usage_usec 500\nnr_periods 4\nnr_throttled 0\nthrottled_usec 0\n";
assert_eq!(cpu_throttling(v2_zero), (4, 0, 0));
let v1 = "nr_periods 12\nnr_throttled 5\nthrottled_time 43210000\n";
assert_eq!(cpu_throttling(v1), (12, 5, 43_210));
assert_eq!(cpu_throttling(""), (0, 0, 0));
}
#[test]
fn apply_limits_errors_when_cgroup_dir_is_missing() {
let missing = std::env::temp_dir().join(format!("kiri-cg-missing-{}", std::process::id()));
+39 -2
View File
@@ -627,6 +627,9 @@ pub struct ContainerStats {
pub tx_packets: u64,
pub io_read_bytes: u64,
pub io_write_bytes: u64,
pub cpu_periods: u64,
pub cpu_throttled_periods: u64,
pub cpu_throttled_usec: u64,
}
fn put_container_stats(o: &mut Vec<u8>, s: &ContainerStats) {
@@ -638,10 +641,13 @@ fn put_container_stats(o: &mut Vec<u8>, s: &ContainerStats) {
for v in [s.rx_bytes, s.rx_packets, s.tx_bytes, s.tx_packets, s.io_read_bytes, s.io_write_bytes] {
put_u64(o, v);
}
for v in [s.cpu_periods, s.cpu_throttled_periods, s.cpu_throttled_usec] {
put_u64(o, v);
}
}
fn read_container_stats(r: &mut Reader<'_>) -> Result<ContainerStats, DecodeError> {
Ok(ContainerStats {
let mut stats = ContainerStats {
read_ns: r.u64()?,
mem_current: r.u64()?,
mem_max: r.u64()?,
@@ -658,7 +664,15 @@ fn read_container_stats(r: &mut Reader<'_>) -> Result<ContainerStats, DecodeErro
tx_packets: r.u64()?,
io_read_bytes: r.u64()?,
io_write_bytes: r.u64()?,
})
..Default::default()
};
// Older agents end the message after the block I/O counters.
if r.remaining() != 0 {
stats.cpu_periods = r.u64()?;
stats.cpu_throttled_periods = r.u64()?;
stats.cpu_throttled_usec = r.u64()?;
}
Ok(stats)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1541,6 +1555,29 @@ mod tests {
assert_eq!(decode(&buf).unwrap(), m);
}
#[test]
fn cpu_throttling_stats() {
let stats = ContainerStats {
cpu_periods: 8,
cpu_throttled_periods: 3,
cpu_throttled_usec: 1200,
..Default::default()
};
round(Msg::ContainerStats(stats));
// An older agent omits the three trailing throttling words.
let mut frame = Vec::new();
Msg::ContainerStats(stats).encode(&mut frame);
let mut old = frame[..frame.len() - 24].to_vec();
let len = (old.len() - 4) as u32;
old[..4].copy_from_slice(&len.to_le_bytes());
assert_eq!(decode(&old).unwrap(), Msg::ContainerStats(ContainerStats::default()));
// A truncated trailing section is rejected rather than partially decoded.
let mut partial = frame[..frame.len() - 8].to_vec();
let len = (partial.len() - 4) as u32;
partial[..4].copy_from_slice(&len.to_le_bytes());
assert_eq!(decode(&partial), Err(DecodeError::Truncated));
}
#[test]
fn round_trip() {
round(Msg::Hello(Hello { protocol: PROTOCOL, init_start_ns: 1, ready_ns: 2, mem_total_kib: 3, mem_available_kib: 4 }));
+41 -1
View File
@@ -78,7 +78,11 @@ fn stats_json(id: &str, name: &str, s: &kiri_proto::ContainerStats, pre: Option<
"cpu_usage": {"total_usage": s.cpu_usage_usec * 1000, "usage_in_kernelmode": s.cpu_system_usec * 1000, "usage_in_usermode": s.cpu_user_usec * 1000},
"system_cpu_usage": s.system_ticks * TICK_NS,
"online_cpus": s.online_cpus,
"throttling_data": {"periods": 0, "throttled_periods": 0, "throttled_time": 0},
"throttling_data": {
"periods": s.cpu_periods,
"throttled_periods": s.cpu_throttled_periods,
"throttled_time": s.cpu_throttled_usec.saturating_mul(1000),
},
})
};
let read = time::rfc3339(std::time::SystemTime::now());
@@ -793,3 +797,39 @@ mod disk_usage_tests {
assert_eq!((du.layers.len(), du.containers.len(), du.volumes.len()), (1, 1, 1));
}
}
#[cfg(test)]
mod stats_tests {
use super::stats_json;
use kiri_proto::ContainerStats;
use serde_json::json;
#[test]
fn throttling_data_matches_cgroup_counters_in_docker_units() {
let prev = ContainerStats {
cpu_periods: 4,
cpu_throttled_periods: 2,
cpu_throttled_usec: 1000,
..Default::default()
};
let sample = ContainerStats {
cpu_periods: 11,
cpu_throttled_periods: 9,
cpu_throttled_usec: 4321,
..Default::default()
};
let value = stats_json("id", "work", &sample, Some(&prev), 0);
assert_eq!(
value["cpu_stats"]["throttling_data"],
json!({
"periods": 11, "throttled_periods": 9, "throttled_time": 4_321_000,
})
);
assert_eq!(
value["precpu_stats"]["throttling_data"],
json!({
"periods": 4, "throttled_periods": 2, "throttled_time": 1_000_000,
})
);
}
}
+6
View File
@@ -13,6 +13,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug
## Fixes
### #537 Engine: report cgroup CPU throttling in container stats (unreleased)
- Fixes: no issue
- Caused: none known
- Caused by: -
- Check: `stats-cpu-throttling`
### #779 Bench: fail the API benchmark on curl errors instead of timing failed runs (unreleased)
- Fixes: #669 `bench/api.sh` passes `--ignore-failure` to `hyperfine` on `api-exec`, masking curl failures and recording time-to-failure as valid timings
- Caused: none known
+8
View File
@@ -1655,6 +1655,14 @@ t oom-kill "137" bash -c "$D run --rm --memory 32m alpine sh -c 'tail /dev/zero'
t stats "128MiB" $D stats --no-stream --format '{{.MemUsage}}' lim
t stats-pids "PIDS" $D stats --no-stream lim
t stats-stream "lim" bash -c "perl -e 'alarm 3; exec @ARGV' $D stats --format '{{.Name}}' lim 2>/dev/null | head -1"
# Container stats carry cgroup CPU throttling counters in Docker units (#537).
t stats-cpu-throttling "ok" bash -c "
$D rm -f lim-thr >/dev/null 2>&1
id=\$($D run -d --name lim-thr --cpus 0.1 alpine sh -c 'i=0; while [ \$i -lt 200000 ]; do i=\$((i+1)); done; sleep 10')
out=\$(curl -s --unix-socket $(printf %q "$SOCK") \"http://d/v1.47/containers/\$id/stats?stream=false\" | python3 -c 'import json, sys; td = json.load(sys.stdin)[\"cpu_stats\"][\"throttling_data\"]; print(\"ok\" if td[\"periods\"] > 0 and td[\"throttled_periods\"] > 0 and td[\"throttled_time\"] > 0 else td)')
$D rm -f lim-thr >/dev/null 2>&1
echo \"\$out\"
"
t top "nginx: master process" $D top lim
t top-ps-titles "PPID" $D top lim
# ps_args picks ps's columns, as Docker runs ps with them (#348).
+2
View File
@@ -918,6 +918,8 @@ t inspect-exposed-udp '{"132/sctp":{},"53/tcp":{},"53/udp":{},"5353/udp":{}} {"1
# --memory gets as much swap again by default, and --memory-swap is applied to
# memory.swap.max on run and update, as on Docker (#523, #690).
t limit-memory-swap "def=268435456:ok custom=201326592:ok zero=134217728:ok unlim=-1:ok none=0:ok upd=335544320:ok cpus=335544320:ok uunlim=-1:ok umem=-1:ok bad=ok:ok:ok" "docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 lhswu >/dev/null 2>&1; sw() { docker exec \"\$1\" sh -c \"[ ! -e /sys/fs/cgroup/memory.swap.max ] && echo ok || { v=\\\$(cat /sys/fs/cgroup/memory.swap.max); [ \\\"\\\$v\\\" = \\\"\$2\\\" ] && echo ok || echo bad:\\\$v; }\"; }; docker run -d --name lhsw0 alpine sleep 60 >/dev/null; docker run -d --name lhsw1 --memory 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw2 --memory 128m --memory-swap 192m alpine sleep 60 >/dev/null; docker run -d --name lhsw3 --memory 128m --memory-swap 128m alpine sleep 60 >/dev/null; docker run -d --name lhsw4 --memory 128m --memory-swap -1 alpine sleep 60 >/dev/null; none=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw0):\$(sw lhsw0 max); def=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); custom=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw2):\$(sw lhsw2 67108864); zero=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw3):\$(sw lhsw3 0); unlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw4):\$(sw lhsw4 max); docker update --memory 512m lhsw1 2>&1 | grep -q 'Memory limit should be smaller than already set memoryswap limit' && b1=ok || b1=bad; docker create --memory-swap 64m alpine true 2>&1 | grep -q 'You should always set the Memory limit' && b2=ok || b2=bad; docker create --memory 128m --memory-swap 64m alpine true 2>&1 | grep -q 'Minimum memoryswap limit' && b3=ok || b3=bad; docker update --memory 192m --memory-swap 320m lhsw1 >/dev/null; upd=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --cpus 1 lhsw1 >/dev/null; cpus=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 134217728); docker update --memory-swap -1 lhsw1 >/dev/null; uunlim=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker update --memory 256m lhsw1 >/dev/null; umem=\$(docker inspect -f '{{.HostConfig.MemorySwap}}' lhsw1):\$(sw lhsw1 max); docker rm -f lhsw0 lhsw1 lhsw2 lhsw3 lhsw4 >/dev/null 2>&1; echo \"def=\$def custom=\$custom zero=\$zero unlim=\$unlim none=\$none upd=\$upd cpus=\$cpus uunlim=\$uunlim umem=\$umem bad=\$b1:\$b2:\$b3\""
# Container stats carry cgroup CPU throttling counters in Docker units (#537).
t stats-cpu-throttling "ok" "docker rm -f lhthr >/dev/null 2>&1; id=\$(docker run -d --name lhthr --cpus 0.1 alpine sh -c 'i=0; while [ \$i -lt 200000 ]; do i=\$((i+1)); done; sleep 10'); out=\$(curl -s --unix-socket /root/.kiri/run/docker.sock \"http://d/v1.47/containers/\$id/stats?stream=false\" | python3 -c 'import json, sys; td = json.load(sys.stdin)[\"cpu_stats\"][\"throttling_data\"]; print(\"ok\" if td[\"periods\"] > 0 and td[\"throttled_periods\"] > 0 and td[\"throttled_time\"] > 0 else td)'); docker rm -f lhthr >/dev/null 2>&1; echo \"\$out\""
$D rm -f "$N" >/dev/null
# An engine in a user namespace (nested Docker, Sysbox, Coder, CI; #597),
# where the kernel refuses mknod of a device and raising nofile past the
+1
View File
@@ -258,3 +258,4 @@ limit-memory-swap-inspect #523 containers with --memory reported HostConfig.Memo
limit-memory-swap-refused #523 invalid --memory-swap values on create and update were accepted instead of refused with Docker's error messages (#690)
limit-memory-swap-update #523 docker update dropped --memory-swap or failed to keep an existing custom or unlimited swap limit (#690)
limit-memory-swap #523 every container with --memory was pinned to memory.swap.max = 0 instead of getting Docker's 2x default or --memory-swap (#690)
stats-cpu-throttling #537 container stats always reported zero for cpu_stats.throttling_data even when a CPU-limited container was throttled
Can't render this file because it contains an unexpected character in line 2 and column 52.