1use crate::{
8 guard::{self, DEADLOCK_GUARD},
9 scratch::Scratch,
10};
11use std::{
12 fs::{File, OpenOptions},
13 io::{self, Read},
14 os::unix::{fs::OpenOptionsExt, process::CommandExt},
15 path::{Path, PathBuf},
16 process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus},
17 sync::mpsc::{self, Receiver},
18 thread::JoinHandle,
19 time::{Duration, Instant},
20};
21
22#[derive(Clone, Copy)]
23pub struct Live(usize);
24struct Owned {
25 child: Option<Child>,
27 pid: u32,
28 status: Option<ExitStatus>,
29 deliberate: bool,
30 service: bool,
31 group: bool,
32}
33pub struct Scene {
34 pub scratch: Scratch,
35 children: Vec<Owned>,
36 nested: bool,
37}
38pub fn scene<T>(mut run: impl FnMut(&mut Scene) -> io::Result<T>) -> io::Result<T> {
43 for attempt in 1..=super::KILLED_RUNS {
44 let mut scene = Scene {
45 scratch: Scratch::new("scene"),
46 children: Vec::new(),
47 nested: std::env::var_os("UNITYRS_TEST_INHERIT_GROUP").is_some(),
48 };
49 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&mut scene)));
50 let (outside, unfinished) = scene.finish()?;
52 if outside {
53 assert!(
54 attempt < super::KILLED_RUNS,
55 "scene killed by SIGKILL on every run: the system ended it from outside"
56 );
57 continue;
58 }
59 return match result {
60 Ok(Ok(_)) if unfinished => Err(io::Error::other(
61 "scene returned while its engine was still alive",
62 )),
63 Ok(value) => value,
64 Err(panic) => std::panic::resume_unwind(panic),
65 };
66 }
67 unreachable!("the final killed scene fails above")
68}
69pub fn live(scene: &mut Scene, cmd: &mut Command, service: bool) -> io::Result<Live> {
73 if !cmd.get_envs().any(|(k, _)| k == crate::scratch::VAR) {
74 cmd.env(crate::scratch::VAR, scene.scratch.path());
75 }
76 if !scene.nested {
77 cmd.process_group(0);
78 }
79 cmd.env("UNITYRS_TEST_INHERIT_GROUP", "1");
80 let child = cmd
81 .spawn()
82 .map_err(|e| io::Error::new(e.kind(), format!("scene spawn: {e}")))?;
83 let token = Live(scene.children.len());
84 scene.children.push(Owned {
85 pid: child.id(),
86 child: Some(child),
87 status: None,
88 deliberate: false,
89 service,
90 group: !scene.nested,
91 });
92 Ok(token)
93}
94impl Scene {
95 #[must_use]
96 pub fn id(&self, live: Live) -> u32 {
97 self.children[live.0].pid
98 }
99 pub fn stdin(&mut self, live: Live) -> Option<&mut ChildStdin> {
103 self.children[live.0].child.as_mut()?.stdin.as_mut()
104 }
105 pub fn take_stdin(&mut self, live: Live) -> Option<ChildStdin> {
107 self.children[live.0].child.as_mut()?.stdin.take()
108 }
109 pub fn take_stdout(&mut self, live: Live) -> Option<ChildStdout> {
111 self.children[live.0].child.as_mut()?.stdout.take()
112 }
113 pub fn take_stderr(&mut self, live: Live) -> Option<ChildStderr> {
115 self.children[live.0].child.as_mut()?.stderr.take()
116 }
117 pub fn adopt(&mut self, pid: u32, service: bool) -> io::Result<Live> {
125 sys::exited(pid).map_err(|e| io::Error::new(e.kind(), format!("scene adopt: {e}")))?;
126 let token = Live(self.children.len());
127 self.children.push(Owned {
128 child: None,
129 pid,
130 status: None,
131 deliberate: false,
132 service,
133 group: false,
134 });
135 Ok(token)
136 }
137 pub fn running(&mut self, live: Live) -> io::Result<bool> {
140 let owned = &mut self.children[live.0];
141 if owned.status.is_none()
142 && sys::exited(owned.pid)
143 .map_err(|e| io::Error::new(e.kind(), format!("scene waitid: {e}")))?
144 {
145 if owned.group {
146 sys::cleanup_exited_group(owned.pid)?;
147 }
148 owned.status = Some(match &mut owned.child {
149 Some(child) => child.wait()?,
150 None => sys::reap(owned.pid)?,
151 });
152 }
153 Ok(owned.status.is_none())
154 }
155 pub fn mark(&mut self, path: &Path, watched: &[Live]) -> io::Result<()> {
162 let deadline = Instant::now() + DEADLOCK_GUARD;
163 while !path.exists() {
164 for live in watched {
165 if !self.running(*live)? {
166 return Err(io::Error::new(
167 io::ErrorKind::BrokenPipe,
168 format!("scene child ended before mark {}", path.display()),
169 ));
170 }
171 }
172 assert!(
173 Instant::now() < deadline,
174 "deadlock guard: scene mark {} missing",
175 path.display()
176 );
177 std::thread::sleep(Duration::from_millis(1));
178 }
179 Ok(())
180 }
181 pub fn signal(&mut self, live: Live, signal: i32) -> io::Result<()> {
182 if signal == libc::SIGKILL {
183 return Err(io::ErrorKind::InvalidInput.into());
184 }
185 if !self.running(live)? {
186 return Err(io::ErrorKind::NotFound.into());
187 }
188 sys::signal(self.id(live), signal, false)
189 }
190 pub fn kill(&mut self, live: Live) -> io::Result<()> {
192 if !self.running(live)? {
193 return Ok(());
194 }
195 let owned = &mut self.children[live.0];
196 owned.deliberate = true;
197 sys::signal(owned.pid, libc::SIGKILL, owned.group)
198 }
199 pub fn wait(&mut self, live: Live) -> io::Result<ExitStatus> {
202 let deadline = Instant::now() + DEADLOCK_GUARD;
203 loop {
204 if let Some(status) = self.children[live.0].status {
205 return Ok(status);
206 }
207 if !self.running(live)? {
208 continue;
209 }
210 assert!(
211 Instant::now() < deadline,
212 "deadlock guard: child did not exit"
213 );
214 std::thread::sleep(Duration::from_millis(1));
215 }
216 }
217 fn finish(&mut self) -> io::Result<(bool, bool)> {
218 let mut outside = false;
219 let mut unfinished = false;
220 for i in 0..self.children.len() {
221 let _ = self.running(Live(i))?;
222 if self.children[i].status.is_none() {
223 unfinished |= !self.children[i].service;
224 self.kill(Live(i))?;
226 }
227 let status = self.wait(Live(i))?;
228 outside |= super::killed(status) && !self.children[i].deliberate;
229 }
230 Ok((outside, unfinished))
231 }
232}
233impl Drop for Scene {
234 fn drop(&mut self) {
235 for owned in &mut self.children {
236 if owned.status.is_none() {
237 let _ = sys::signal(owned.pid, libc::SIGKILL, owned.group);
239 let _ = match &mut owned.child {
240 Some(child) => child.wait(),
241 None => sys::reap(owned.pid),
242 };
243 }
244 }
245 }
246}
247#[must_use]
249pub fn drain(mut input: impl Read + Send + 'static) -> (Receiver<Vec<u8>>, JoinHandle<()>) {
250 let (tx, rx) = mpsc::channel();
251 let thread = std::thread::spawn(move || {
252 loop {
253 let mut bytes = vec![0; 4096];
254 match input.read(&mut bytes) {
255 Ok(0) => break,
256 Ok(n) => {
257 bytes.truncate(n);
258 let _ = tx.send(bytes);
262 }
263 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
264 Err(_) => break,
265 }
266 }
267 });
268 (rx, thread)
269}
270pub struct Fifo {
274 path: PathBuf,
275 rx: Receiver<String>,
276 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
277 thread: Option<JoinHandle<()>>,
278}
279impl Fifo {
280 pub fn new(scene: &Scene, name: &str) -> io::Result<Self> {
281 let path = scene.scratch.path().join(name);
282 sys::fifo(&path).map_err(|e| io::Error::new(e.kind(), format!("scene mkfifo: {e}")))?;
283 let mut file: File = OpenOptions::new()
284 .read(true)
285 .write(true)
286 .custom_flags(libc::O_NONBLOCK | libc::O_CLOEXEC)
287 .open(&path)?;
288 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
289 let stopping = stop.clone();
290 let (tx, rx) = mpsc::channel();
291 let thread = std::thread::spawn(move || {
292 let mut pending = Vec::new();
293 let mut bytes = [0; 4096];
294 while !stopping.load(std::sync::atomic::Ordering::Acquire) {
295 match file.read(&mut bytes) {
296 Ok(n) => {
297 for b in &bytes[..n] {
298 if *b == b'\n' {
299 if tx
300 .send(String::from_utf8_lossy(&pending).into_owned())
301 .is_err()
302 {
303 return;
304 }
305 pending.clear();
306 } else {
307 pending.push(*b);
308 }
309 }
310 }
311 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
312 std::thread::sleep(Duration::from_millis(1));
313 }
314 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
315 Err(_) => return,
316 }
317 }
318 });
319 Ok(Self {
320 path,
321 rx,
322 stop,
323 thread: Some(thread),
324 })
325 }
326 #[must_use]
327 pub fn path(&self) -> &Path {
328 &self.path
329 }
330 #[must_use]
331 pub fn line(&self) -> String {
332 guard::recv(&self.rx, "fresh lifecycle FIFO line")
333 }
334 pub fn line_while(&self, scene: &mut Scene, live: Live) -> io::Result<String> {
341 let deadline = Instant::now() + DEADLOCK_GUARD;
342 loop {
343 match self.rx.recv_timeout(Duration::from_millis(1)) {
344 Ok(text) => return Ok(text),
345 Err(mpsc::RecvTimeoutError::Disconnected) => {
346 return Err(io::ErrorKind::BrokenPipe.into());
347 }
348 Err(mpsc::RecvTimeoutError::Timeout) => {}
349 }
350 if !scene.running(live)? {
351 return Err(io::ErrorKind::BrokenPipe.into());
352 }
353 assert!(
354 Instant::now() < deadline,
355 "deadlock guard: lifecycle FIFO line missing"
356 );
357 }
358 }
359}
360impl Drop for Fifo {
361 fn drop(&mut self) {
362 self.stop.store(true, std::sync::atomic::Ordering::Release);
363 if let Some(thread) = self.thread.take() {
364 let _ = thread.join();
365 }
366 }
367}
368#[path = "sys.rs"]
369mod sys;
370
371#[cfg(test)]
372#[path = "live_tests.rs"]
373mod tests;