1use std::collections::BTreeMap;
19use std::fmt;
20use std::future::Future;
21use std::path::PathBuf;
22use std::pin::Pin;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicU64, Ordering};
25use std::time::{Duration, SystemTime};
26
27use crate::job_registry::{JobPlace, JobRegistry, JobStatus};
28use crate::shell_session::{ContainerProbe, ContainerProbeError};
29
30pub const JOB_MARKER_ENV: &str = "AITHER_CONTAINER_JOB";
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
40pub enum MemoryDomain {
41 Machine,
43 Container,
45}
46
47impl fmt::Display for MemoryDomain {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str(match self {
50 Self::Machine => "machine",
51 Self::Container => "container",
52 })
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
58pub struct MemorySize(pub u64);
59
60impl fmt::Display for MemorySize {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
63 let mut unit = 0;
64 let mut size = self.0;
65 let mut tenths = 0;
67 while size >= 1024 && unit + 1 < UNITS.len() {
68 tenths = (size % 1024) * 10 / 1024;
69 size /= 1024;
70 unit += 1;
71 }
72 if unit == 0 {
73 write!(f, "{size} B")
74 } else {
75 write!(f, "{size}.{tenths} {}", UNITS[unit])
76 }
77 }
78}
79
80#[derive(Debug, thiserror::Error)]
82pub enum FootprintError {
83 #[error("reading {what} failed: {source}")]
85 Io {
86 what: &'static str,
88 source: std::io::Error,
90 },
91 #[error("{what} answered `{content}`, which is not understood")]
93 Malformed {
94 what: &'static str,
96 content: String,
98 },
99 #[error("{what} is not available on this platform")]
101 Unsupported {
102 what: &'static str,
104 },
105 #[error(transparent)]
107 Container(#[from] ContainerProbeError),
108 #[error("`{0}` cannot name an agent's registry entry")]
110 InvalidAgent(String),
111}
112
113pub trait FootprintReader: Send + Sync + 'static {
117 fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError>;
125
126 fn physical_memory(&self) -> Result<u64, FootprintError>;
132}
133
134#[derive(Clone)]
136pub struct AnyFootprintReader(Arc<dyn FootprintReader>);
137
138impl AnyFootprintReader {
139 #[must_use]
141 pub fn new(reader: impl FootprintReader) -> Self {
142 Self(Arc::new(reader))
143 }
144}
145
146impl FootprintReader for AnyFootprintReader {
147 fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
148 self.0.tree_footprints(roots)
149 }
150
151 fn physical_memory(&self) -> Result<u64, FootprintError> {
152 self.0.physical_memory()
153 }
154}
155
156impl fmt::Debug for AnyFootprintReader {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.write_str("AnyFootprintReader")
159 }
160}
161
162#[derive(Debug, Clone, Copy, Default)]
169pub struct SystemFootprints;
170
171impl FootprintReader for SystemFootprints {
172 fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
173 system::tree_footprints(roots)
174 }
175
176 fn physical_memory(&self) -> Result<u64, FootprintError> {
177 system::physical_memory()
178 }
179}
180
181#[cfg(unix)]
182mod system {
183 use super::FootprintError;
184
185 pub(super) fn tree_footprints(roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
186 if roots.is_empty() {
187 return Ok(Vec::new());
188 }
189 let trees = crate::process_tree::tree_pids(roots).map_err(|source| FootprintError::Io {
190 what: "the process table",
191 source,
192 })?;
193 Ok(trees
194 .into_iter()
195 .map(|pids| pids.into_iter().map(process_footprint).sum())
196 .collect())
197 }
198
199 #[cfg(target_vendor = "apple")]
201 fn process_footprint(pid: u32) -> u64 {
202 let mut usage: libc::rusage_info_v2 = unsafe { std::mem::zeroed() };
203 let status = unsafe {
206 libc::proc_pid_rusage(
207 pid.cast_signed(),
208 libc::RUSAGE_INFO_V2,
209 (&raw mut usage).cast::<libc::rusage_info_t>(),
210 )
211 };
212 if status == 0 {
213 usage.ri_phys_footprint
214 } else {
215 0
216 }
217 }
218
219 #[cfg(not(target_vendor = "apple"))]
221 fn process_footprint(pid: u32) -> u64 {
222 let Ok(rollup) = std::fs::read_to_string(format!("/proc/{pid}/smaps_rollup")) else {
223 return 0;
224 };
225 rollup
226 .lines()
227 .find_map(|line| line.strip_prefix("Pss:"))
228 .and_then(|rest| rest.trim().strip_suffix("kB"))
229 .and_then(|kib| kib.trim().parse::<u64>().ok())
230 .map_or(0, |kib| kib * 1024)
231 }
232
233 pub(super) fn physical_memory() -> Result<u64, FootprintError> {
234 let (pages, page) = unsafe {
236 (
237 libc::sysconf(libc::_SC_PHYS_PAGES),
238 libc::sysconf(libc::_SC_PAGESIZE),
239 )
240 };
241 match (u64::try_from(pages), u64::try_from(page)) {
242 (Ok(pages), Ok(page)) => Ok(pages * page),
243 _ => Err(FootprintError::Io {
244 what: "the physical memory size",
245 source: std::io::Error::last_os_error(),
246 }),
247 }
248 }
249}
250
251#[cfg(windows)]
252mod system {
253 use std::collections::HashMap;
254 use std::io;
255
256 use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
257 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
258 CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
259 TH32CS_SNAPPROCESS,
260 };
261 use windows_sys::Win32::System::ProcessStatus::{
262 GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX,
263 };
264 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
265 use windows_sys::Win32::System::Threading::{
266 OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ,
267 };
268
269 use super::FootprintError;
270
271 struct Handle(HANDLE);
273
274 impl Drop for Handle {
275 fn drop(&mut self) {
276 unsafe { CloseHandle(self.0) };
278 }
279 }
280
281 fn io_error(what: &'static str) -> FootprintError {
282 FootprintError::Io {
283 what,
284 source: io::Error::last_os_error(),
285 }
286 }
287
288 fn process_table() -> Result<Vec<(u32, u32)>, FootprintError> {
291 const WHAT: &str = "the process table";
292 let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
295 if snapshot == INVALID_HANDLE_VALUE {
296 return Err(io_error(WHAT));
297 }
298 let snapshot = Handle(snapshot);
299 let mut entry = PROCESSENTRY32W {
300 dwSize: size_of::<PROCESSENTRY32W>()
301 .try_into()
302 .expect("the entry size fits u32"),
303 ..PROCESSENTRY32W::default()
304 };
305 let mut table = Vec::new();
306 let mut more = unsafe { Process32FirstW(snapshot.0, &raw mut entry) } != 0;
309 while more {
310 table.push((entry.th32ProcessID, entry.th32ParentProcessID));
311 more = unsafe { Process32NextW(snapshot.0, &raw mut entry) } != 0;
313 }
314 let end = io::Error::last_os_error();
316 if end.raw_os_error() == Some(18) {
317 Ok(table)
318 } else {
319 Err(FootprintError::Io {
320 what: WHAT,
321 source: end,
322 })
323 }
324 }
325
326 fn private_bytes(pid: u32) -> u64 {
329 let process =
331 unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, 0, pid) };
332 if process.is_null() {
333 return 0;
334 }
335 let process = Handle(process);
336 let mut counters = PROCESS_MEMORY_COUNTERS_EX {
337 cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>()
338 .try_into()
339 .expect("the counters size fits u32"),
340 PageFaultCount: 0,
341 PeakWorkingSetSize: 0,
342 WorkingSetSize: 0,
343 QuotaPeakPagedPoolUsage: 0,
344 QuotaPagedPoolUsage: 0,
345 QuotaPeakNonPagedPoolUsage: 0,
346 QuotaNonPagedPoolUsage: 0,
347 PagefileUsage: 0,
348 PeakPagefileUsage: 0,
349 PrivateUsage: 0,
350 };
351 let ok = unsafe {
355 GetProcessMemoryInfo(
356 process.0,
357 (&raw mut counters).cast::<PROCESS_MEMORY_COUNTERS>(),
358 counters.cb,
359 )
360 };
361 if ok == 0 {
362 0
363 } else {
364 counters.PrivateUsage as u64
365 }
366 }
367
368 pub(super) fn tree_footprints(roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
369 if roots.is_empty() {
370 return Ok(Vec::new());
371 }
372 let table = process_table()?;
373 let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
374 for &(pid, parent) in &table {
375 children.entry(parent).or_default().push(pid);
376 }
377 Ok(roots
378 .iter()
379 .map(|&root| {
380 if !table.iter().any(|&(pid, _)| pid == root) {
381 return 0;
382 }
383 let mut seen = vec![root];
385 let mut next = 0;
386 while let Some(&pid) = seen.get(next) {
387 next += 1;
388 for &child in children.get(&pid).into_iter().flatten() {
389 if !seen.contains(&child) {
390 seen.push(child);
391 }
392 }
393 }
394 seen.into_iter().map(private_bytes).sum()
395 })
396 .collect())
397 }
398
399 pub(super) fn physical_memory() -> Result<u64, FootprintError> {
400 let mut status = MEMORYSTATUSEX {
401 dwLength: size_of::<MEMORYSTATUSEX>()
402 .try_into()
403 .expect("the status size fits u32"),
404 dwMemoryLoad: 0,
405 ullTotalPhys: 0,
406 ullAvailPhys: 0,
407 ullTotalPageFile: 0,
408 ullAvailPageFile: 0,
409 ullTotalVirtual: 0,
410 ullAvailVirtual: 0,
411 ullAvailExtendedVirtual: 0,
412 };
413 if unsafe { GlobalMemoryStatusEx(&raw mut status) } == 0 {
416 return Err(io_error("the physical memory size"));
417 }
418 Ok(status.ullTotalPhys)
419 }
420}
421
422#[cfg(not(any(unix, windows)))]
423mod system {
424 use super::FootprintError;
425
426 pub(super) fn tree_footprints(_: &[u32]) -> Result<Vec<u64>, FootprintError> {
427 Err(FootprintError::Unsupported {
428 what: "the footprint of a process tree",
429 })
430 }
431
432 pub(super) fn physical_memory() -> Result<u64, FootprintError> {
433 Err(FootprintError::Unsupported {
434 what: "the physical memory size",
435 })
436 }
437}
438
439pub trait FootprintRegistry: Send + Sync + 'static {
443 fn publish(&self, total_bytes: u64) -> Result<(), FootprintError>;
449
450 fn others(&self) -> Result<Vec<u64>, FootprintError>;
456}
457
458#[derive(Clone)]
460pub struct AnyFootprintRegistry(Arc<dyn FootprintRegistry>);
461
462impl AnyFootprintRegistry {
463 #[must_use]
465 pub fn new(registry: impl FootprintRegistry) -> Self {
466 Self(Arc::new(registry))
467 }
468}
469
470impl FootprintRegistry for AnyFootprintRegistry {
471 fn publish(&self, total_bytes: u64) -> Result<(), FootprintError> {
472 self.0.publish(total_bytes)
473 }
474
475 fn others(&self) -> Result<Vec<u64>, FootprintError> {
476 self.0.others()
477 }
478}
479
480impl fmt::Debug for AnyFootprintRegistry {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 f.write_str("AnyFootprintRegistry")
483 }
484}
485
486#[derive(Debug, Clone)]
492pub struct FileFootprintRegistry {
493 dir: PathBuf,
494 agent: String,
495 stale_after: Duration,
496}
497
498impl FileFootprintRegistry {
499 const EXTENSION: &'static str = "footprint";
500
501 pub fn new(
509 dir: impl Into<PathBuf>,
510 agent: impl Into<String>,
511 stale_after: Duration,
512 ) -> Result<Self, FootprintError> {
513 let agent = agent.into();
514 if agent.is_empty() || agent.contains(['/', '\\']) || agent.starts_with('.') {
515 return Err(FootprintError::InvalidAgent(agent));
516 }
517 Ok(Self {
518 dir: dir.into(),
519 agent,
520 stale_after,
521 })
522 }
523
524 fn entry(&self) -> PathBuf {
525 self.dir.join(format!("{}.{}", self.agent, Self::EXTENSION))
526 }
527}
528
529impl FootprintRegistry for FileFootprintRegistry {
530 fn publish(&self, total_bytes: u64) -> Result<(), FootprintError> {
531 use std::io::Write as _;
532
533 let io = |source| FootprintError::Io {
534 what: "the footprint registry",
535 source,
536 };
537 if total_bytes == 0 {
538 return match std::fs::remove_file(self.entry()) {
539 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(io(error)),
540 _ => Ok(()),
541 };
542 }
543 std::fs::create_dir_all(&self.dir).map_err(io)?;
544 let mut file = tempfile::NamedTempFile::new_in(&self.dir).map_err(io)?;
545 write!(file, "{total_bytes}").map_err(io)?;
546 file.persist(self.entry())
547 .map_err(|error| io(error.error))?;
548 Ok(())
549 }
550
551 fn others(&self) -> Result<Vec<u64>, FootprintError> {
552 let io = |source| FootprintError::Io {
553 what: "the footprint registry",
554 source,
555 };
556 let entries = match std::fs::read_dir(&self.dir) {
557 Ok(entries) => entries,
558 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
559 Err(error) => return Err(io(error)),
560 };
561 let own = self.entry();
562 let now = SystemTime::now();
563 let mut others = Vec::new();
564 for entry in entries {
565 let path = entry.map_err(io)?.path();
566 if path == own || path.extension().is_none_or(|ext| ext != Self::EXTENSION) {
567 continue;
568 }
569 let Ok(content) = std::fs::read_to_string(&path) else {
571 continue;
572 };
573 let modified = std::fs::metadata(&path).and_then(|meta| meta.modified());
574 if modified
575 .is_ok_and(|at| now.duration_since(at).unwrap_or_default() > self.stale_after)
576 {
577 continue;
578 }
579 let bytes = content
580 .trim()
581 .parse()
582 .map_err(|_| FootprintError::Malformed {
583 what: "a footprint registry entry",
584 content: content.clone(),
585 })?;
586 others.push(bytes);
587 }
588 Ok(others)
589 }
590}
591
592#[derive(Debug, Clone, PartialEq, Eq)]
594pub struct CgroupMemory {
595 pub current_bytes: u64,
597 pub limit_bytes: Option<u64>,
600 pub pressure: String,
602}
603
604impl CgroupMemory {
605 pub fn parse(output: &str) -> Result<Self, FootprintError> {
612 let malformed = || FootprintError::Malformed {
613 what: "the container's memory cgroup",
614 content: output.to_string(),
615 };
616 let mut lines = output.lines();
617 let limit = lines.next().ok_or_else(malformed)?.trim();
618 let limit_bytes = if limit == "max" {
619 None
620 } else {
621 Some(limit.parse().map_err(|_| malformed())?)
622 };
623 let current_bytes = lines
624 .next()
625 .ok_or_else(malformed)?
626 .trim()
627 .parse()
628 .map_err(|_| malformed())?;
629 let pressure = lines.collect::<Vec<_>>().join("\n");
630 Ok(Self {
631 current_bytes,
632 limit_bytes,
633 pressure,
634 })
635 }
636}
637
638pub trait ContainerMemory: Send + Sync + 'static {
641 fn cgroup(&self) -> impl Future<Output = Result<CgroupMemory, FootprintError>> + Send;
643
644 fn job_footprints(
648 &self,
649 task_ids: &[String],
650 ) -> impl Future<Output = Result<Vec<u64>, FootprintError>> + Send;
651}
652
653pub trait ContainerMemoryImpl: Send + Sync {
656 fn cgroup_boxed(
658 &self,
659 ) -> Pin<Box<dyn Future<Output = Result<CgroupMemory, FootprintError>> + Send + '_>>;
660
661 fn job_footprints_boxed<'a>(
663 &'a self,
664 task_ids: &'a [String],
665 ) -> Pin<Box<dyn Future<Output = Result<Vec<u64>, FootprintError>> + Send + 'a>>;
666}
667
668impl<T: ContainerMemory> ContainerMemoryImpl for T {
669 fn cgroup_boxed(
670 &self,
671 ) -> Pin<Box<dyn Future<Output = Result<CgroupMemory, FootprintError>> + Send + '_>> {
672 Box::pin(self.cgroup())
673 }
674
675 fn job_footprints_boxed<'a>(
676 &'a self,
677 task_ids: &'a [String],
678 ) -> Pin<Box<dyn Future<Output = Result<Vec<u64>, FootprintError>> + Send + 'a>> {
679 Box::pin(self.job_footprints(task_ids))
680 }
681}
682
683#[derive(Clone)]
685pub struct AnyContainerMemory(Arc<dyn ContainerMemoryImpl>);
686
687impl AnyContainerMemory {
688 #[must_use]
690 pub fn new(memory: impl ContainerMemory) -> Self {
691 Self(Arc::new(memory))
692 }
693}
694
695impl ContainerMemory for AnyContainerMemory {
696 async fn cgroup(&self) -> Result<CgroupMemory, FootprintError> {
697 self.0.cgroup_boxed().await
698 }
699
700 async fn job_footprints(&self, task_ids: &[String]) -> Result<Vec<u64>, FootprintError> {
701 self.0.job_footprints_boxed(task_ids).await
702 }
703}
704
705impl fmt::Debug for AnyContainerMemory {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 f.write_str("AnyContainerMemory")
708 }
709}
710
711#[derive(Debug, Clone)]
713pub struct ProbedContainerMemory {
714 probe: ContainerProbe,
715}
716
717impl ProbedContainerMemory {
718 #[must_use]
720 pub const fn new(probe: ContainerProbe) -> Self {
721 Self { probe }
722 }
723}
724
725impl ContainerMemory for ProbedContainerMemory {
726 async fn cgroup(&self) -> Result<CgroupMemory, FootprintError> {
727 let output = self
728 .probe
729 .read(include_str!("../templates/container_memory_cgroup.sh"))
730 .await?;
731 CgroupMemory::parse(&output)
732 }
733
734 async fn job_footprints(&self, task_ids: &[String]) -> Result<Vec<u64>, FootprintError> {
735 if task_ids.is_empty() {
736 return Ok(Vec::new());
737 }
738 let output = self
739 .probe
740 .read(include_str!("../templates/container_memory_jobs.sh"))
741 .await?;
742 let mut by_job: BTreeMap<&str, u64> = BTreeMap::new();
743 for line in output.lines() {
744 let malformed = || FootprintError::Malformed {
745 what: "a container job's footprint",
746 content: line.to_string(),
747 };
748 let (id, kib) = line.split_once(' ').ok_or_else(malformed)?;
749 let kib: u64 = kib.trim().parse().map_err(|_| malformed())?;
750 *by_job.entry(id).or_default() += kib * 1024;
751 }
752 Ok(task_ids
753 .iter()
754 .map(|id| by_job.get(id.as_str()).copied().unwrap_or(0))
755 .collect())
756 }
757}
758
759#[derive(Debug, Clone)]
762pub struct ResponseWindow(Arc<AtomicU64>);
763
764impl ResponseWindow {
765 #[must_use]
767 pub fn new(window: Duration) -> Self {
768 let window = Self::nanos(window);
769 Self(Arc::new(AtomicU64::new(window)))
770 }
771
772 fn nanos(window: Duration) -> u64 {
773 u64::try_from(window.as_nanos()).expect("a response window fits in u64 nanoseconds")
774 }
775
776 pub fn set(&self, window: Duration) {
779 self.0.store(Self::nanos(window), Ordering::Relaxed);
780 }
781
782 #[must_use]
784 pub fn get(&self) -> Duration {
785 Duration::from_nanos(self.0.load(Ordering::Relaxed))
786 }
787}
788
789#[derive(Debug, Clone, PartialEq, Eq)]
791pub struct JobFootprint {
792 pub task_id: String,
794 pub command: String,
796 pub pid: u32,
798 pub footprint_bytes: u64,
800}
801
802impl JobFootprint {
803 #[must_use]
805 pub const fn footprint(&self) -> MemorySize {
806 MemorySize(self.footprint_bytes)
807 }
808}
809
810#[derive(Debug, Clone, PartialEq, Eq)]
813pub struct MemorySnapshot {
814 pub domain: MemoryDomain,
816 pub capacity_bytes: u64,
819 pub jobs: Vec<JobFootprint>,
821 pub own_bytes: u64,
823 pub total_bytes: u64,
825 pub largest_contributor: bool,
827}
828
829impl MemorySnapshot {
830 #[must_use]
835 pub const fn exceeded_by(&self, bytes: u64) -> bool {
836 match self.domain {
837 MemoryDomain::Machine => bytes > self.capacity_bytes,
838 MemoryDomain::Container => bytes >= self.capacity_bytes,
839 }
840 }
841}
842
843#[derive(Debug, Clone, PartialEq, Eq)]
845pub struct ContainerSnapshot {
846 pub snapshot: MemorySnapshot,
848 pub pressure: String,
851}
852
853#[derive(Debug, Clone)]
855pub struct JobMemory {
856 jobs: JobRegistry,
857 reader: AnyFootprintReader,
858 registry: Option<AnyFootprintRegistry>,
859 window: ResponseWindow,
860 container: Option<AnyContainerMemory>,
861}
862
863impl JobMemory {
864 #[must_use]
867 pub const fn new(
868 jobs: JobRegistry,
869 reader: AnyFootprintReader,
870 registry: Option<AnyFootprintRegistry>,
871 window: ResponseWindow,
872 ) -> Self {
873 Self {
874 jobs,
875 reader,
876 registry,
877 window,
878 container: None,
879 }
880 }
881
882 #[must_use]
885 pub fn with_container(mut self, container: AnyContainerMemory) -> Self {
886 self.container = Some(container);
887 self
888 }
889
890 #[must_use]
892 pub const fn has_container(&self) -> bool {
893 self.container.is_some()
894 }
895
896 #[must_use]
898 pub fn response_window(&self) -> Duration {
899 self.window.get()
900 }
901
902 async fn running_at(&self, place: JobPlace) -> Vec<crate::JobInfo> {
904 self.jobs
905 .list()
906 .await
907 .into_iter()
908 .filter(|job| job.place == place && matches!(job.status, JobStatus::Running))
909 .collect()
910 }
911
912 pub async fn container_snapshot(&self) -> Result<Option<ContainerSnapshot>, FootprintError> {
920 let Some(container) = &self.container else {
921 return Ok(None);
922 };
923 let cgroup = container.cgroup().await?;
924 let Some(capacity_bytes) = cgroup.limit_bytes else {
925 return Ok(None);
926 };
927 let running = self.running_at(JobPlace::Container).await;
928 let task_ids: Vec<String> = running.iter().map(|job| job.task_id.clone()).collect();
929 let footprints = container.job_footprints(&task_ids).await?;
930 let mut jobs: Vec<JobFootprint> = running
931 .into_iter()
932 .zip(footprints)
933 .map(|(job, footprint_bytes)| JobFootprint {
934 task_id: job.task_id,
935 command: job.script,
936 pid: job.pid,
937 footprint_bytes,
938 })
939 .collect();
940 jobs.sort_by_key(|job| std::cmp::Reverse(job.footprint_bytes));
941 let own_bytes = jobs.iter().map(|job| job.footprint_bytes).sum();
942 Ok(Some(ContainerSnapshot {
943 snapshot: MemorySnapshot {
944 domain: MemoryDomain::Container,
945 capacity_bytes,
946 jobs,
947 own_bytes,
948 total_bytes: own_bytes,
950 largest_contributor: true,
951 },
952 pressure: cgroup.pressure,
953 }))
954 }
955
956 pub async fn snapshot(&self) -> Result<MemorySnapshot, FootprintError> {
964 let running = self.running_at(JobPlace::Host).await;
965 let roots: Vec<u32> = running.iter().map(|job| job.pid).collect();
966 let (reader, registry) = (self.reader.clone(), self.registry.clone());
967 let (footprints, physical_bytes, own_bytes, others) = blocking::unblock(move || {
968 let footprints = reader.tree_footprints(&roots)?;
969 let own: u64 = footprints.iter().sum();
970 let others = match registry {
971 Some(registry) => {
972 registry.publish(own)?;
973 registry.others()?
974 }
975 None => Vec::new(),
976 };
977 Ok::<_, FootprintError>((footprints, reader.physical_memory()?, own, others))
978 })
979 .await?;
980 let mut jobs: Vec<JobFootprint> = running
981 .into_iter()
982 .zip(footprints)
983 .map(|(job, footprint_bytes)| JobFootprint {
984 task_id: job.task_id,
985 command: job.script,
986 pid: job.pid,
987 footprint_bytes,
988 })
989 .collect();
990 jobs.sort_by_key(|job| std::cmp::Reverse(job.footprint_bytes));
991 Ok(MemorySnapshot {
992 domain: MemoryDomain::Machine,
993 capacity_bytes: physical_bytes,
994 jobs,
995 own_bytes,
996 total_bytes: own_bytes + others.iter().sum::<u64>(),
997 largest_contributor: others.iter().all(|other| *other <= own_bytes),
998 })
999 }
1000
1001 pub async fn kill_runaway(&self, job: &JobFootprint, snapshot: &MemorySnapshot) -> bool {
1005 self.jobs
1006 .kill_runaway(
1007 &job.task_id,
1008 job.footprint_bytes,
1009 snapshot.capacity_bytes,
1010 snapshot.domain,
1011 )
1012 .await
1013 }
1014}
1015
1016#[cfg(test)]
1017mod tests {
1018 use super::*;
1019
1020 #[test]
1021 fn sizes_read_in_binary_units() {
1022 assert_eq!(MemorySize(512).to_string(), "512 B");
1023 assert_eq!(MemorySize(1536).to_string(), "1.5 KiB");
1024 assert_eq!(MemorySize(36 * 1024 * 1024 * 1024).to_string(), "36.0 GiB");
1025 }
1026
1027 #[test]
1028 fn the_file_registry_totals_other_agents_and_forgets_withdrawn_and_stale_ones() {
1029 let dir = tempfile::tempdir().unwrap();
1030 let long = Duration::from_secs(3600);
1031 let a = FileFootprintRegistry::new(dir.path(), "a", long).unwrap();
1032 let b = FileFootprintRegistry::new(dir.path(), "b", long).unwrap();
1033 a.publish(100).unwrap();
1034 b.publish(30).unwrap();
1035 assert_eq!(a.others().unwrap(), vec![30]);
1036 assert_eq!(b.others().unwrap(), vec![100]);
1037 a.publish(0).unwrap();
1038 assert_eq!(b.others().unwrap(), Vec::<u64>::new());
1039 let stale = FileFootprintRegistry::new(dir.path(), "c", Duration::ZERO).unwrap();
1040 b.publish(30).unwrap();
1041 std::thread::sleep(Duration::from_millis(20));
1042 assert_eq!(stale.others().unwrap(), Vec::<u64>::new());
1043 assert!(FileFootprintRegistry::new(dir.path(), "../x", long).is_err());
1044 }
1045
1046 #[cfg(any(unix, windows))]
1047 #[test]
1048 fn this_process_tree_has_a_footprint_and_the_machine_has_memory() {
1049 let reader = SystemFootprints;
1050 let footprints = reader.tree_footprints(&[std::process::id()]).unwrap();
1051 assert!(footprints[0] > 0);
1052 assert!(reader.physical_memory().unwrap() > footprints[0]);
1053 }
1054
1055 #[test]
1056 fn the_cgroup_probe_reads_the_limit_the_usage_and_the_pressure() {
1057 let limited = CgroupMemory::parse(
1058 "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",
1059 )
1060 .unwrap();
1061 assert_eq!(limited.limit_bytes, Some(4 * 1024 * 1024 * 1024));
1062 assert_eq!(limited.current_bytes, 1024 * 1024 * 1024);
1063 assert!(limited.pressure.starts_with("some avg10=1.00"));
1064 assert!(limited.pressure.contains("\nfull avg10=0.00"));
1065
1066 let unlimited = CgroupMemory::parse("max\n5\n").unwrap();
1067 assert_eq!(unlimited.limit_bytes, None);
1068 assert_eq!(unlimited.pressure, "");
1069
1070 assert!(CgroupMemory::parse("").is_err());
1071 assert!(CgroupMemory::parse("lots\n5\n").is_err());
1072 assert!(CgroupMemory::parse("max\n").is_err());
1073 }
1074
1075 #[test]
1076 fn a_container_is_exceeded_at_its_limit_and_a_machine_above_its_memory() {
1077 let snapshot = |domain| MemorySnapshot {
1078 domain,
1079 capacity_bytes: 100,
1080 jobs: Vec::new(),
1081 own_bytes: 0,
1082 total_bytes: 0,
1083 largest_contributor: true,
1084 };
1085 let machine = snapshot(MemoryDomain::Machine);
1086 assert!(!machine.exceeded_by(100) && machine.exceeded_by(101));
1087 let container = snapshot(MemoryDomain::Container);
1088 assert!(!container.exceeded_by(99) && container.exceeded_by(100));
1089 }
1090
1091 #[cfg(unix)]
1092 mod placed {
1093 use std::collections::HashMap;
1094 use std::os::unix::process::ExitStatusExt as _;
1095 use std::sync::Mutex;
1096
1097 use async_channel::{Receiver, Sender};
1098
1099 use super::*;
1100 use crate::job_registry::job_registry_channel;
1101 use crate::{
1102 AnyContainerExec, ContainerExec, ContainerExecOutcome, ExecLifetime, SandboxMode,
1103 };
1104
1105 const GIB: u64 = 1024 * 1024 * 1024;
1106
1107 struct Container {
1109 cgroup: &'static str,
1110 jobs: &'static str,
1111 scripts: Mutex<Vec<String>>,
1112 }
1113
1114 impl ContainerExec for Container {
1115 fn exec(
1116 &self,
1117 _container_id: &str,
1118 script: &str,
1119 _working_dir: &str,
1120 _kill_rx: Receiver<()>,
1121 _stdin_rx: Receiver<Vec<u8>>,
1122 _lifetime: ExecLifetime,
1123 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
1124 self.scripts.lock().unwrap().push(script.to_string());
1125 let stdout = if script.contains("memory.max") {
1126 Ok(self.cgroup)
1127 } else if script.contains(JOB_MARKER_ENV) {
1128 Ok(self.jobs)
1129 } else {
1130 Err(format!("unexpected probe: {script}"))
1131 };
1132 std::future::ready(stdout.map(|stdout| ContainerExecOutcome::Completed {
1133 output: std::process::Output {
1134 status: std::process::ExitStatus::from_raw(0),
1135 stdout: stdout.as_bytes().to_vec(),
1136 stderr: Vec::new(),
1137 },
1138 killed: Vec::new(),
1139 }))
1140 }
1141
1142 fn exec_streamed(
1143 &self,
1144 _container_id: &str,
1145 _script: &str,
1146 _working_dir: &str,
1147 _kill_rx: Receiver<()>,
1148 _stdin_rx: Receiver<Vec<u8>>,
1149 _stdout: Sender<Vec<u8>>,
1150 _lifetime: crate::ExecLifetime,
1151 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
1152 std::future::ready(Err("a probe is never streamed".to_string()))
1153 }
1154 }
1155
1156 fn container_memory(
1157 cgroup: &'static str,
1158 jobs: &'static str,
1159 ) -> (Arc<Container>, AnyContainerMemory) {
1160 let container = Arc::new(Container {
1161 cgroup,
1162 jobs,
1163 scripts: Mutex::new(Vec::new()),
1164 });
1165 let exec = AnyContainerExec::new(Arc::clone(&container));
1166 let memory = ProbedContainerMemory::new(ContainerProbe::new(&exec, "box"));
1167 (container, AnyContainerMemory::new(memory))
1168 }
1169
1170 struct Held(HashMap<u32, u64>);
1172
1173 impl FootprintReader for Held {
1174 fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
1175 Ok(roots
1176 .iter()
1177 .map(|pid| self.0.get(pid).copied().unwrap_or(0))
1178 .collect())
1179 }
1180
1181 fn physical_memory(&self) -> Result<u64, FootprintError> {
1182 Ok(16 * GIB)
1183 }
1184 }
1185
1186 async fn memory_with_jobs() -> JobMemory {
1187 let (jobs, service) = job_registry_channel(crate::output_policy::fixture::policy());
1188 tokio::spawn(async move { service.serve().await });
1189 for (place, pid, task) in [
1190 (JobPlace::Host, 1, "host"),
1191 (JobPlace::Container, 2, "boxed"),
1192 (JobPlace::Remote, 3, "remote"),
1193 ] {
1194 jobs.register_at(
1195 place,
1196 pid,
1197 &crate::test_ids::lease(task),
1198 "exec",
1199 task,
1200 crate::Interpreter::Shell,
1201 SandboxMode::Sandboxed,
1202 )
1203 .await;
1204 }
1205 let held = Held(HashMap::from([(1, 2 * GIB), (2, 90 * GIB), (3, 90 * GIB)]));
1208 JobMemory::new(
1209 jobs,
1210 AnyFootprintReader::new(held),
1211 None,
1212 ResponseWindow::new(Duration::from_secs(60)),
1213 )
1214 }
1215
1216 #[tokio::test]
1217 async fn the_machine_counts_only_jobs_that_run_on_it() {
1218 let memory = memory_with_jobs().await;
1219 let snapshot = memory.snapshot().await.unwrap();
1220 let tasks: Vec<_> = snapshot
1221 .jobs
1222 .iter()
1223 .map(|job| job.task_id.as_str())
1224 .collect();
1225 assert_eq!(tasks, ["host"]);
1226 assert_eq!(snapshot.own_bytes, 2 * GIB);
1227 assert_eq!(snapshot.domain, MemoryDomain::Machine);
1228 }
1229
1230 #[tokio::test]
1231 async fn a_container_with_a_limit_is_judged_against_it_with_its_own_jobs() {
1232 let (container, reader) = container_memory(
1233 "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",
1234 "boxed 1048576\nboxed 524288\nother 99\n",
1235 );
1236 let memory = memory_with_jobs().await.with_container(reader);
1237 let snapshot = memory.container_snapshot().await.unwrap().unwrap();
1238 assert_eq!(snapshot.snapshot.domain, MemoryDomain::Container);
1239 assert_eq!(snapshot.snapshot.capacity_bytes, 4 * GIB);
1240 let jobs: Vec<_> = snapshot
1241 .snapshot
1242 .jobs
1243 .iter()
1244 .map(|job| (job.task_id.as_str(), job.footprint_bytes))
1245 .collect();
1246 assert_eq!(jobs, [("boxed", GIB + GIB / 2)]);
1249 assert!(snapshot.pressure.starts_with("some avg10=12.00"));
1250 assert_eq!(container.scripts.lock().unwrap().len(), 2);
1252 }
1253
1254 #[tokio::test]
1255 async fn a_container_without_a_limit_or_a_terminal_without_a_container_adds_nothing() {
1256 let (_, unlimited) = container_memory("max\n123\n", "");
1257 let memory = memory_with_jobs().await.with_container(unlimited);
1258 assert_eq!(memory.container_snapshot().await.unwrap(), None);
1259 assert_eq!(
1260 memory_with_jobs().await.container_snapshot().await.unwrap(),
1261 None
1262 );
1263 }
1264 }
1265}