Skip to main content

alpha2_os/
memory.rs

1//! How much memory the machine has, and how much this process may use under a container or job
2//! limit.
3
4#[cfg(any(target_os = "linux", target_os = "android"))]
5use std::path::Path;
6
7/// The machine's memory and this process's limit. Unavailable figures are `None`.
8#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
9pub struct MemoryCapacity {
10    /// Physical memory installed.
11    pub physical_bytes: Option<u64>,
12    /// Memory available without paging: `MemAvailable` on Linux, free plus inactive plus
13    /// purgeable pages on macOS, `ullAvailPhys` on Windows, what the app may still allocate on iOS.
14    pub available_bytes: Option<u64>,
15    /// The lowest of a cgroup or job limit and the physical total.
16    pub limit_bytes: Option<u64>,
17    /// What set `limit_bytes`: `cgroup-v2`, `cgroup-v1`, `job`, `app` (the per-app limit on
18    /// iOS) or `physical`.
19    pub limit_source: &'static str,
20    /// The working set under a cgroup limit ([`CgroupMemory::working_set_bytes`]); `None` for
21    /// physical and job limits.
22    pub used_in_limit_bytes: Option<u64>,
23    /// What the kernel charges against a cgroup limit, file page cache included.
24    pub charged_in_limit_bytes: Option<u64>,
25}
26
27impl MemoryCapacity {
28    /// The limit, else the physical total.
29    #[must_use]
30    pub fn effective_limit(&self) -> Option<u64> {
31        match (self.limit_bytes, self.physical_bytes) {
32            (Some(limit), Some(physical)) => Some(limit.min(physical)),
33            (limit, physical) => limit.or(physical),
34        }
35    }
36
37    /// The lower of available memory and the headroom left under the limit.
38    #[must_use]
39    pub fn headroom(&self) -> Option<u64> {
40        let in_limit = self
41            .limit_bytes
42            .zip(self.used_in_limit_bytes)
43            .map(|(limit, used)| limit.saturating_sub(used));
44        match (self.available_bytes, in_limit) {
45            (Some(available), Some(in_limit)) => Some(available.min(in_limit)),
46            (available, in_limit) => available.or(in_limit),
47        }
48    }
49}
50
51/// The machine's memory and this process's limit, read now.
52#[must_use]
53pub fn memory_capacity() -> MemoryCapacity {
54    #[cfg(any(target_os = "linux", target_os = "android"))]
55    {
56        memory_capacity_at(Path::new("/"))
57    }
58    #[cfg(any(target_vendor = "apple", windows))]
59    {
60        crate::platform::memory_capacity()
61    }
62    #[cfg(not(any(
63        target_os = "linux",
64        target_os = "android",
65        target_vendor = "apple",
66        windows
67    )))]
68    {
69        MemoryCapacity {
70            limit_source: "physical",
71            ..MemoryCapacity::default()
72        }
73    }
74}
75
76/// [`memory_capacity`] with `root` standing in for `/`.
77#[cfg(any(target_os = "linux", target_os = "android"))]
78#[must_use]
79pub fn memory_capacity_at(root: &Path) -> MemoryCapacity {
80    let meminfo = std::fs::read_to_string(root.join("proc/meminfo")).unwrap_or_default();
81    let kib = |key: &str| {
82        meminfo
83            .lines()
84            .find_map(|line| line.strip_prefix(key))
85            .and_then(|rest| rest.trim().strip_suffix("kB"))
86            .and_then(|value| value.trim().parse::<u64>().ok())
87            .map(|value| value.saturating_mul(1_024))
88    };
89    let physical = kib("MemTotal:");
90    let available = kib("MemAvailable:");
91    match cgroup_memory_at(root) {
92        Some(cgroup) if physical.is_none_or(|physical| cgroup.limit_bytes < physical) => {
93            MemoryCapacity {
94                physical_bytes: physical,
95                available_bytes: available,
96                limit_bytes: Some(cgroup.limit_bytes),
97                limit_source: cgroup.source,
98                used_in_limit_bytes: cgroup.working_set_bytes,
99                charged_in_limit_bytes: cgroup.charged_bytes,
100            }
101        }
102        _ => MemoryCapacity {
103            physical_bytes: physical,
104            available_bytes: available,
105            limit_bytes: physical,
106            limit_source: "physical",
107            used_in_limit_bytes: None,
108            charged_in_limit_bytes: None,
109        },
110    }
111}
112
113/// The lowest memory limit on this process's cgroup path and what is charged against it.
114#[cfg(any(target_os = "linux", target_os = "android"))]
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
116pub struct CgroupMemory {
117    /// The limit, `memory.max` or `memory.limit_in_bytes`.
118    pub limit_bytes: u64,
119    /// What the kernel charges at that level, file page cache included.
120    pub charged_bytes: Option<u64>,
121    /// The charge less the page cache the kernel reclaims before it kills (`inactive_file` and
122    /// `active_file`); the charge itself when `memory.stat` cannot be read.
123    pub working_set_bytes: Option<u64>,
124    /// `cgroup-v2` or `cgroup-v1`.
125    pub source: &'static str,
126}
127
128/// [`CgroupMemory`] of this process, read now; `None` without a cgroup memory limit.
129#[cfg(any(target_os = "linux", target_os = "android"))]
130#[must_use]
131pub fn cgroup_memory() -> Option<CgroupMemory> {
132    cgroup_memory_at(Path::new("/"))
133}
134
135/// [`cgroup_memory`] with `root` standing in for `/`. Levels without a limit (`max`, or v1's
136/// near-`u64::MAX` default) are skipped; v2 is read first.
137#[cfg(any(target_os = "linux", target_os = "android"))]
138#[must_use]
139pub fn cgroup_memory_at(root: &Path) -> Option<CgroupMemory> {
140    let level = Level::lowest(root)?;
141    level.read(0)
142}
143
144/// Reads [`CgroupMemory`] repeatedly for a watch, finding the lowest limit's level again after a
145/// failed read. Below [`Self::STAT_FROM_PERCENT`] of the limit the working set is the charge.
146#[cfg(any(target_os = "linux", target_os = "android"))]
147#[derive(Debug)]
148pub struct CgroupMemoryWatch {
149    root: std::path::PathBuf,
150    level: Option<Level>,
151}
152
153#[cfg(any(target_os = "linux", target_os = "android"))]
154impl CgroupMemoryWatch {
155    /// Below this share of the limit the page cache is not worth parsing.
156    pub const STAT_FROM_PERCENT: u64 = 90;
157
158    /// A watch of this process's cgroup path.
159    #[must_use]
160    pub fn new() -> Self {
161        Self::at(Path::new("/"))
162    }
163
164    /// A watch with `root` standing in for `/`.
165    #[must_use]
166    pub fn at(root: &Path) -> Self {
167        Self {
168            root: root.to_owned(),
169            level: None,
170        }
171    }
172
173    /// `None` without a limit, or when the level just stopped answering.
174    pub fn read(&mut self) -> Option<CgroupMemory> {
175        if self.level.is_none() {
176            self.level = Level::lowest(&self.root);
177        }
178        let memory = self
179            .level
180            .as_ref()?
181            .read(Self::STAT_FROM_PERCENT)
182            .filter(|memory| memory.charged_bytes.is_some());
183        if memory.is_none() {
184            self.level = None;
185        }
186        memory
187    }
188}
189
190#[cfg(any(target_os = "linux", target_os = "android"))]
191impl Default for CgroupMemoryWatch {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197/// The cgroup directory whose memory limit is the lowest on the process's path.
198#[cfg(any(target_os = "linux", target_os = "android"))]
199#[derive(Clone, Debug)]
200struct Level {
201    directory: std::path::PathBuf,
202    /// The limit file, then the charge file.
203    files: [&'static str; 2],
204    /// The `memory.stat` keys of reclaimable page cache.
205    cache: [&'static str; 2],
206    source: &'static str,
207}
208
209#[cfg(any(target_os = "linux", target_os = "android"))]
210impl Level {
211    const V2: ([&'static str; 2], [&'static str; 2], &'static str) = (
212        ["memory.max", "memory.current"],
213        ["inactive_file", "active_file"],
214        "cgroup-v2",
215    );
216    const V1: ([&'static str; 2], [&'static str; 2], &'static str) = (
217        ["memory.limit_in_bytes", "memory.usage_in_bytes"],
218        ["total_inactive_file", "total_active_file"],
219        "cgroup-v1",
220    );
221
222    fn lowest(root: &Path) -> Option<Self> {
223        let membership = std::fs::read_to_string(root.join("proc/self/cgroup")).ok()?;
224        if let Some(relative) = membership.lines().find_map(|line| line.strip_prefix("0::"))
225            && let Some(level) = Self::lowest_under(&root.join("sys/fs/cgroup"), relative, Self::V2)
226        {
227            return Some(level);
228        }
229        let relative = membership.lines().find_map(|line| {
230            let mut fields = line.splitn(3, ':');
231            let _ = fields.next()?;
232            let controllers = fields.next()?;
233            controllers
234                .split(',')
235                .any(|controller| controller == "memory")
236                .then(|| fields.next())
237                .flatten()
238        })?;
239        Self::lowest_under(&root.join("sys/fs/cgroup/memory"), relative, Self::V1)
240    }
241
242    fn lowest_under(
243        mount: &Path,
244        relative: &str,
245        (files, cache, source): ([&'static str; 2], [&'static str; 2], &'static str),
246    ) -> Option<Self> {
247        let mut best: Option<(u64, std::path::PathBuf)> = None;
248        let mut path = Some(Path::new(relative.trim_start_matches('/')));
249        while let Some(level) = path {
250            let directory = mount.join(level);
251            if let Some(limit) = read_limit(&directory.join(files[0]))
252                && best.as_ref().is_none_or(|(known, _)| limit < *known)
253            {
254                best = Some((limit, directory));
255            }
256            path = level.parent();
257        }
258        best.map(|(_, directory)| Self {
259            directory,
260            files,
261            cache,
262            source,
263        })
264    }
265
266    /// `None` when the limit is gone. Parses `memory.stat` only from `stat_from_percent` of it.
267    fn read(&self, stat_from_percent: u64) -> Option<CgroupMemory> {
268        let limit = read_limit(&self.directory.join(self.files[0]))?;
269        let charged = read_number(&self.directory.join(self.files[1]));
270        let cached = charged
271            .filter(|charged| {
272                charged.saturating_mul(100) >= limit.saturating_mul(stat_from_percent)
273            })
274            .and_then(|_| self.cached());
275        Some(CgroupMemory {
276            limit_bytes: limit,
277            charged_bytes: charged,
278            working_set_bytes: charged
279                .map(|charged| cached.map_or(charged, |cached| charged.saturating_sub(cached))),
280            source: self.source,
281        })
282    }
283
284    fn cached(&self) -> Option<u64> {
285        let stat = std::fs::read_to_string(self.directory.join("memory.stat")).ok()?;
286        self.cache.iter().try_fold(0_u64, |sum, key| {
287            let value = stat.lines().find_map(|line| {
288                line.strip_prefix(key)?
289                    .strip_prefix(' ')?
290                    .trim()
291                    .parse::<u64>()
292                    .ok()
293            })?;
294            Some(sum.saturating_add(value))
295        })
296    }
297}
298
299#[cfg(any(target_os = "linux", target_os = "android"))]
300fn read_number(path: &Path) -> Option<u64> {
301    std::fs::read_to_string(path)
302        .ok()
303        .and_then(|text| text.trim().parse::<u64>().ok())
304}
305
306/// A limit, or `None` for `max` and v1's near-`u64::MAX` default.
307#[cfg(any(target_os = "linux", target_os = "android"))]
308fn read_limit(path: &Path) -> Option<u64> {
309    read_number(path).filter(|limit| *limit < (1_u64 << 60))
310}
311
312#[cfg(test)]
313#[path = "memory_tests.rs"]
314mod tests;