use crate::sys::utils::get_all_utf8_data;
use std::cmp::min;
use std::io::ErrorKind;
use std::path::Path;
use std::str::FromStr;
use super::super::cgroup::parse::{cgroup_base_for_path, get_cgroup_mounts, get_cgroup_path};
use super::super::cgroup::types::*;
pub(crate) fn limits_for_system() -> Option<crate::CGroupLimits> {
let v2_root = Path::new("/sys/fs/cgroup");
let v1_root = Path::new("/sys/fs/cgroup/memory");
let v2_bases = [CGroupBase::root(v2_root)];
let v1_bases = [CGroupBase::root(v1_root)];
let v1_bases = if v1_root.join("memory.limit_in_bytes").exists() {
&v1_bases[..]
} else {
&[]
};
limits_for_base(&v2_bases, v1_bases)
}
pub(crate) fn limits_for_process(proc_path: &Path) -> Option<crate::CGroupLimits> {
let cgroup_path = get_cgroup_path(&proc_path.join("cgroup"))?;
let cgroup_mounts = get_cgroup_mounts(&proc_path.join("mountinfo"))?;
limits_for_process_with_context(&cgroup_path, &cgroup_mounts, read_cgroup_limits_context()?)
}
pub(super) fn limits_for_process_with_context(
cgroup_path: &CGroupPath,
cgroup_mounts: &CGroupMounts,
context: CGroupLimitsContext,
) -> Option<crate::CGroupLimits> {
if let Some(path) = &cgroup_path.v1_memory {
let base = cgroup_base_for_path(path, &cgroup_mounts.v1_memory)?;
return v1_limits(&base.base, &base.root, context);
}
let base = cgroup_base_for_path(cgroup_path.v2.as_ref()?, &cgroup_mounts.v2)?;
v2_limits(&base.base, &base.root, context)
}
pub(super) fn limits_for_base(
v2_bases: &[CGroupBase],
v1_bases: &[CGroupBase],
) -> Option<crate::CGroupLimits> {
let context = read_cgroup_limits_context()?;
limits_for_base_with_context(v2_bases, v1_bases, context)
}
pub(super) fn limits_for_base_with_context(
v2_bases: &[CGroupBase],
v1_bases: &[CGroupBase],
context: CGroupLimitsContext,
) -> Option<crate::CGroupLimits> {
v1_bases
.iter()
.find_map(|v1_base| v1_limits(&v1_base.base, &v1_base.root, context))
.or_else(|| {
v2_bases
.iter()
.find_map(|v2_base| v2_limits(&v2_base.base, &v2_base.root, context))
})
}
pub(super) fn read_cgroup_limits_context() -> Option<CGroupLimitsContext> {
let mut mem_total = None;
let mut swap_total = 0;
let mut swap_free = 0;
read_table("/proc/meminfo", ':', |key, value_kib| {
let value = value_kib.saturating_mul(1_024);
match key {
"MemTotal" => mem_total = Some(value),
"SwapTotal" => swap_total = value,
"SwapFree" => swap_free = value,
_ => (),
}
});
Some(CGroupLimitsContext {
mem_total: mem_total?,
swap_total,
swap_free,
})
}
pub(super) fn v2_limits(
base: &Path,
root: &Path,
context: CGroupLimitsContext,
) -> Option<crate::CGroupLimits> {
let mem_max = read_v2_memory_max(&base.join("memory.max"), root)?;
let (total_memory, free_memory) = memory_limits(
base,
root,
"memory.max",
"memory.current",
context.mem_total,
mem_max,
|path| read_v2_memory_max(path, root),
)?;
let mem_rss = read_table_key(&base.join("memory.stat"), "anon", ' ')?;
let mut limits = crate::CGroupLimits {
total_memory,
free_memory,
free_swap: context.swap_free,
rss: mem_rss,
};
if let Some(swap_cur) = read_u64(&base.join("memory.swap.current")) {
limits.free_swap = context.swap_total.saturating_sub(swap_cur);
}
Some(limits)
}
pub(super) fn v1_limits(
base: &Path,
root: &Path,
context: CGroupLimitsContext,
) -> Option<crate::CGroupLimits> {
let mem_max = read_u64(&base.join("memory.limit_in_bytes"))?;
let (total_memory, free_memory) = memory_limits(
base,
root,
"memory.limit_in_bytes",
"memory.usage_in_bytes",
context.mem_total,
mem_max,
read_u64,
)?;
let mem_rss = read_table_key(&base.join("memory.stat"), "total_rss", ' ')?;
Some(crate::CGroupLimits {
total_memory,
free_memory,
free_swap: context.swap_free,
rss: mem_rss,
})
}
pub(super) fn memory_limits<F>(
base: &Path,
root: &Path,
limit_file: &str,
usage_file: &str,
mem_total: u64,
base_limit: u64,
read_limit: F,
) -> Option<(u64, u64)>
where
F: Fn(&Path) -> Option<u64>,
{
let mem_cur = read_u64(&base.join(usage_file))?;
let mut total_memory = None;
let mut free_memory = None;
for (pos, path) in base.ancestors().enumerate() {
let is_base = pos == 0;
let mem_max = if is_base {
base_limit
} else {
read_limit(&path.join(limit_file))?
};
if mem_max <= mem_total {
let mem_cur = if is_base {
mem_cur
} else {
read_u64(&path.join(usage_file))?
};
total_memory = Some(match total_memory {
Some(total_memory) => min(total_memory, mem_max),
None => mem_max,
});
free_memory = Some(match free_memory {
Some(free_memory) => min(free_memory, mem_max.saturating_sub(mem_cur)),
None => mem_max.saturating_sub(mem_cur),
});
}
if path == root {
return Some((total_memory?, free_memory?));
}
}
None
}
pub(super) fn read_v2_memory_max(filename: &Path, root: &Path) -> Option<u64> {
let content = match get_all_utf8_data(filename, 16_635) {
Ok(content) => content,
Err(err)
if err.kind() == ErrorKind::NotFound
&& filename.parent() == Some(root)
&& get_all_utf8_data(root.join("cgroup.controllers"), 4096).is_ok()
&& matches!(
std::fs::metadata(root.join("cgroup.type")),
Err(err) if err.kind() == ErrorKind::NotFound
) =>
{
return Some(u64::MAX);
}
Err(_) => {
sinf_debug!("Failed to read u64 in filename {filename:?}");
return None;
}
};
let content = content.trim();
if content == "max" {
return Some(u64::MAX);
}
match u64::from_str(content).ok() {
Some(value) => Some(value),
None => {
sinf_debug!("Failed to read u64 in filename {filename:?}");
None
}
}
}
pub(super) fn read_u64(filename: &Path) -> Option<u64> {
let result = get_all_utf8_data(filename, 16_635)
.ok()
.and_then(|d| u64::from_str(d.trim()).ok());
if result.is_none() {
sinf_debug!("Failed to read u64 in filename {filename:?}");
}
result
}
pub(super) fn read_table<F>(filename: &str, colsep: char, mut f: F)
where
F: FnMut(&str, u64),
{
if let Ok(content) = get_all_utf8_data(filename, 16_635) {
content
.split('\n')
.flat_map(|line| {
let mut split = line.split(colsep);
let key = split.next()?;
let value = split.next()?;
let value0 = value.trim_start().split(' ').next()?;
let value0_u64 = u64::from_str(value0).ok()?;
Some((key, value0_u64))
})
.for_each(|(k, v)| f(k, v));
}
}
pub(super) fn read_table_key(filename: &Path, target_key: &str, colsep: char) -> Option<u64> {
if let Ok(content) = get_all_utf8_data(filename, 16_635) {
return content.split('\n').find_map(|line| {
let mut split = line.split(colsep);
let key = split.next()?;
if key != target_key {
return None;
}
let value = split.next()?;
let value0 = value.trim_start().split(' ').next()?;
u64::from_str(value0).ok()
});
}
None
}