Debian Codegraph @

src/app/data/process.rs

raw symbols SCIP
1 use std::{collections::BTreeMap, vec::Vec};
2
3 use crate::{
4 collection::processes::{Pid, ProcessHarvest},
5 utils::int_hash::IntHashMap,
6 };
7
8 #[derive(Clone, Debug, Default)]
9 pub struct ProcessData {
10 /// A PID to process data map.
11 pub process_harvest: BTreeMap<Pid, ProcessHarvest>,
12
13 /// A mapping between a process PID to any children process PIDs.
14 pub process_parent_mapping: IntHashMap<Pid, Vec<Pid>>,
15
16 /// PIDs corresponding to processes that have no parents.
17 pub orphan_pids: Vec<Pid>,
18 }
19
20 impl ProcessData {
21 pub(super) fn ingest(&mut self, list_of_processes: Vec<ProcessHarvest>) {
22 self.process_parent_mapping.clear();
23
24 // Reverse as otherwise the pid mappings are in the wrong order.
25 list_of_processes.iter().rev().for_each(|process_harvest| {
26 if let Some(parent_pid) = process_harvest.parent_pid {
27 if let Some(entry) = self.process_parent_mapping.get_mut(&parent_pid) {
28 entry.push(process_harvest.pid);
29 } else {
30 self.process_parent_mapping
31 .insert(parent_pid, vec![process_harvest.pid]);
32 }
33 }
34 });
35
36 self.process_parent_mapping.shrink_to_fit();
37
38 let process_pid_map = list_of_processes
39 .into_iter()
40 .map(|process| (process.pid, process))
41 .collect();
42 self.process_harvest = process_pid_map;
43
44 // We collect all processes that either:
45 // - Do not have a parent PID (that is, they are orphan processes)
46 // - Have a parent PID but we don't have the parent (we promote them as orphans)
47 self.orphan_pids = self
48 .process_harvest
49 .iter()
50 .filter_map(|(pid, process_harvest)| match process_harvest.parent_pid {
51 Some(parent_pid) if self.process_harvest.contains_key(&parent_pid) => None,
52 _ => Some(*pid),
53 })
54 .collect();
55 }
56 }