1
use std::os::unix::process::CommandExt;
2
use std::process::{Command, Stdio};
3
use std::time::{Duration, Instant};
4

            
5
use super::*;
6

            
7
2
fn state_of(pid: u32) -> Option<char> {
8
2
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
9
1
    stat.rsplit_once(')')?.1.trim().chars().next()
10
2
}
11

            
12
4
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
13
4
    let deadline = Instant::now() + Duration::from_secs(10);
14
6
    while !done() {
15
2
        assert!(Instant::now() < deadline, "timed out waiting for {what}");
16
2
        std::thread::sleep(Duration::from_millis(20));
17
    }
18
4
}
19

            
20
/// A group with a `sleep` grandchild, as a watched cargo has its test binaries.
21
2
fn spawn_group() -> (std::process::Child, Group, u32) {
22
2
    let mut child = Command::new("bash")
23
2
        .args(["-c", "sleep 120 & wait"])
24
2
        .stdout(Stdio::null())
25
2
        .process_group(0)
26
2
        .spawn()
27
2
        .expect("spawn bash");
28
2
    let group = Group::of(&child);
29
4
    wait_until("the grandchild", || group.members().len() == 2);
30
2
    let grandchild = group
31
2
        .members()
32
2
        .into_iter()
33
4
        .find(|&pid| pid != child.id())
34
2
        .expect("a grandchild");
35
2
    let _ = child.try_wait();
36
2
    (child, group, grandchild)
37
2
}
38

            
39
#[test]
40
1
fn thread_states_cover_every_member_of_the_group() {
41
1
    let _processes = crate::test_support::processes();
42
1
    let (mut child, group, grandchild) = spawn_group();
43
1
    let states = group.thread_states();
44
1
    group.kill();
45
1
    let _ = child.wait();
46
1
    assert!(
47
1
        states
48
1
            .iter()
49
2
            .any(|line| line.contains(&format!("pid {grandchild} "))),
50
        "the grandchild is missing from {states:?}"
51
    );
52
1
}
53

            
54
#[test]
55
1
fn a_frozen_group_stays_visible_until_it_is_killed() {
56
1
    let _processes = crate::test_support::processes();
57
1
    let (mut child, group, grandchild) = spawn_group();
58
1
    group.freeze();
59
1
    wait_until("the grandchild to stop", || {
60
1
        state_of(grandchild) == Some('T')
61
1
    });
62
1
    assert!(group.members().contains(&grandchild));
63

            
64
1
    group.kill();
65
1
    let _ = child.wait();
66
1
    wait_until(
67
1
        "the grandchild to be gone",
68
1
        || !matches!(state_of(grandchild), Some(state) if state != 'Z'),
69
    );
70
1
}
71

            
72
const HELPER_ENV: &str = "XTASK_SIGNAL_HELPER";
73

            
74
/// Body of the child process of `termination_keeps_the_default_action_between_runs`;
75
/// a no-op in the normal suite.
76
#[test]
77
1
fn signal_helper() {
78
1
    if std::env::var_os(HELPER_ENV).is_none() {
79
1
        return;
80
    }
81
    for _ in 0..2 {
82
        drop(Termination::watch().expect("watch"));
83
    }
84
    println!("ready");
85
    std::thread::sleep(Duration::from_secs(60));
86
1
}
87

            
88
/// Handlers outlive a run, so they must go back to terminating the process.
89
#[test]
90
1
fn termination_keeps_the_default_action_between_runs() {
91
    use std::io::{BufRead, BufReader};
92
    use std::os::unix::process::ExitStatusExt;
93

            
94
1
    let _processes = crate::test_support::processes();
95
1
    let mut helper = Command::new(std::env::current_exe().expect("test exe"))
96
1
        .args([
97
1
            "--exact",
98
1
            "watchdog::group::tests::signal_helper",
99
1
            "--nocapture",
100
1
        ])
101
1
        .env(HELPER_ENV, "1")
102
1
        .stdout(Stdio::piped())
103
1
        .spawn()
104
1
        .expect("spawn helper");
105
1
    let stdout = helper.stdout.take().expect("helper stdout");
106
1
    let ready = BufReader::new(stdout)
107
1
        .lines()
108
1
        .map_while(Result::ok)
109
3
        .any(|line| line == "ready");
110
1
    assert!(ready, "the helper never got past its watched runs");
111

            
112
1
    let pid = Pid::from_raw(i32::try_from(helper.id()).expect("pid"));
113
1
    nix::sys::signal::kill(pid, Signal::SIGTERM).expect("signal the helper");
114
1
    let status = helper.wait().expect("helper exit");
115
1
    assert_eq!(status.signal(), Some(SIGTERM), "{status:?}");
116
1
}
117

            
118
/// Body of the child process of `an_inner_watch_leaves_the_outer_one_in_force`;
119
/// a no-op in the normal suite.
120
#[test]
121
2
fn nested_signal_helper() {
122
2
    if std::env::var_os(HELPER_ENV).is_none() {
123
1
        return;
124
1
    }
125
1
    let outer = Termination::watch().expect("outer watch");
126
1
    drop(Termination::watch().expect("inner watch"));
127
1
    println!("ready");
128
1
    for _ in 0..600 {
129
2
        if outer.requested() {
130
1
            println!("seen");
131
1
            return;
132
1
        }
133
1
        std::thread::sleep(Duration::from_millis(100));
134
    }
135
2
}
136

            
137
#[test]
138
1
fn an_inner_watch_leaves_the_outer_one_in_force() {
139
    use std::io::{BufRead, BufReader};
140

            
141
1
    let _processes = crate::test_support::processes();
142
1
    let mut helper = Command::new(std::env::current_exe().expect("test exe"))
143
1
        .args([
144
1
            "--exact",
145
1
            "watchdog::group::tests::nested_signal_helper",
146
1
            "--nocapture",
147
1
        ])
148
1
        .env(HELPER_ENV, "1")
149
1
        .stdout(Stdio::piped())
150
1
        .spawn()
151
1
        .expect("spawn helper");
152
1
    let stdout = helper.stdout.take().expect("helper stdout");
153
1
    let mut lines = BufReader::new(stdout).lines().map_while(Result::ok);
154
1
    assert!(
155
3
        lines.any(|line| line == "ready"),
156
        "the helper never got past its watches"
157
    );
158

            
159
1
    let pid = Pid::from_raw(i32::try_from(helper.id()).expect("pid"));
160
1
    nix::sys::signal::kill(pid, Signal::SIGTERM).expect("signal the helper");
161
1
    let seen = lines.any(|line| line == "seen");
162
1
    let status = helper.wait().expect("helper exit");
163
1
    assert!(seen && status.success(), "{status:?}");
164
1
}