| 1 | //! cgroup-related code for Linux. |
| 2 | //! |
| 3 | //! For info about cgroups, see things like [the kernel docs](https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html) |
| 4 | //! and [Kubernetes docs](https://kubernetes.io/docs/concepts/architecture/cgroups/#deprecation-of-cgroup-v1). |
| 5 | |
| 6 | use std::{fs, io::BufRead, time::Instant}; |
| 7 | |
| 8 | fn read_u64(path: &str) -> Option<u64> { |
| 9 | fs::read_to_string(path).ok()?.trim().parse().ok() |
| 10 | } |
| 11 | |
| 12 | fn read_stat_key(path: &str, key: &str) -> Option<u64> { |
| 13 | // TODO: Maybe check if this is worth it for the files we read. |
| 14 | let file = fs::File::open(path).ok()?; |
| 15 | for line in std::io::BufReader::new(file).lines().map_while(Result::ok) { |
| 16 | if let Some(rest) = line.strip_prefix(key) |
| 17 | && let Some(val) = rest.strip_prefix(' ') |
| 18 | { |
| 19 | return val.trim().parse().ok(); |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | None |
| 24 | } |
| 25 | |
| 26 | /// Represents cgroup memory limits. |
| 27 | #[derive(Debug)] |
| 28 | pub(crate) enum CgroupMemLimit { |
| 29 | Bytes(u64), |
| 30 | Max, |
| 31 | } |
| 32 | |
| 33 | /// Represents cgroup memory usage data. |
| 34 | #[derive(Debug)] |
| 35 | pub(crate) struct CgroupMemData { |
| 36 | pub used_bytes: u64, |
| 37 | pub limit: Option<CgroupMemLimit>, |
| 38 | } |
| 39 | |
| 40 | /// Gathers memory data from cgroup sources. |
| 41 | #[derive(Default, Debug)] |
| 42 | pub(crate) struct CgroupMemCollector { |
| 43 | pub ram: Option<CgroupMemData>, |
| 44 | pub swap: Option<CgroupMemData>, |
| 45 | } |
| 46 | |
| 47 | /// Computes the cgroup v1 swap limit. Calculated by getting memsw and subtracting the memory limits. |
| 48 | #[inline] |
| 49 | fn cgroup_v1_swap_limit( |
| 50 | memsw_limit: u64, mem_limit: Option<u64>, total_memory: u64, total_swap: u64, |
| 51 | ) -> u64 { |
| 52 | let effective_memsw_limit = memsw_limit.min(total_memory + total_swap); |
| 53 | let effective_mem_limit = mem_limit.map_or(0, |mem_limit| mem_limit.min(total_memory)); |
| 54 | |
| 55 | effective_memsw_limit.saturating_sub(effective_mem_limit) |
| 56 | } |
| 57 | |
| 58 | impl CgroupMemCollector { |
| 59 | /// Refresh the cgroup memory data. |
| 60 | /// |
| 61 | /// Based on [docker's CLI](https://github.com/docker/cli/blob/master/cli/command/container/stats_helpers.go#L254). |
| 62 | pub(crate) fn refresh(&mut self, total_memory: u64, total_swap: u64) { |
| 63 | if !self.try_update_memory_cgroup_v1(total_memory, total_swap) |
| 64 | && !self.try_update_memory_cgroup_v2() |
| 65 | { |
| 66 | self.ram = None; |
| 67 | self.swap = None; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Try and update the memory using cgroup v1 semantics. If successful, returns `true`. |
| 72 | fn try_update_memory_cgroup_v1(&mut self, total_memory: u64, total_swap: u64) -> bool { |
| 73 | if let Some(mem_usage) = read_u64("/sys/fs/cgroup/memory/memory.usage_in_bytes") { |
| 74 | // --- Memory --- |
| 75 | let inactive = |
| 76 | read_stat_key("/sys/fs/cgroup/memory/memory.stat", "total_inactive_file"); |
| 77 | let used_bytes = match inactive { |
| 78 | Some(inactive) if inactive < mem_usage => mem_usage - inactive, |
| 79 | _ => mem_usage, |
| 80 | }; |
| 81 | |
| 82 | // Technically if it's some insanely high value (https://unix.stackexchange.com/a/421182), |
| 83 | // then it's "unlimited", but we can just make it so we take the max of the main and this anyway. |
| 84 | let mem_limit_raw = read_u64("/sys/fs/cgroup/memory/memory.limit_in_bytes"); |
| 85 | let mem_limit = mem_limit_raw.map(CgroupMemLimit::Bytes); |
| 86 | |
| 87 | self.ram = Some(CgroupMemData { |
| 88 | used_bytes, |
| 89 | limit: mem_limit, |
| 90 | }); |
| 91 | |
| 92 | // --- Swap --- |
| 93 | // Since swap is dependent on the normal memory usage, we couple it together. |
| 94 | if let Some(memsw_usage) = read_u64("/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes") |
| 95 | { |
| 96 | let used_bytes = memsw_usage.saturating_sub(mem_usage); |
| 97 | |
| 98 | // Same idea for here. |
| 99 | let swap_limit = read_u64("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") |
| 100 | .map(|memsw_limit| { |
| 101 | cgroup_v1_swap_limit(memsw_limit, mem_limit_raw, total_memory, total_swap) |
| 102 | }) |
| 103 | .map(CgroupMemLimit::Bytes); |
| 104 | |
| 105 | self.swap = Some(CgroupMemData { |
| 106 | used_bytes, |
| 107 | limit: swap_limit, |
| 108 | }); |
| 109 | } |
| 110 | |
| 111 | true |
| 112 | } else { |
| 113 | false |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Try and update the memory using cgroup v2 semantics. If successful, returns `true`. |
| 118 | fn try_update_memory_cgroup_v2(&mut self) -> bool { |
| 119 | let mut could_update = false; |
| 120 | |
| 121 | if let Some(mem_current) = read_u64("/sys/fs/cgroup/memory.current") { |
| 122 | // --- Memory --- |
| 123 | let inactive = read_stat_key("/sys/fs/cgroup/memory.stat", "inactive_file"); |
| 124 | let used_bytes = match inactive { |
| 125 | Some(inactive) if inactive < mem_current => mem_current - inactive, |
| 126 | _ => mem_current, |
| 127 | }; |
| 128 | |
| 129 | let limit = fs::read_to_string("/sys/fs/cgroup/memory.max") |
| 130 | .ok() |
| 131 | .and_then(|s| match s.trim() { |
| 132 | "max" => Some(CgroupMemLimit::Max), |
| 133 | v => v.parse::<u64>().map(CgroupMemLimit::Bytes).ok(), |
| 134 | }); |
| 135 | |
| 136 | self.ram = Some(CgroupMemData { used_bytes, limit }); |
| 137 | |
| 138 | could_update = true; |
| 139 | } |
| 140 | |
| 141 | // --- Swap --- |
| 142 | if let Some(swap_current) = read_u64("/sys/fs/cgroup/memory.swap.current") { |
| 143 | let limit = fs::read_to_string("/sys/fs/cgroup/memory.swap.max") |
| 144 | .ok() |
| 145 | .and_then(|s| match s.trim() { |
| 146 | "max" => Some(CgroupMemLimit::Max), |
| 147 | v => v.parse::<u64>().map(CgroupMemLimit::Bytes).ok(), |
| 148 | }); |
| 149 | |
| 150 | self.swap = Some(CgroupMemData { |
| 151 | used_bytes: swap_current, |
| 152 | limit, |
| 153 | }); |
| 154 | |
| 155 | could_update = true; |
| 156 | } |
| 157 | |
| 158 | could_update |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[inline] |
| 163 | fn parse_cpu_quota(cpu_max: String) -> Option<f64> { |
| 164 | let mut parts = cpu_max.split_whitespace(); |
| 165 | let quota_str = parts.next().unwrap_or(""); |
| 166 | |
| 167 | if quota_str != "max" { |
| 168 | let period: u64 = { |
| 169 | let period_str = parts.next().unwrap_or(""); |
| 170 | |
| 171 | match period_str.parse() { |
| 172 | Ok(v) => v, |
| 173 | Err(_) => return None, |
| 174 | } |
| 175 | }; |
| 176 | |
| 177 | match quota_str.parse::<u64>() { |
| 178 | Ok(quota) if quota > 0 && period > 0 => Some(quota as f64 / period as f64), |
| 179 | _ => None, |
| 180 | } |
| 181 | } else { |
| 182 | None // "max" = unlimited |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// Gathers CPU data from cgroup sources. |
| 187 | #[derive(Default, Debug)] |
| 188 | pub(crate) struct CgroupCpuCollector { |
| 189 | /// A maximum number of CPUs (cores) that can be used, as defined by the cgroup. |
| 190 | pub cpu_quota: Option<f64>, |
| 191 | |
| 192 | /// Computed average CPU usage percent (only set when a quota is active). |
| 193 | pub avg_cpu_percent: Option<f32>, |
| 194 | |
| 195 | /// The previous CPU microsecond time (usage) and when it was last updated. Used to compute average cgroup CPU usage. |
| 196 | prev_cpu: Option<(u64, Instant)>, |
| 197 | } |
| 198 | |
| 199 | impl CgroupCpuCollector { |
| 200 | pub(crate) fn refresh(&mut self) { |
| 201 | if !self.try_update_cpu_cgroup_v1() && !self.try_update_cpu_cgroup_v2() { |
| 202 | self.cpu_quota = None; |
| 203 | self.avg_cpu_percent = None; |
| 204 | self.prev_cpu = None; |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /// Try to update CPU data using cgroup v1 semantics. Returns `true` on success. |
| 209 | fn try_update_cpu_cgroup_v1(&mut self) -> bool { |
| 210 | let quota_raw: i64 = { |
| 211 | let quota_str = match fs::read_to_string("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") { |
| 212 | Ok(s) => s, |
| 213 | Err(_) => return false, |
| 214 | }; |
| 215 | |
| 216 | match quota_str.trim().parse() { |
| 217 | Ok(v) => v, |
| 218 | Err(_) => return false, |
| 219 | } |
| 220 | }; |
| 221 | |
| 222 | self.cpu_quota = if quota_raw > 0 { |
| 223 | let period = read_u64("/sys/fs/cgroup/cpu/cpu.cfs_period_us"); |
| 224 | |
| 225 | period.and_then(|p| { |
| 226 | if p > 0 { |
| 227 | Some(quota_raw as f64 / p as f64) |
| 228 | } else { |
| 229 | None |
| 230 | } |
| 231 | }) |
| 232 | } else { |
| 233 | // If it's less than 0 (-1) then it's representing "unlimited" quota (AKA use the full CPU). |
| 234 | None |
| 235 | }; |
| 236 | |
| 237 | // cpuacct.usage is in nanoseconds; convert to microseconds for consistency with v2 |
| 238 | if let Some(usage_nsec) = read_u64("/sys/fs/cgroup/cpuacct/cpuacct.usage") { |
| 239 | self.try_compute_avg_and_update(usage_nsec / 1000); |
| 240 | } else { |
| 241 | self.avg_cpu_percent = None; |
| 242 | } |
| 243 | |
| 244 | true |
| 245 | } |
| 246 | |
| 247 | /// Try to update CPU data using cgroup v2 semantics. Returns `true` on success. |
| 248 | fn try_update_cpu_cgroup_v2(&mut self) -> bool { |
| 249 | let cpu_max = match fs::read_to_string("/sys/fs/cgroup/cpu.max") { |
| 250 | Ok(s) => s, |
| 251 | Err(_) => return false, |
| 252 | }; |
| 253 | |
| 254 | self.cpu_quota = parse_cpu_quota(cpu_max); |
| 255 | |
| 256 | // cpu.stat usage_usec is in microseconds |
| 257 | if let Some(current_microseconds) = read_stat_key("/sys/fs/cgroup/cpu.stat", "usage_usec") { |
| 258 | self.try_compute_avg_and_update(current_microseconds); |
| 259 | } else { |
| 260 | self.avg_cpu_percent = None; |
| 261 | } |
| 262 | |
| 263 | true |
| 264 | } |
| 265 | |
| 266 | /// Try and compute average CPU usage based on the current microseconds. Note that this requires _two_ invocations |
| 267 | /// to compute a value, as the first invocation just sets the baseline for the next CPU time and timestamp to |
| 268 | /// compare with. |
| 269 | fn try_compute_avg_and_update(&mut self, current_microseconds: u64) { |
| 270 | let now = Instant::now(); |
| 271 | |
| 272 | self.avg_cpu_percent = if let (Some(cpu_quota), Some(prev_cpu)) = |
| 273 | (self.cpu_quota, self.prev_cpu) |
| 274 | { |
| 275 | let (prev_microseconds, prev_time) = prev_cpu; |
| 276 | |
| 277 | let elapsed_microseconds = now.duration_since(prev_time).as_micros() as u64; |
| 278 | if elapsed_microseconds > 0 && cpu_quota > 0.0 { |
| 279 | let delta = current_microseconds.saturating_sub(prev_microseconds); |
| 280 | let pct = (delta as f64 / (elapsed_microseconds as f64 * cpu_quota) * 100.0) as f32; |
| 281 | |
| 282 | Some(pct.clamp(0.0, 100.0)) |
| 283 | } else { |
| 284 | None |
| 285 | } |
| 286 | } else { |
| 287 | None |
| 288 | }; |
| 289 | |
| 290 | self.prev_cpu = Some((current_microseconds, now)); |
| 291 | } |
| 292 | } |