adk_harness/shell/
pids.rs1use std::sync::Mutex;
11
12use adk_core::Result;
13use async_trait::async_trait;
14use serde::{Deserialize, Serialize};
15
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct ShellPidRecord {
34 pub pid: u32,
36 pub started: String,
38 pub owner_pid: u32,
40 pub owner_started: String,
42}
43
44#[async_trait]
64pub trait ShellPidRegistry: Send + Sync {
65 async fn register(&self, record: &ShellPidRecord) -> Result<()>;
67
68 async fn remove(&self, record: &ShellPidRecord) -> Result<()>;
70
71 async fn list(&self) -> Result<Vec<ShellPidRecord>>;
73}
74
75#[derive(Debug, Default)]
78pub struct InMemoryShellPidRegistry {
79 records: Mutex<Vec<ShellPidRecord>>,
80}
81
82#[async_trait]
83impl ShellPidRegistry for InMemoryShellPidRegistry {
84 async fn register(&self, record: &ShellPidRecord) -> Result<()> {
85 let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
86 records.retain(|existing| existing != record);
87 records.push(record.clone());
88 Ok(())
89 }
90
91 async fn remove(&self, record: &ShellPidRecord) -> Result<()> {
92 self.records
93 .lock()
94 .unwrap_or_else(std::sync::PoisonError::into_inner)
95 .retain(|existing| existing != record);
96 Ok(())
97 }
98
99 async fn list(&self) -> Result<Vec<ShellPidRecord>> {
100 Ok(self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone())
101 }
102}
103
104#[cfg(feature = "sqlite")]
116#[derive(Debug, Clone)]
117pub struct SqliteShellPidRegistry {
118 pool: sqlx::SqlitePool,
119}
120
121#[cfg(feature = "sqlite")]
122impl SqliteShellPidRegistry {
123 pub fn new(pool: sqlx::SqlitePool) -> Self {
125 Self { pool }
126 }
127
128 pub async fn migrate(&self) -> Result<()> {
134 sqlx::query(
135 "CREATE TABLE IF NOT EXISTS adk_harness_shell_pids (\
136 pid INTEGER NOT NULL, started TEXT NOT NULL, owner_pid INTEGER NOT NULL, \
137 owner_started TEXT NOT NULL, PRIMARY KEY (pid, started))",
138 )
139 .execute(&self.pool)
140 .await
141 .map_err(crate::fsutil::db_error)?;
142 Ok(())
143 }
144}
145
146#[cfg(feature = "sqlite")]
147#[async_trait]
148impl ShellPidRegistry for SqliteShellPidRegistry {
149 async fn register(&self, record: &ShellPidRecord) -> Result<()> {
150 sqlx::query(
151 "INSERT OR REPLACE INTO adk_harness_shell_pids \
152 (pid, started, owner_pid, owner_started) VALUES (?, ?, ?, ?)",
153 )
154 .bind(i64::from(record.pid))
155 .bind(&record.started)
156 .bind(i64::from(record.owner_pid))
157 .bind(&record.owner_started)
158 .execute(&self.pool)
159 .await
160 .map_err(crate::fsutil::db_error)?;
161 Ok(())
162 }
163
164 async fn remove(&self, record: &ShellPidRecord) -> Result<()> {
165 sqlx::query("DELETE FROM adk_harness_shell_pids WHERE pid = ? AND started = ?")
166 .bind(i64::from(record.pid))
167 .bind(&record.started)
168 .execute(&self.pool)
169 .await
170 .map_err(crate::fsutil::db_error)?;
171 Ok(())
172 }
173
174 async fn list(&self) -> Result<Vec<ShellPidRecord>> {
175 let rows: Vec<(i64, String, i64, String)> = sqlx::query_as(
176 "SELECT pid, started, owner_pid, owner_started FROM adk_harness_shell_pids",
177 )
178 .fetch_all(&self.pool)
179 .await
180 .map_err(crate::fsutil::db_error)?;
181 Ok(rows
182 .into_iter()
183 .filter_map(|(pid, started, owner_pid, owner_started)| {
184 Some(ShellPidRecord {
185 pid: u32::try_from(pid).ok()?,
186 started,
187 owner_pid: u32::try_from(owner_pid).ok()?,
188 owner_started,
189 })
190 })
191 .collect())
192 }
193}
194
195pub(crate) fn process_start(pid: u32) -> Option<String> {
198 #[cfg(target_os = "macos")]
199 {
200 let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
201 let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
202 let written = unsafe {
205 libc::proc_pidinfo(
206 pid as libc::c_int,
207 libc::PROC_PIDTBSDINFO,
208 0,
209 std::ptr::from_mut(&mut info).cast(),
210 size,
211 )
212 };
213 (written == size).then(|| format!("{}.{:06}", info.pbi_start_tvsec, info.pbi_start_tvusec))
214 }
215 #[cfg(target_os = "linux")]
216 {
217 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
220 let after_name = &stat[stat.rfind(')')? + 1..];
221 after_name.split_whitespace().nth(19).map(str::to_string)
222 }
223 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
224 {
225 let _ = pid;
226 None
227 }
228}
229
230pub(crate) fn this_process() -> Option<(u32, String)> {
232 let pid = std::process::id();
233 process_start(pid).map(|started| (pid, started))
234}
235
236pub async fn reap_orphaned_shells(registry: &dyn ShellPidRegistry) -> Result<usize> {
260 let mut killed = 0;
261 for record in registry.list().await? {
262 let owner = process_start(record.owner_pid);
263 if owner.as_deref() == Some(record.owner_started.as_str()) {
264 continue;
265 }
266 if this_process().is_none() {
268 continue;
269 }
270 let current = process_start(record.pid);
271 if current.is_none() || current.as_deref() == Some(record.started.as_str()) {
272 #[cfg(unix)]
273 let signalled = unsafe { libc::killpg(record.pid as libc::pid_t, libc::SIGKILL) } == 0;
276 #[cfg(not(unix))]
277 let signalled = false;
278 if signalled {
279 killed += 1;
280 tracing::info!(
281 process.pid = record.pid,
282 "reaped a background shell a crash left running"
283 );
284 }
285 }
286 registry.remove(&record).await?;
287 }
288 Ok(killed)
289}
290
291#[cfg(all(test, unix))]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn this_process_has_a_start_time_that_does_not_change() {
297 if cfg!(not(any(target_os = "macos", target_os = "linux"))) {
298 return;
299 }
300 let (pid, started) = this_process().expect("macOS and Linux report a start time");
301 assert_eq!(pid, std::process::id());
302 assert_eq!(process_start(pid), Some(started));
303 }
304
305 #[tokio::test]
309 async fn an_orphan_is_killed_and_a_reused_pid_is_not() {
310 if cfg!(not(any(target_os = "macos", target_os = "linux"))) {
311 return;
312 }
313 let spawn = || {
314 let mut command = std::process::Command::new("sleep");
315 command.arg("30");
316 unsafe {
318 std::os::unix::process::CommandExt::pre_exec(&mut command, || {
319 libc::setsid();
320 Ok(())
321 });
322 }
323 command.spawn().unwrap()
324 };
325 let mut orphan = spawn();
326 let mut reused = spawn();
327 let registry = InMemoryShellPidRegistry::default();
328 let dead_owner = |pid: u32, started: String| ShellPidRecord {
330 pid,
331 started,
332 owner_pid: u32::MAX - 1,
333 owner_started: "never".into(),
334 };
335 registry
336 .register(&dead_owner(orphan.id(), process_start(orphan.id()).unwrap()))
337 .await
338 .unwrap();
339 registry.register(&dead_owner(reused.id(), "0.000001".into())).await.unwrap();
340
341 assert_eq!(reap_orphaned_shells(®istry).await.unwrap(), 1);
342 assert!(registry.list().await.unwrap().is_empty());
343 let status = orphan.wait().unwrap();
344 assert!(!status.success(), "the orphan was killed: {status:?}");
345 assert!(reused.try_wait().unwrap().is_none(), "a reused pid is never signalled");
346 reused.kill().unwrap();
347 reused.wait().unwrap();
348 }
349
350 #[tokio::test]
351 async fn a_live_owners_shells_are_left_alone() {
352 let Some((pid, started)) = this_process() else { return };
353 let registry = InMemoryShellPidRegistry::default();
354 let record =
355 ShellPidRecord { pid: 1, started: "x".into(), owner_pid: pid, owner_started: started };
356 registry.register(&record).await.unwrap();
357 assert_eq!(reap_orphaned_shells(®istry).await.unwrap(), 0);
358 assert_eq!(registry.list().await.unwrap(), vec![record]);
359 }
360}