|
| 1 | +use std::{ |
| 2 | + collections::HashMap, |
| 3 | + os::unix::fs::DirEntryExt, |
| 4 | + path::PathBuf, |
| 5 | + sync::Arc, |
| 6 | + time::{Duration, SystemTime}, |
| 7 | +}; |
| 8 | + |
| 9 | +use tokio::{ |
| 10 | + sync::{watch::Receiver, Mutex}, |
| 11 | + task::JoinHandle, |
| 12 | + time, |
| 13 | +}; |
| 14 | + |
| 15 | +use crate::host_info::get_cgroup_paths; |
| 16 | + |
| 17 | +#[derive(Debug)] |
| 18 | +struct ContainerIdEntry { |
| 19 | + container_id: Option<String>, |
| 20 | + pub last_seen: SystemTime, |
| 21 | +} |
| 22 | + |
| 23 | +type ContainerIdMap = HashMap<u64, ContainerIdEntry>; |
| 24 | + |
| 25 | +#[derive(Debug, Clone, Default)] |
| 26 | +pub struct ContainerIdCache(Arc<Mutex<ContainerIdMap>>); |
| 27 | + |
| 28 | +impl ContainerIdCache { |
| 29 | + pub fn new() -> Self { |
| 30 | + let mut map = HashMap::new(); |
| 31 | + ContainerIdCache::update_unlocked(&mut map); |
| 32 | + ContainerIdCache(Arc::new(Mutex::new(map))) |
| 33 | + } |
| 34 | + |
| 35 | + fn update_unlocked(map: &mut ContainerIdMap) { |
| 36 | + for root in get_cgroup_paths() { |
| 37 | + ContainerIdCache::walk_proc_cgroups_inner(&root, map, None); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + async fn update(&mut self) { |
| 42 | + let mut map = self.0.lock().await; |
| 43 | + ContainerIdCache::update_unlocked(&mut map); |
| 44 | + } |
| 45 | + |
| 46 | + async fn prune(&mut self) { |
| 47 | + let now = SystemTime::now(); |
| 48 | + self.0.lock().await.retain(|_, value| { |
| 49 | + now.duration_since(value.last_seen).unwrap() < Duration::from_secs(30) |
| 50 | + }) |
| 51 | + } |
| 52 | + |
| 53 | + pub async fn get_container_id(&self, cgroup_id: u64) -> Option<String> { |
| 54 | + let mut map = self.0.lock().await; |
| 55 | + match map.get(&cgroup_id) { |
| 56 | + Some(entry) => entry.container_id.clone(), |
| 57 | + None => { |
| 58 | + // Update the container ID cache and try again |
| 59 | + ContainerIdCache::update_unlocked(&mut map); |
| 60 | + map.get(&cgroup_id).map(|s| s.container_id.clone())? |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + pub fn start_worker(mut self, mut running: Receiver<bool>) -> JoinHandle<()> { |
| 66 | + let mut update_interval = time::interval(time::Duration::from_secs(30)); |
| 67 | + tokio::spawn(async move { |
| 68 | + loop { |
| 69 | + tokio::select! { |
| 70 | + _ = update_interval.tick() => { |
| 71 | + self.update().await; |
| 72 | + self.prune().await; |
| 73 | + }, |
| 74 | + _ = running.changed() => { |
| 75 | + if !*running.borrow() { |
| 76 | + return; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + }) |
| 82 | + } |
| 83 | + |
| 84 | + fn walk_proc_cgroups_inner(path: &PathBuf, map: &mut ContainerIdMap, parent_id: Option<&str>) { |
| 85 | + for entry in std::fs::read_dir(path).unwrap() { |
| 86 | + let entry = entry.unwrap(); |
| 87 | + let p = entry.path(); |
| 88 | + if !p.is_dir() { |
| 89 | + continue; |
| 90 | + } |
| 91 | + |
| 92 | + let container_id = match map.get_mut(&entry.ino()) { |
| 93 | + Some(e) => { |
| 94 | + e.last_seen = SystemTime::now(); |
| 95 | + e.container_id.clone() |
| 96 | + } |
| 97 | + None => { |
| 98 | + let last_component = p |
| 99 | + .file_name() |
| 100 | + .map(|f| f.to_str().unwrap_or("")) |
| 101 | + .unwrap_or(""); |
| 102 | + let container_id = match ContainerIdCache::extract_container_id(last_component) |
| 103 | + { |
| 104 | + Some(cid) => Some(cid), |
| 105 | + None => parent_id.map(|f| f.to_owned()), |
| 106 | + }; |
| 107 | + let last_seen = SystemTime::now(); |
| 108 | + map.insert( |
| 109 | + entry.ino(), |
| 110 | + ContainerIdEntry { |
| 111 | + container_id: container_id.clone(), |
| 112 | + last_seen, |
| 113 | + }, |
| 114 | + ); |
| 115 | + container_id |
| 116 | + } |
| 117 | + }; |
| 118 | + ContainerIdCache::walk_proc_cgroups_inner(&p, map, container_id.as_deref()); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + pub fn extract_container_id(cgroup: &str) -> Option<String> { |
| 123 | + if cgroup.is_empty() { |
| 124 | + return None; |
| 125 | + } |
| 126 | + |
| 127 | + let cgroup = cgroup.strip_suffix(".scope").unwrap_or(cgroup); |
| 128 | + if cgroup.len() < 64 { |
| 129 | + return None; |
| 130 | + } |
| 131 | + |
| 132 | + let (prefix, id) = cgroup.split_at(cgroup.len() - 64); |
| 133 | + |
| 134 | + if !prefix.is_empty() && !prefix.ends_with('-') { |
| 135 | + return None; |
| 136 | + } |
| 137 | + |
| 138 | + if id.chars().all(|c| c.is_ascii_hexdigit()) { |
| 139 | + Some(id.split_at(12).0.to_owned()) |
| 140 | + } else { |
| 141 | + None |
| 142 | + } |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +#[cfg(test)] |
| 147 | +mod tests { |
| 148 | + use super::*; |
| 149 | + |
| 150 | + #[test] |
| 151 | + fn extract_container_id() { |
| 152 | + let tests = [ |
| 153 | + ("e73c55f3e7f5b6a9cfc32a89bf13e44d348bcc4fa7b079f804d61fb1532ddbe5", Some("e73c55f3e7f5")), |
| 154 | + ("cri-containerd-219d7afb8e7450929eaeb06f2d27cbf7183bfa5b55b7275696f3df4154a979af.scope", Some("219d7afb8e74")), |
| 155 | + ("kubelet-kubepods-burstable-pod469726a5_079d_4d15_a259_1f654b534b44.slice", None), |
| 156 | + ("libpod-conmon-a2d2a36121868d946af912b931fc5f6b42bf84c700cef67784422b1e2c8585ee.scope", Some("a2d2a3612186")), |
| 157 | + ("init.scope", None), |
| 158 | + ("app-flatpak-com.github.IsmaelMartinez.teams_for_linux-384393947.scope", None), |
| 159 | + ]; |
| 160 | + |
| 161 | + for (cgroup, expected) in tests { |
| 162 | + let cid = ContainerIdCache::extract_container_id(cgroup); |
| 163 | + assert_eq!(cid.as_deref(), expected); |
| 164 | + } |
| 165 | + } |
| 166 | +} |
0 commit comments