oxedyne/fe2o3/fe2o3_sys/tests/signal.rs
15.2 KiB, 5 runs
created by r1870400018:66885, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Tests for `fe2o3_sys::signal` against real processes and the kernel's own account of them. |
| 2 | //! |
| 3 | //! Every tree is made of `sh` and `sleep`, whose parentage the kernel reports in |
| 4 | //! `/proc/<pid>/status`, a file the module under test does not read. A signal's effect is seen in |
| 5 | //! what the processes do with it: a shell that traps `TERM` writes a file, and one that does not |
| 6 | //! dies. The group tests run a copy of this test binary as the program that signals, because the |
| 7 | //! caller of `to_own_group` is itself in the group it signals and must outlive it. |
| 8 | |
| 9 | #![cfg(all(target_os = "linux", feature = "signal"))] |
| 10 | |
| 11 | use oxedyne_fe2o3_core::prelude::*; |
| 12 | use oxedyne_fe2o3_core::stop::on_stop_request; |
| 13 | use oxedyne_fe2o3_sys::signal::{ |
| 14 | still_running, |
| 15 | to_members, |
| 16 | to_group, |
| 17 | to_own_group, |
| 18 | tree_of, |
| 19 | Proc, |
| 20 | Signal, |
| 21 | }; |
| 22 | |
| 23 | use nix::sys::signal::{ |
| 24 | killpg, |
| 25 | Signal as Sig, |
| 26 | }; |
| 27 | use nix::unistd::Pid; |
| 28 | |
| 29 | use std::{ |
| 30 | collections::BTreeMap, |
| 31 | env, |
| 32 | fs, |
| 33 | os::unix::process::CommandExt, |
| 34 | path::PathBuf, |
| 35 | process::{ |
| 36 | Child, |
| 37 | Command, |
| 38 | Stdio, |
| 39 | }, |
| 40 | thread, |
| 41 | time::{ |
| 42 | Duration, |
| 43 | Instant, |
| 44 | }, |
| 45 | }; |
| 46 | |
| 47 | const HELPER: &str = "FE2O3_SYS_SIGNAL_HELPER"; |
| 48 | const MODE: &str = "FE2O3_SYS_SIGNAL_MODE"; |
| 49 | const NAP: Duration = Duration::from_millis(20); |
| 50 | const PATIENCE: Duration = Duration::from_secs(8); |
| 51 | |
| 52 | // A shell that notes the signal it is given and ends, after a pause if it is told one. |
| 53 | const TRAPPER: &str = "trap 'sleep \"$4\"; echo got > \"$1\"; exit 0' TERM |
| 54 | echo up > \"$2\" |
| 55 | n=0 |
| 56 | while [ $n -lt $3 ]; do sleep 0.1; n=$((n + 1)); done |
| 57 | "; |
| 58 | |
| 59 | // A shell that starts the trapper below it, and notes the signal itself. |
| 60 | const PARENT: &str = "trap 'echo got > \"$1\"; exit 0' TERM |
| 61 | sh \"$2\" \"$3\" \"$4\" 50 0 & |
| 62 | n=0 |
| 63 | while [ $n -lt 50 ]; do sleep 0.1; n=$((n + 1)); done |
| 64 | "; |
| 65 | |
| 66 | fn io<T>(r: std::io::Result<T>, what: &str) -> Outcome<T> { |
| 67 | match r { |
| 68 | Ok(v) => Ok(v), |
| 69 | Err(e) => Err(err!("{}: {}.", what, e; IO, File)), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // A directory of this test's own, under the caller's temporary directory. |
| 74 | struct Dir(PathBuf); |
| 75 | |
| 76 | impl Dir { |
| 77 | fn new(what: &str) -> Outcome<Self> { |
| 78 | let path = env::temp_dir().join(format!("fe2o3_sys_signal_{}_{}", what, std::process::id())); |
| 79 | let _ = fs::remove_dir_all(&path); |
| 80 | res!(io(fs::create_dir_all(&path), "make the test directory")); |
| 81 | Ok(Self(path)) |
| 82 | } |
| 83 | |
| 84 | fn file(&self, name: &str) -> PathBuf { |
| 85 | self.0.join(name) |
| 86 | } |
| 87 | |
| 88 | fn script(&self, name: &str, body: &str) -> Outcome<PathBuf> { |
| 89 | let path = self.file(name); |
| 90 | res!(io(fs::write(&path, body), "write a script")); |
| 91 | Ok(path) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | impl Drop for Dir { |
| 96 | fn drop(&mut self) { |
| 97 | let _ = fs::remove_dir_all(&self.0); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // A process group that is ended however the test does. |
| 102 | struct Group(i32); |
| 103 | |
| 104 | impl Drop for Group { |
| 105 | fn drop(&mut self) { |
| 106 | let _ = killpg(Pid::from_raw(self.0), Sig::SIGKILL); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn until<F: Fn() -> bool>(what: &str, ask: F) -> Outcome<()> { |
| 111 | let begun = Instant::now(); |
| 112 | while !ask() { |
| 113 | if begun.elapsed() > PATIENCE { |
| 114 | return Err(err!("Waited {} s for {}.", PATIENCE.as_secs(), what; Test, Timeout)); |
| 115 | } |
| 116 | thread::sleep(NAP); |
| 117 | } |
| 118 | Ok(()) |
| 119 | } |
| 120 | |
| 121 | // What the kernel's status file says a process's parent is. |
| 122 | fn parent_of(pid: u32) -> Option<u32> { |
| 123 | let text = fs::read_to_string(format!("/proc/{}/status", pid)).ok()?; |
| 124 | text.lines() |
| 125 | .find_map(|l| l.strip_prefix("PPid:")) |
| 126 | .and_then(|v| v.trim().parse().ok()) |
| 127 | } |
| 128 | |
| 129 | // A root shell, in a group of its own, over a shell, over a `sleep`, and the tree read once all three stand. |
| 130 | fn three_deep() -> Outcome<(Child, Group, Vec<Proc>)> { |
| 131 | let child = res!(io(Command::new("sh") |
| 132 | .args(["-c", "sh -c 'sleep 60; :'; :"]) |
| 133 | .process_group(0) |
| 134 | .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()) |
| 135 | .spawn(), "start the tree")); |
| 136 | let group = Group(child.id() as i32); |
| 137 | let root = child.id(); |
| 138 | until("the tree to stand three deep", || { |
| 139 | match tree_of(root) { |
| 140 | Ok(t) => t.len() >= 3, |
| 141 | Err(_) => false, |
| 142 | } |
| 143 | })?; |
| 144 | let tree = res!(tree_of(root)); |
| 145 | Ok((child, group, tree)) |
| 146 | } |
| 147 | |
| 148 | #[test] |
| 149 | fn tree_of_reads_a_real_tree_with_each_process_after_the_one_that_started_it() -> Outcome<()> { |
| 150 | let (mut child, _group, tree) = res!(three_deep()); |
| 151 | assert_eq!(tree[0].pid, child.id(), "the tree starts at the process asked about"); |
| 152 | assert_eq!(tree.len(), 3, "a shell, a shell and a sleep: {:?}", tree); |
| 153 | for (at, one) in tree.iter().enumerate().skip(1) { |
| 154 | let parent = match parent_of(one.pid) { |
| 155 | Some(p) => p, |
| 156 | None => return Err(err!("The kernel has no status for process {}.", one.pid; Test, Missing)), |
| 157 | }; |
| 158 | let before = tree[..at].iter().any(|p| p.pid == parent); |
| 159 | assert!(before, "process {} was started by {}, which is not earlier in {:?}", one.pid, parent, tree); |
| 160 | } |
| 161 | assert_eq!(still_running(&tree).len(), 3, "all three run"); |
| 162 | let _ = child.kill(); |
| 163 | let _ = child.wait(); |
| 164 | Ok(()) |
| 165 | } |
| 166 | |
| 167 | #[test] |
| 168 | fn a_signal_to_a_tree_goes_to_the_farthest_first_and_ends_every_process() -> Outcome<()> { |
| 169 | let (mut child, _group, tree) = res!(three_deep()); |
| 170 | let mut parents: BTreeMap<u32, u32> = BTreeMap::new(); |
| 171 | for one in &tree { |
| 172 | if let Some(p) = parent_of(one.pid) { |
| 173 | parents.insert(one.pid, p); |
| 174 | } |
| 175 | } |
| 176 | let sent = to_members(&tree, Signal::Terminate); |
| 177 | assert_eq!(sent.len(), 3, "every process was reached: {:?}", sent); |
| 178 | // The kernel's own parentage, read before anything was signalled: no process is reached before |
| 179 | // each process it started. |
| 180 | for (at, pid) in sent.iter().enumerate() { |
| 181 | for (kid, parent) in &parents { |
| 182 | if parent == pid { |
| 183 | let kid_at = sent.iter().position(|p| p == kid); |
| 184 | assert!( |
| 185 | matches!(kid_at, Some(k) if k < at), |
| 186 | "process {} was reached before {}, which it started: {:?}", pid, kid, sent); |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | let _ = child.wait(); |
| 191 | res!(until("every process to end", || still_running(&tree).is_empty())); |
| 192 | Ok(()) |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn a_shell_that_ends_at_once_does_not_say_the_program_beneath_it_has() -> Outcome<()> { |
| 197 | let dir = res!(Dir::new("trapper")); |
| 198 | let trapper = res!(dir.script("trapper.sh", TRAPPER)); |
| 199 | let (got, up) = (dir.file("got"), dir.file("up")); |
| 200 | // The program is slow to end: it traps the signal, saves for a second and goes. The shell above |
| 201 | // it has no trap and ends where it stands, which is what `sh -c` does for an editor. |
| 202 | let mut child = res!(io(Command::new("sh") |
| 203 | .arg("-c") |
| 204 | .arg("sh \"$0\" \"$1\" \"$2\" 100 1; :") |
| 205 | .arg(&trapper).arg(&got).arg(&up) |
| 206 | .process_group(0) |
| 207 | .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()) |
| 208 | .spawn(), "start the shell")); |
| 209 | let _group = Group(child.id() as i32); |
| 210 | res!(until("the program to start", || up.is_file())); |
| 211 | let tree = res!(tree_of(child.id())); |
| 212 | let program = tree[1]; |
| 213 | assert!(tree.len() >= 2, "the shell and the program: {:?}", tree); |
| 214 | to_members(&tree, Signal::Terminate); |
| 215 | let _ = child.wait(); |
| 216 | assert!(!tree[0].running(), "the shell ended with the signal"); |
| 217 | assert!(program.running(), "the program, saving for a second, is still running: {:?}", still_running(&tree)); |
| 218 | assert!(!got.exists(), "it has not saved yet"); |
| 219 | res!(until("the program to end", || still_running(&tree).is_empty())); |
| 220 | assert!(got.is_file(), "the program was reached and saved before it ended"); |
| 221 | Ok(()) |
| 222 | } |
| 223 | |
| 224 | // The program that signals, run by the tests below as a copy of this binary. It is told its |
| 225 | // directory, and whether it was started to lead a group; it starts a shell that starts another, |
| 226 | // each noting `TERM` in a file, and signals its own group. |
| 227 | #[test] |
| 228 | fn helper_that_signals_its_own_group() -> Outcome<()> { |
| 229 | let dir = match env::var(HELPER) { |
| 230 | Ok(d) => PathBuf::from(d), |
| 231 | Err(_) => return Ok(()), |
| 232 | }; |
| 233 | let leads = env::var(MODE).map(|m| m == "lead").unwrap_or(false); |
| 234 | // The caller is in the group it signals, so it hears the signal too and must not end by it. |
| 235 | res!(on_stop_request(|_| {})); |
| 236 | until("the stop listener to be installed", || { |
| 237 | match fs::read_to_string("/proc/self/status") { |
| 238 | // The mask of caught signals, the fifteenth bit of which is SIGTERM. |
| 239 | Ok(s) => s.lines() |
| 240 | .find_map(|l| l.strip_prefix("SigCgt:")) |
| 241 | .and_then(|m| u64::from_str_radix(m.trim(), 16).ok()) |
| 242 | .map(|m| m & (1 << 14) != 0) |
| 243 | .unwrap_or(false), |
| 244 | Err(_) => false, |
| 245 | } |
| 246 | })?; |
| 247 | let (mid, leaf, up) = (dir.join("mid"), dir.join("leaf"), dir.join("up")); |
| 248 | let child = res!(io(Command::new("sh") |
| 249 | .arg(dir.join("parent.sh")).arg(&mid).arg(dir.join("trapper.sh")).arg(&leaf).arg(&up) |
| 250 | .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()) |
| 251 | .spawn(), "start the shells")); |
| 252 | res!(until("the shells to start", || up.is_file())); |
| 253 | let sent = res!(to_own_group(Signal::Terminate)); |
| 254 | println!("HELPER sent={} leads={}", sent, leads); |
| 255 | match sent { |
| 256 | true => { |
| 257 | res!(until("both shells to note the signal", || mid.is_file() && leaf.is_file())); |
| 258 | println!("HELPER noted=2"); |
| 259 | }, |
| 260 | false => { |
| 261 | thread::sleep(Duration::from_millis(1_000)); |
| 262 | println!("HELPER noted={}", [&mid, &leaf].iter().filter(|p| p.is_file()).count()); |
| 263 | let mut child = child; |
| 264 | let _ = child.kill(); |
| 265 | let _ = child.wait(); |
| 266 | }, |
| 267 | } |
| 268 | Ok(()) |
| 269 | } |
| 270 | |
| 271 | // Runs the helper in this directory, and what it printed. |
| 272 | fn run_helper(dir: &Dir, lead: bool) -> Outcome<(Vec<String>, Group)> { |
| 273 | let exe = res!(io(env::current_exe(), "find this test binary")); |
| 274 | let mut cmd = Command::new(exe); |
| 275 | cmd.args(["--exact", "helper_that_signals_its_own_group", "--nocapture", "--test-threads=1"]) |
| 276 | .env(HELPER, &dir.0) |
| 277 | .env(MODE, if lead { "lead" } else { "follow" }) |
| 278 | .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); |
| 279 | if lead { |
| 280 | cmd.process_group(0); |
| 281 | } |
| 282 | let child = res!(io(cmd.spawn(), "start the helper")); |
| 283 | let group = Group(child.id() as i32); |
| 284 | let out = res!(io(child.wait_with_output(), "wait on the helper")); |
| 285 | let text = String::from_utf8_lossy(&out.stdout).to_string(); |
| 286 | assert!(out.status.success(), "the helper failed ({}): {}", out.status, text); |
| 287 | // The harness leaves its own "test ... " on the line the first print lands on. |
| 288 | Ok((text.lines().filter_map(|l| l.find("HELPER ").map(|i| l[i..].to_string())).collect(), group)) |
| 289 | } |
| 290 | |
| 291 | fn stand_the_shells(dir: &Dir) -> Outcome<()> { |
| 292 | res!(dir.script("trapper.sh", TRAPPER)); |
| 293 | res!(dir.script("parent.sh", PARENT)); |
| 294 | Ok(()) |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn a_group_signal_reaches_a_child_and_a_grandchild_of_a_caller_that_leads_the_group() -> Outcome<()> { |
| 299 | let dir = res!(Dir::new("lead")); |
| 300 | res!(stand_the_shells(&dir)); |
| 301 | let (said, _group) = res!(run_helper(&dir, true)); |
| 302 | assert!(said.iter().any(|l| l == "HELPER sent=true leads=true"), "{:?}", said); |
| 303 | assert!(said.iter().any(|l| l == "HELPER noted=2"), "{:?}", said); |
| 304 | assert!(dir.file("mid").is_file(), "the child noted the signal"); |
| 305 | assert!(dir.file("leaf").is_file(), "and so did the grandchild"); |
| 306 | Ok(()) |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn a_caller_that_does_not_lead_its_group_declines_and_signals_nobody() -> Outcome<()> { |
| 311 | let dir = res!(Dir::new("follow")); |
| 312 | res!(stand_the_shells(&dir)); |
| 313 | let (said, _group) = res!(run_helper(&dir, false)); |
| 314 | assert!(said.iter().any(|l| l == "HELPER sent=false leads=false"), "{:?}", said); |
| 315 | assert!(said.iter().any(|l| l == "HELPER noted=0"), "{:?}", said); |
| 316 | assert!(!dir.file("mid").exists() && !dir.file("leaf").exists(), "a signal went out"); |
| 317 | Ok(()) |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn a_process_is_known_by_its_start_and_not_by_its_number_alone() -> Outcome<()> { |
| 322 | let mut child = res!(io(Command::new("sleep").arg("30").spawn(), "start a sleep")); |
| 323 | let seen = Proc::of(child.id()); |
| 324 | assert!(matches!(seen, Some(p) if p.pid == child.id() && p.running()), "{:?}", seen); |
| 325 | let _ = child.kill(); |
| 326 | let _ = child.wait(); |
| 327 | let gone = match seen { |
| 328 | Some(p) => p, |
| 329 | None => return Err(err!("The sleep was not seen."; Test, Missing)), |
| 330 | }; |
| 331 | assert!(!gone.running(), "a process that has been waited on is not running"); |
| 332 | assert_eq!(Proc::of(child.id()), None, "and its number is not one"); |
| 333 | Ok(()) |
| 334 | } |
| 335 | |
| 336 | #[test] |
| 337 | fn a_process_that_has_ended_and_awaits_its_parents_wait_is_not_running() -> Outcome<()> { |
| 338 | let mut child = res!(io(Command::new("sleep").arg("0.4").spawn(), "start a sleep")); |
| 339 | let seen = match Proc::of(child.id()) { |
| 340 | Some(p) => p, |
| 341 | None => return Err(err!("The sleep was not seen."; Test, Missing)), |
| 342 | }; |
| 343 | assert!(seen.running()); |
| 344 | // The kernel's own word for it: state Z in its status, with this process not having waited. |
| 345 | let state = |pid: u32| fs::read_to_string(format!("/proc/{}/status", pid)).ok() |
| 346 | .and_then(|t| t.lines().find_map(|l| l.strip_prefix("State:").map(|v| v.trim().to_string()))); |
| 347 | res!(until("the sleep to end and wait to be waited on", || { |
| 348 | state(child.id()).map(|s| s.starts_with('Z')).unwrap_or(false) |
| 349 | })); |
| 350 | assert!(!seen.running(), "an ended process, still in the table, is not running"); |
| 351 | assert_eq!(Proc::of(child.id()), None, "and is not one that can be signalled"); |
| 352 | assert!(still_running(&[seen]).is_empty()); |
| 353 | let _ = child.wait(); |
| 354 | Ok(()) |
| 355 | } |
| 356 | |
| 357 | // A shell leading a group of its own, over a `sleep` it started: a signal to the group by the |
| 358 | // shell's number ends both, which the kernel's own table shows. |
| 359 | #[test] |
| 360 | fn a_signal_to_a_group_the_caller_started_ends_its_child_and_grandchild() -> Outcome<()> { |
| 361 | let dir = res!(Dir::new("to_group")); |
| 362 | let note = dir.file("grandchild"); |
| 363 | let mut child = res!(io(Command::new("sh") |
| 364 | .arg("-c").arg("sleep 30 & echo $! > \"$1\"; wait") |
| 365 | .arg("sh").arg(¬e) |
| 366 | .process_group(0) |
| 367 | .stdin(Stdio::null()) |
| 368 | .spawn(), "start a shell leading its own group")); |
| 369 | let _group = Group(child.id() as i32); |
| 370 | res!(until("the shell to note its sleep", || { |
| 371 | fs::read_to_string(¬e).map(|t| t.ends_with('\n')).unwrap_or(false) |
| 372 | })); |
| 373 | let grandchild: u32 = match fs::read_to_string(¬e).ok().and_then(|t| t.trim().parse().ok()) { |
| 374 | Some(n) => n, |
| 375 | None => return Err(err!("The shell noted no sleep."; Test, Missing)), |
| 376 | }; |
| 377 | assert_eq!(parent_of(grandchild), Some(child.id()), "the sleep is the shell's own"); |
| 378 | let seen = match Proc::of(grandchild) { |
| 379 | Some(p) => p, |
| 380 | None => return Err(err!("The sleep was not seen."; Test, Missing)), |
| 381 | }; |
| 382 | res!(to_group(child.id(), Signal::Kill)); |
| 383 | let status = res!(io(child.wait(), "wait on the shell")); |
| 384 | assert!(!status.success(), "the shell was killed, not left to finish"); |
| 385 | res!(until("the sleep beneath the shell to end", || !seen.running())); |
| 386 | Ok(()) |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn a_signal_to_group_0_1_or_the_callers_own_is_refused() { |
| 391 | assert!(to_group(0, Signal::Kill).is_err()); |
| 392 | assert!(to_group(1, Signal::Kill).is_err()); |
| 393 | let own = nix::unistd::getpgrp().as_raw() as u32; |
| 394 | assert!(to_group(own, Signal::Terminate).is_err()); |
| 395 | assert!(to_group(u32::MAX, Signal::Terminate).is_err()); |
| 396 | } |