use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime};
use crate::job_registry::{JobPlace, JobRegistry, JobStatus};
use crate::shell_session::{ContainerProbe, ContainerProbeError};
pub const JOB_MARKER_ENV: &str = "AITHER_CONTAINER_JOB";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum MemoryDomain {
Machine,
Container,
}
impl fmt::Display for MemoryDomain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Machine => "machine",
Self::Container => "container",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct MemorySize(pub u64);
impl fmt::Display for MemorySize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut unit = 0;
let mut size = self.0;
let mut tenths = 0;
while size >= 1024 && unit + 1 < UNITS.len() {
tenths = (size % 1024) * 10 / 1024;
size /= 1024;
unit += 1;
}
if unit == 0 {
write!(f, "{size} B")
} else {
write!(f, "{size}.{tenths} {}", UNITS[unit])
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum FootprintError {
#[error("reading {what} failed: {source}")]
Io {
what: &'static str,
source: std::io::Error,
},
#[error("{what} answered `{content}`, which is not understood")]
Malformed {
what: &'static str,
content: String,
},
#[error("{what} is not available on this platform")]
Unsupported {
what: &'static str,
},
#[error(transparent)]
Container(#[from] ContainerProbeError),
#[error("`{0}` cannot name an agent's registry entry")]
InvalidAgent(String),
}
pub trait FootprintReader: Send + Sync + 'static {
fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError>;
fn physical_memory(&self) -> Result<u64, FootprintError>;
}
#[derive(Clone)]
pub struct AnyFootprintReader(Arc<dyn FootprintReader>);
impl AnyFootprintReader {
#[must_use]
pub fn new(reader: impl FootprintReader) -> Self {
Self(Arc::new(reader))
}
}
impl FootprintReader for AnyFootprintReader {
fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
self.0.tree_footprints(roots)
}
fn physical_memory(&self) -> Result<u64, FootprintError> {
self.0.physical_memory()
}
}
impl fmt::Debug for AnyFootprintReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyFootprintReader")
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemFootprints;
impl FootprintReader for SystemFootprints {
fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
system::tree_footprints(roots)
}
fn physical_memory(&self) -> Result<u64, FootprintError> {
system::physical_memory()
}
}
#[cfg(unix)]
mod system {
use super::FootprintError;
pub(super) fn tree_footprints(roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
if roots.is_empty() {
return Ok(Vec::new());
}
let trees = crate::process_tree::tree_pids(roots).map_err(|source| FootprintError::Io {
what: "the process table",
source,
})?;
Ok(trees
.into_iter()
.map(|pids| pids.into_iter().map(process_footprint).sum())
.collect())
}
#[cfg(target_vendor = "apple")]
fn process_footprint(pid: u32) -> u64 {
let mut usage: libc::rusage_info_v2 = unsafe { std::mem::zeroed() };
let status = unsafe {
libc::proc_pid_rusage(
pid.cast_signed(),
libc::RUSAGE_INFO_V2,
(&raw mut usage).cast::<libc::rusage_info_t>(),
)
};
if status == 0 {
usage.ri_phys_footprint
} else {
0
}
}
#[cfg(not(target_vendor = "apple"))]
fn process_footprint(pid: u32) -> u64 {
let Ok(rollup) = std::fs::read_to_string(format!("/proc/{pid}/smaps_rollup")) else {
return 0;
};
rollup
.lines()
.find_map(|line| line.strip_prefix("Pss:"))
.and_then(|rest| rest.trim().strip_suffix("kB"))
.and_then(|kib| kib.trim().parse::<u64>().ok())
.map_or(0, |kib| kib * 1024)
}
pub(super) fn physical_memory() -> Result<u64, FootprintError> {
let (pages, page) = unsafe {
(
libc::sysconf(libc::_SC_PHYS_PAGES),
libc::sysconf(libc::_SC_PAGESIZE),
)
};
match (u64::try_from(pages), u64::try_from(page)) {
(Ok(pages), Ok(page)) => Ok(pages * page),
_ => Err(FootprintError::Io {
what: "the physical memory size",
source: std::io::Error::last_os_error(),
}),
}
}
}
#[cfg(windows)]
mod system {
use std::collections::HashMap;
use std::io;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
TH32CS_SNAPPROCESS,
};
use windows_sys::Win32::System::ProcessStatus::{
GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX,
};
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ,
};
use super::FootprintError;
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
fn io_error(what: &'static str) -> FootprintError {
FootprintError::Io {
what,
source: io::Error::last_os_error(),
}
}
fn process_table() -> Result<Vec<(u32, u32)>, FootprintError> {
const WHAT: &str = "the process table";
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
if snapshot == INVALID_HANDLE_VALUE {
return Err(io_error(WHAT));
}
let snapshot = Handle(snapshot);
let mut entry = PROCESSENTRY32W {
dwSize: size_of::<PROCESSENTRY32W>()
.try_into()
.expect("the entry size fits u32"),
..PROCESSENTRY32W::default()
};
let mut table = Vec::new();
let mut more = unsafe { Process32FirstW(snapshot.0, &raw mut entry) } != 0;
while more {
table.push((entry.th32ProcessID, entry.th32ParentProcessID));
more = unsafe { Process32NextW(snapshot.0, &raw mut entry) } != 0;
}
let end = io::Error::last_os_error();
if end.raw_os_error() == Some(18) {
Ok(table)
} else {
Err(FootprintError::Io {
what: WHAT,
source: end,
})
}
}
fn private_bytes(pid: u32) -> u64 {
let process =
unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, 0, pid) };
if process.is_null() {
return 0;
}
let process = Handle(process);
let mut counters = PROCESS_MEMORY_COUNTERS_EX {
cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>()
.try_into()
.expect("the counters size fits u32"),
PageFaultCount: 0,
PeakWorkingSetSize: 0,
WorkingSetSize: 0,
QuotaPeakPagedPoolUsage: 0,
QuotaPagedPoolUsage: 0,
QuotaPeakNonPagedPoolUsage: 0,
QuotaNonPagedPoolUsage: 0,
PagefileUsage: 0,
PeakPagefileUsage: 0,
PrivateUsage: 0,
};
let ok = unsafe {
GetProcessMemoryInfo(
process.0,
(&raw mut counters).cast::<PROCESS_MEMORY_COUNTERS>(),
counters.cb,
)
};
if ok == 0 {
0
} else {
counters.PrivateUsage as u64
}
}
pub(super) fn tree_footprints(roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
if roots.is_empty() {
return Ok(Vec::new());
}
let table = process_table()?;
let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
for &(pid, parent) in &table {
children.entry(parent).or_default().push(pid);
}
Ok(roots
.iter()
.map(|&root| {
if !table.iter().any(|&(pid, _)| pid == root) {
return 0;
}
let mut seen = vec![root];
let mut next = 0;
while let Some(&pid) = seen.get(next) {
next += 1;
for &child in children.get(&pid).into_iter().flatten() {
if !seen.contains(&child) {
seen.push(child);
}
}
}
seen.into_iter().map(private_bytes).sum()
})
.collect())
}
pub(super) fn physical_memory() -> Result<u64, FootprintError> {
let mut status = MEMORYSTATUSEX {
dwLength: size_of::<MEMORYSTATUSEX>()
.try_into()
.expect("the status size fits u32"),
dwMemoryLoad: 0,
ullTotalPhys: 0,
ullAvailPhys: 0,
ullTotalPageFile: 0,
ullAvailPageFile: 0,
ullTotalVirtual: 0,
ullAvailVirtual: 0,
ullAvailExtendedVirtual: 0,
};
if unsafe { GlobalMemoryStatusEx(&raw mut status) } == 0 {
return Err(io_error("the physical memory size"));
}
Ok(status.ullTotalPhys)
}
}
#[cfg(not(any(unix, windows)))]
mod system {
use super::FootprintError;
pub(super) fn tree_footprints(_: &[u32]) -> Result<Vec<u64>, FootprintError> {
Err(FootprintError::Unsupported {
what: "the footprint of a process tree",
})
}
pub(super) fn physical_memory() -> Result<u64, FootprintError> {
Err(FootprintError::Unsupported {
what: "the physical memory size",
})
}
}
pub trait FootprintRegistry: Send + Sync + 'static {
fn publish(&self, total_bytes: u64) -> Result<(), FootprintError>;
fn others(&self) -> Result<Vec<u64>, FootprintError>;
}
#[derive(Clone)]
pub struct AnyFootprintRegistry(Arc<dyn FootprintRegistry>);
impl AnyFootprintRegistry {
#[must_use]
pub fn new(registry: impl FootprintRegistry) -> Self {
Self(Arc::new(registry))
}
}
impl FootprintRegistry for AnyFootprintRegistry {
fn publish(&self, total_bytes: u64) -> Result<(), FootprintError> {
self.0.publish(total_bytes)
}
fn others(&self) -> Result<Vec<u64>, FootprintError> {
self.0.others()
}
}
impl fmt::Debug for AnyFootprintRegistry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyFootprintRegistry")
}
}
#[derive(Debug, Clone)]
pub struct FileFootprintRegistry {
dir: PathBuf,
agent: String,
stale_after: Duration,
}
impl FileFootprintRegistry {
const EXTENSION: &'static str = "footprint";
pub fn new(
dir: impl Into<PathBuf>,
agent: impl Into<String>,
stale_after: Duration,
) -> Result<Self, FootprintError> {
let agent = agent.into();
if agent.is_empty() || agent.contains(['/', '\\']) || agent.starts_with('.') {
return Err(FootprintError::InvalidAgent(agent));
}
Ok(Self {
dir: dir.into(),
agent,
stale_after,
})
}
fn entry(&self) -> PathBuf {
self.dir.join(format!("{}.{}", self.agent, Self::EXTENSION))
}
}
impl FootprintRegistry for FileFootprintRegistry {
fn publish(&self, total_bytes: u64) -> Result<(), FootprintError> {
use std::io::Write as _;
let io = |source| FootprintError::Io {
what: "the footprint registry",
source,
};
if total_bytes == 0 {
return match std::fs::remove_file(self.entry()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(io(error)),
_ => Ok(()),
};
}
std::fs::create_dir_all(&self.dir).map_err(io)?;
let mut file = tempfile::NamedTempFile::new_in(&self.dir).map_err(io)?;
write!(file, "{total_bytes}").map_err(io)?;
file.persist(self.entry())
.map_err(|error| io(error.error))?;
Ok(())
}
fn others(&self) -> Result<Vec<u64>, FootprintError> {
let io = |source| FootprintError::Io {
what: "the footprint registry",
source,
};
let entries = match std::fs::read_dir(&self.dir) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(io(error)),
};
let own = self.entry();
let now = SystemTime::now();
let mut others = Vec::new();
for entry in entries {
let path = entry.map_err(io)?.path();
if path == own || path.extension().is_none_or(|ext| ext != Self::EXTENSION) {
continue;
}
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let modified = std::fs::metadata(&path).and_then(|meta| meta.modified());
if modified
.is_ok_and(|at| now.duration_since(at).unwrap_or_default() > self.stale_after)
{
continue;
}
let bytes = content
.trim()
.parse()
.map_err(|_| FootprintError::Malformed {
what: "a footprint registry entry",
content: content.clone(),
})?;
others.push(bytes);
}
Ok(others)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupMemory {
pub current_bytes: u64,
pub limit_bytes: Option<u64>,
pub pressure: String,
}
impl CgroupMemory {
pub fn parse(output: &str) -> Result<Self, FootprintError> {
let malformed = || FootprintError::Malformed {
what: "the container's memory cgroup",
content: output.to_string(),
};
let mut lines = output.lines();
let limit = lines.next().ok_or_else(malformed)?.trim();
let limit_bytes = if limit == "max" {
None
} else {
Some(limit.parse().map_err(|_| malformed())?)
};
let current_bytes = lines
.next()
.ok_or_else(malformed)?
.trim()
.parse()
.map_err(|_| malformed())?;
let pressure = lines.collect::<Vec<_>>().join("\n");
Ok(Self {
current_bytes,
limit_bytes,
pressure,
})
}
}
pub trait ContainerMemory: Send + Sync + 'static {
fn cgroup(&self) -> impl Future<Output = Result<CgroupMemory, FootprintError>> + Send;
fn job_footprints(
&self,
task_ids: &[String],
) -> impl Future<Output = Result<Vec<u64>, FootprintError>> + Send;
}
pub trait ContainerMemoryImpl: Send + Sync {
fn cgroup_boxed(
&self,
) -> Pin<Box<dyn Future<Output = Result<CgroupMemory, FootprintError>> + Send + '_>>;
fn job_footprints_boxed<'a>(
&'a self,
task_ids: &'a [String],
) -> Pin<Box<dyn Future<Output = Result<Vec<u64>, FootprintError>> + Send + 'a>>;
}
impl<T: ContainerMemory> ContainerMemoryImpl for T {
fn cgroup_boxed(
&self,
) -> Pin<Box<dyn Future<Output = Result<CgroupMemory, FootprintError>> + Send + '_>> {
Box::pin(self.cgroup())
}
fn job_footprints_boxed<'a>(
&'a self,
task_ids: &'a [String],
) -> Pin<Box<dyn Future<Output = Result<Vec<u64>, FootprintError>> + Send + 'a>> {
Box::pin(self.job_footprints(task_ids))
}
}
#[derive(Clone)]
pub struct AnyContainerMemory(Arc<dyn ContainerMemoryImpl>);
impl AnyContainerMemory {
#[must_use]
pub fn new(memory: impl ContainerMemory) -> Self {
Self(Arc::new(memory))
}
}
impl ContainerMemory for AnyContainerMemory {
async fn cgroup(&self) -> Result<CgroupMemory, FootprintError> {
self.0.cgroup_boxed().await
}
async fn job_footprints(&self, task_ids: &[String]) -> Result<Vec<u64>, FootprintError> {
self.0.job_footprints_boxed(task_ids).await
}
}
impl fmt::Debug for AnyContainerMemory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyContainerMemory")
}
}
#[derive(Debug, Clone)]
pub struct ProbedContainerMemory {
probe: ContainerProbe,
}
impl ProbedContainerMemory {
#[must_use]
pub const fn new(probe: ContainerProbe) -> Self {
Self { probe }
}
}
impl ContainerMemory for ProbedContainerMemory {
async fn cgroup(&self) -> Result<CgroupMemory, FootprintError> {
let output = self
.probe
.read(include_str!("../templates/container_memory_cgroup.sh"))
.await?;
CgroupMemory::parse(&output)
}
async fn job_footprints(&self, task_ids: &[String]) -> Result<Vec<u64>, FootprintError> {
if task_ids.is_empty() {
return Ok(Vec::new());
}
let output = self
.probe
.read(include_str!("../templates/container_memory_jobs.sh"))
.await?;
let mut by_job: BTreeMap<&str, u64> = BTreeMap::new();
for line in output.lines() {
let malformed = || FootprintError::Malformed {
what: "a container job's footprint",
content: line.to_string(),
};
let (id, kib) = line.split_once(' ').ok_or_else(malformed)?;
let kib: u64 = kib.trim().parse().map_err(|_| malformed())?;
*by_job.entry(id).or_default() += kib * 1024;
}
Ok(task_ids
.iter()
.map(|id| by_job.get(id.as_str()).copied().unwrap_or(0))
.collect())
}
}
#[derive(Debug, Clone)]
pub struct ResponseWindow(Arc<AtomicU64>);
impl ResponseWindow {
#[must_use]
pub fn new(window: Duration) -> Self {
let window = Self::nanos(window);
Self(Arc::new(AtomicU64::new(window)))
}
fn nanos(window: Duration) -> u64 {
u64::try_from(window.as_nanos()).expect("a response window fits in u64 nanoseconds")
}
pub fn set(&self, window: Duration) {
self.0.store(Self::nanos(window), Ordering::Relaxed);
}
#[must_use]
pub fn get(&self) -> Duration {
Duration::from_nanos(self.0.load(Ordering::Relaxed))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobFootprint {
pub task_id: String,
pub command: String,
pub pid: u32,
pub footprint_bytes: u64,
}
impl JobFootprint {
#[must_use]
pub const fn footprint(&self) -> MemorySize {
MemorySize(self.footprint_bytes)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemorySnapshot {
pub domain: MemoryDomain,
pub capacity_bytes: u64,
pub jobs: Vec<JobFootprint>,
pub own_bytes: u64,
pub total_bytes: u64,
pub largest_contributor: bool,
}
impl MemorySnapshot {
#[must_use]
pub const fn exceeded_by(&self, bytes: u64) -> bool {
match self.domain {
MemoryDomain::Machine => bytes > self.capacity_bytes,
MemoryDomain::Container => bytes >= self.capacity_bytes,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainerSnapshot {
pub snapshot: MemorySnapshot,
pub pressure: String,
}
#[derive(Debug, Clone)]
pub struct JobMemory {
jobs: JobRegistry,
reader: AnyFootprintReader,
registry: Option<AnyFootprintRegistry>,
window: ResponseWindow,
container: Option<AnyContainerMemory>,
}
impl JobMemory {
#[must_use]
pub const fn new(
jobs: JobRegistry,
reader: AnyFootprintReader,
registry: Option<AnyFootprintRegistry>,
window: ResponseWindow,
) -> Self {
Self {
jobs,
reader,
registry,
window,
container: None,
}
}
#[must_use]
pub fn with_container(mut self, container: AnyContainerMemory) -> Self {
self.container = Some(container);
self
}
#[must_use]
pub const fn has_container(&self) -> bool {
self.container.is_some()
}
#[must_use]
pub fn response_window(&self) -> Duration {
self.window.get()
}
async fn running_at(&self, place: JobPlace) -> Vec<crate::JobInfo> {
self.jobs
.list()
.await
.into_iter()
.filter(|job| job.place == place && matches!(job.status, JobStatus::Running))
.collect()
}
pub async fn container_snapshot(&self) -> Result<Option<ContainerSnapshot>, FootprintError> {
let Some(container) = &self.container else {
return Ok(None);
};
let cgroup = container.cgroup().await?;
let Some(capacity_bytes) = cgroup.limit_bytes else {
return Ok(None);
};
let running = self.running_at(JobPlace::Container).await;
let task_ids: Vec<String> = running.iter().map(|job| job.task_id.clone()).collect();
let footprints = container.job_footprints(&task_ids).await?;
let mut jobs: Vec<JobFootprint> = running
.into_iter()
.zip(footprints)
.map(|(job, footprint_bytes)| JobFootprint {
task_id: job.task_id,
command: job.script,
pid: job.pid,
footprint_bytes,
})
.collect();
jobs.sort_by_key(|job| std::cmp::Reverse(job.footprint_bytes));
let own_bytes = jobs.iter().map(|job| job.footprint_bytes).sum();
Ok(Some(ContainerSnapshot {
snapshot: MemorySnapshot {
domain: MemoryDomain::Container,
capacity_bytes,
jobs,
own_bytes,
total_bytes: own_bytes,
largest_contributor: true,
},
pressure: cgroup.pressure,
}))
}
pub async fn snapshot(&self) -> Result<MemorySnapshot, FootprintError> {
let running = self.running_at(JobPlace::Host).await;
let roots: Vec<u32> = running.iter().map(|job| job.pid).collect();
let (reader, registry) = (self.reader.clone(), self.registry.clone());
let (footprints, physical_bytes, own_bytes, others) = blocking::unblock(move || {
let footprints = reader.tree_footprints(&roots)?;
let own: u64 = footprints.iter().sum();
let others = match registry {
Some(registry) => {
registry.publish(own)?;
registry.others()?
}
None => Vec::new(),
};
Ok::<_, FootprintError>((footprints, reader.physical_memory()?, own, others))
})
.await?;
let mut jobs: Vec<JobFootprint> = running
.into_iter()
.zip(footprints)
.map(|(job, footprint_bytes)| JobFootprint {
task_id: job.task_id,
command: job.script,
pid: job.pid,
footprint_bytes,
})
.collect();
jobs.sort_by_key(|job| std::cmp::Reverse(job.footprint_bytes));
Ok(MemorySnapshot {
domain: MemoryDomain::Machine,
capacity_bytes: physical_bytes,
jobs,
own_bytes,
total_bytes: own_bytes + others.iter().sum::<u64>(),
largest_contributor: others.iter().all(|other| *other <= own_bytes),
})
}
pub async fn kill_runaway(&self, job: &JobFootprint, snapshot: &MemorySnapshot) -> bool {
self.jobs
.kill_runaway(
&job.task_id,
job.footprint_bytes,
snapshot.capacity_bytes,
snapshot.domain,
)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_read_in_binary_units() {
assert_eq!(MemorySize(512).to_string(), "512 B");
assert_eq!(MemorySize(1536).to_string(), "1.5 KiB");
assert_eq!(MemorySize(36 * 1024 * 1024 * 1024).to_string(), "36.0 GiB");
}
#[test]
fn the_file_registry_totals_other_agents_and_forgets_withdrawn_and_stale_ones() {
let dir = tempfile::tempdir().unwrap();
let long = Duration::from_secs(3600);
let a = FileFootprintRegistry::new(dir.path(), "a", long).unwrap();
let b = FileFootprintRegistry::new(dir.path(), "b", long).unwrap();
a.publish(100).unwrap();
b.publish(30).unwrap();
assert_eq!(a.others().unwrap(), vec![30]);
assert_eq!(b.others().unwrap(), vec![100]);
a.publish(0).unwrap();
assert_eq!(b.others().unwrap(), Vec::<u64>::new());
let stale = FileFootprintRegistry::new(dir.path(), "c", Duration::ZERO).unwrap();
b.publish(30).unwrap();
std::thread::sleep(Duration::from_millis(20));
assert_eq!(stale.others().unwrap(), Vec::<u64>::new());
assert!(FileFootprintRegistry::new(dir.path(), "../x", long).is_err());
}
#[cfg(any(unix, windows))]
#[test]
fn this_process_tree_has_a_footprint_and_the_machine_has_memory() {
let reader = SystemFootprints;
let footprints = reader.tree_footprints(&[std::process::id()]).unwrap();
assert!(footprints[0] > 0);
assert!(reader.physical_memory().unwrap() > footprints[0]);
}
#[test]
fn the_cgroup_probe_reads_the_limit_the_usage_and_the_pressure() {
let limited = CgroupMemory::parse(
"4294967296\n1073741824\nsome avg10=1.00 avg60=0.00 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n",
)
.unwrap();
assert_eq!(limited.limit_bytes, Some(4 * 1024 * 1024 * 1024));
assert_eq!(limited.current_bytes, 1024 * 1024 * 1024);
assert!(limited.pressure.starts_with("some avg10=1.00"));
assert!(limited.pressure.contains("\nfull avg10=0.00"));
let unlimited = CgroupMemory::parse("max\n5\n").unwrap();
assert_eq!(unlimited.limit_bytes, None);
assert_eq!(unlimited.pressure, "");
assert!(CgroupMemory::parse("").is_err());
assert!(CgroupMemory::parse("lots\n5\n").is_err());
assert!(CgroupMemory::parse("max\n").is_err());
}
#[test]
fn a_container_is_exceeded_at_its_limit_and_a_machine_above_its_memory() {
let snapshot = |domain| MemorySnapshot {
domain,
capacity_bytes: 100,
jobs: Vec::new(),
own_bytes: 0,
total_bytes: 0,
largest_contributor: true,
};
let machine = snapshot(MemoryDomain::Machine);
assert!(!machine.exceeded_by(100) && machine.exceeded_by(101));
let container = snapshot(MemoryDomain::Container);
assert!(!container.exceeded_by(99) && container.exceeded_by(100));
}
#[cfg(unix)]
mod placed {
use std::collections::HashMap;
use std::os::unix::process::ExitStatusExt as _;
use std::sync::Mutex;
use async_channel::{Receiver, Sender};
use super::*;
use crate::job_registry::job_registry_channel;
use crate::{
AnyContainerExec, ContainerExec, ContainerExecOutcome, ExecLifetime, SandboxMode,
};
const GIB: u64 = 1024 * 1024 * 1024;
struct Container {
cgroup: &'static str,
jobs: &'static str,
scripts: Mutex<Vec<String>>,
}
impl ContainerExec for Container {
fn exec(
&self,
_container_id: &str,
script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_lifetime: ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
self.scripts.lock().unwrap().push(script.to_string());
let stdout = if script.contains("memory.max") {
Ok(self.cgroup)
} else if script.contains(JOB_MARKER_ENV) {
Ok(self.jobs)
} else {
Err(format!("unexpected probe: {script}"))
};
std::future::ready(stdout.map(|stdout| ContainerExecOutcome::Completed {
output: std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: stdout.as_bytes().to_vec(),
stderr: Vec::new(),
},
killed: Vec::new(),
}))
}
fn exec_streamed(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_stdout: Sender<Vec<u8>>,
_lifetime: crate::ExecLifetime,
) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
std::future::ready(Err("a probe is never streamed".to_string()))
}
}
fn container_memory(
cgroup: &'static str,
jobs: &'static str,
) -> (Arc<Container>, AnyContainerMemory) {
let container = Arc::new(Container {
cgroup,
jobs,
scripts: Mutex::new(Vec::new()),
});
let exec = AnyContainerExec::new(Arc::clone(&container));
let memory = ProbedContainerMemory::new(ContainerProbe::new(&exec, "box"));
(container, AnyContainerMemory::new(memory))
}
struct Held(HashMap<u32, u64>);
impl FootprintReader for Held {
fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
Ok(roots
.iter()
.map(|pid| self.0.get(pid).copied().unwrap_or(0))
.collect())
}
fn physical_memory(&self) -> Result<u64, FootprintError> {
Ok(16 * GIB)
}
}
async fn memory_with_jobs() -> JobMemory {
let (jobs, service) = job_registry_channel(crate::output_policy::fixture::policy());
tokio::spawn(async move { service.serve().await });
for (place, pid, task) in [
(JobPlace::Host, 1, "host"),
(JobPlace::Container, 2, "boxed"),
(JobPlace::Remote, 3, "remote"),
] {
jobs.register_at(
place,
pid,
&crate::test_ids::lease(task),
"exec",
task,
crate::Interpreter::Shell,
SandboxMode::Sandboxed,
)
.await;
}
let held = Held(HashMap::from([(1, 2 * GIB), (2, 90 * GIB), (3, 90 * GIB)]));
JobMemory::new(
jobs,
AnyFootprintReader::new(held),
None,
ResponseWindow::new(Duration::from_secs(60)),
)
}
#[tokio::test]
async fn the_machine_counts_only_jobs_that_run_on_it() {
let memory = memory_with_jobs().await;
let snapshot = memory.snapshot().await.unwrap();
let tasks: Vec<_> = snapshot
.jobs
.iter()
.map(|job| job.task_id.as_str())
.collect();
assert_eq!(tasks, ["host"]);
assert_eq!(snapshot.own_bytes, 2 * GIB);
assert_eq!(snapshot.domain, MemoryDomain::Machine);
}
#[tokio::test]
async fn a_container_with_a_limit_is_judged_against_it_with_its_own_jobs() {
let (container, reader) = container_memory(
"4294967296\n1073741824\nsome avg10=12.00 avg60=0.00 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n",
"boxed 1048576\nboxed 524288\nother 99\n",
);
let memory = memory_with_jobs().await.with_container(reader);
let snapshot = memory.container_snapshot().await.unwrap().unwrap();
assert_eq!(snapshot.snapshot.domain, MemoryDomain::Container);
assert_eq!(snapshot.snapshot.capacity_bytes, 4 * GIB);
let jobs: Vec<_> = snapshot
.snapshot
.jobs
.iter()
.map(|job| (job.task_id.as_str(), job.footprint_bytes))
.collect();
assert_eq!(jobs, [("boxed", GIB + GIB / 2)]);
assert!(snapshot.pressure.starts_with("some avg10=12.00"));
assert_eq!(container.scripts.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn a_container_without_a_limit_or_a_terminal_without_a_container_adds_nothing() {
let (_, unlimited) = container_memory("max\n123\n", "");
let memory = memory_with_jobs().await.with_container(unlimited);
assert_eq!(memory.container_snapshot().await.unwrap(), None);
assert_eq!(
memory_with_jobs().await.container_snapshot().await.unwrap(),
None
);
}
}
}