1
//! `xtask postgres -- CMD` must not leak its cluster when it is asked to stop.
2
//!
3
//! A leaked cluster keeps its port and its directory; twenty of them exhaust
4
//! the 54320..54340 range every later run scans.
5

            
6
use std::path::{Path, PathBuf};
7
use std::process::{Child, Command, Stdio};
8
use std::time::{Duration, Instant};
9

            
10
const WAIT: Duration = Duration::from_secs(120);
11

            
12
9
fn wait_for<T>(what: &str, mut probe: impl FnMut() -> Option<T>) -> T {
13
9
    let deadline = Instant::now() + WAIT;
14
408
    while Instant::now() < deadline {
15
408
        if let Some(found) = probe() {
16
9
            return found;
17
399
        }
18
399
        std::thread::sleep(Duration::from_millis(50));
19
    }
20
    panic!("timed out waiting for {what}");
21
9
}
22

            
23
4
fn pid_alive(pid: &str) -> bool {
24
4
    std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| !stat.contains(") Z "))
25
4
}
26

            
27
376
fn announced(marker: &Path) -> Option<(PathBuf, String)> {
28
376
    let text = std::fs::read_to_string(marker).ok()?;
29
4
    let (data_dir, pid) = text.trim().split_once(' ')?;
30
4
    Some((PathBuf::from(data_dir), pid.to_string()))
31
376
}
32

            
33
3
fn terminate(xtask: &mut Child) {
34
3
    send(xtask, "TERM");
35
3
}
36

            
37
5
fn send(xtask: &Child, signal: &str) {
38
5
    let signalled = Command::new("kill")
39
5
        .args([&format!("-{signal}"), &xtask.id().to_string()])
40
5
        .status()
41
5
        .is_ok_and(|status| status.success());
42
5
    assert!(signalled, "kill -{signal} failed");
43
5
}
44

            
45
4
fn reap_leak(data_dir: &Path, pid: &str) {
46
4
    let _ = Command::new("kill").args(["-KILL", pid]).status();
47
4
    if let Some(root) = data_dir.parent() {
48
4
        let _ = std::fs::remove_dir_all(root);
49
    }
50
4
}
51

            
52
3
fn run_announcing_cluster(scratch: &Path) -> (Child, PathBuf) {
53
3
    let marker = scratch.join("cluster");
54
3
    let script = format!(
55
        "d=$(psql \"$DATABASE_URL\" -Atc 'show data_directory'); \
56
         echo \"$d $(head -1 \"$d/postmaster.pid\")\" > {}; sleep 120",
57
3
        marker.display()
58
    );
59
3
    let xtask = Command::new(env!("CARGO_BIN_EXE_xtask"))
60
3
        .args(["postgres", "--", "bash", "-c", &script])
61
3
        .spawn()
62
3
        .expect("xtask starts");
63
3
    (xtask, marker)
64
3
}
65

            
66
#[test]
67
1
fn a_terminated_run_leaves_no_postmaster_and_no_directory() {
68
1
    let scratch = tempfile::tempdir().expect("tempdir");
69
1
    let (mut xtask, marker) = run_announcing_cluster(scratch.path());
70
1
    assert_terminated_cleanly(&mut xtask, &marker);
71
1
}
72

            
73
#[test]
74
1
fn a_hangup_leaves_no_postmaster_and_no_directory() {
75
1
    let scratch = tempfile::tempdir().expect("tempdir");
76
1
    let (mut xtask, marker) = run_announcing_cluster(scratch.path());
77
118
    let (data_dir, pid) = wait_for("the cluster to be announced", || announced(&marker));
78
1
    send(&xtask, "HUP");
79
1
    assert_stopped_cleanly(&mut xtask, &data_dir, &pid);
80
1
}
81

            
82
#[test]
83
1
fn a_quit_leaves_no_postmaster_and_no_directory() {
84
1
    let scratch = tempfile::tempdir().expect("tempdir");
85
1
    let (mut xtask, marker) = run_announcing_cluster(scratch.path());
86
86
    let (data_dir, pid) = wait_for("the cluster to be announced", || announced(&marker));
87
1
    send(&xtask, "QUIT");
88
1
    assert_stopped_cleanly(&mut xtask, &data_dir, &pid);
89
1
}
90

            
91
#[test]
92
1
fn a_terminated_release_run_leaves_no_postmaster_and_no_directory() {
93
1
    let scratch = tempfile::tempdir().expect("tempdir");
94
1
    let marker = scratch.path().join("cluster");
95
1
    let bin = scratch.path().join("bin");
96
1
    std::fs::create_dir(&bin).expect("bin dir");
97
1
    let cargo = bin.join("cargo");
98
1
    let script = format!(
99
        "#!/bin/bash\nd=$(psql \"$DATABASE_URL\" -Atc 'show data_directory'); \
100
         echo \"$d $(head -1 \"$d/postmaster.pid\")\" > {}; sleep 120\n",
101
1
        marker.display()
102
    );
103
1
    std::fs::write(&cargo, script).expect("fake cargo");
104
1
    std::fs::set_permissions(&cargo, std::os::unix::fs::PermissionsExt::from_mode(0o755))
105
1
        .expect("chmod");
106
1
    let path = format!(
107
        "{}:{}",
108
1
        bin.display(),
109
1
        std::env::var("PATH").unwrap_or_default()
110
    );
111
1
    let mut xtask = Command::new(env!("CARGO_BIN_EXE_xtask"))
112
1
        .arg("release")
113
1
        .current_dir(scratch.path())
114
1
        .env("PATH", path)
115
1
        .spawn()
116
1
        .expect("xtask starts");
117

            
118
1
    assert_terminated_cleanly(&mut xtask, &marker);
119
1
}
120

            
121
/// Terminates `xtask` once its cluster is announced in `marker`, and asserts it
122
/// failed and left no postmaster or directory.
123
2
fn assert_terminated_cleanly(xtask: &mut Child, marker: &Path) {
124
172
    let (data_dir, pid) = wait_for("the cluster to be announced", || announced(marker));
125
2
    terminate(xtask);
126
2
    assert_stopped_cleanly(xtask, &data_dir, &pid);
127
2
}
128

            
129
4
fn assert_stopped_cleanly(xtask: &mut Child, data_dir: &Path, pid: &str) {
130
30
    let exited = wait_for("xtask to exit", || xtask.try_wait().expect("try_wait"));
131

            
132
4
    let leaked = pid_alive(pid) || data_dir.exists();
133
4
    reap_leak(data_dir, pid);
134
4
    assert!(!leaked, "the cluster at {data_dir:?} (pid {pid}) leaked");
135
4
    assert!(!exited.success(), "a terminated run must fail: {exited}");
136
4
}
137

            
138
/// Whether any live process was started with `needle` in its command line.
139
1
fn command_line_mentions(needle: &str) -> bool {
140
1
    std::fs::read_dir("/proc")
141
1
        .into_iter()
142
1
        .flatten()
143
1
        .flatten()
144
119
        .filter_map(|entry| std::fs::read(entry.path().join("cmdline")).ok())
145
64
        .any(|cmdline| String::from_utf8_lossy(&cmdline).contains(needle))
146
1
}
147

            
148
1
fn real_initdb() -> String {
149
1
    let found = Command::new("sh")
150
1
        .args(["-c", "command -v initdb"])
151
1
        .output()
152
1
        .expect("sh runs");
153
1
    String::from_utf8_lossy(&found.stdout).trim().to_string()
154
1
}
155

            
156
/// An initdb that reports its data dir, then holds until `go` exists or 120 s pass, so the
157
/// test's signal always lands while the cluster is still starting, however loaded the host.
158
1
fn held_initdb(bin: &Path, marker: &Path, go: &Path) {
159
1
    let initdb = bin.join("initdb");
160
1
    let script = format!(
161
        "#!/bin/bash\necho \"$2\" > {}\nwhile [ ! -e {} ] && [ $SECONDS -lt 120 ]; do sleep 0.05; done\nexec {} \"$@\"\n",
162
1
        marker.display(),
163
1
        go.display(),
164
1
        real_initdb()
165
    );
166
1
    std::fs::write(&initdb, script).expect("fake initdb");
167
1
    std::fs::set_permissions(&initdb, std::os::unix::fs::PermissionsExt::from_mode(0o755))
168
1
        .expect("chmod");
169
1
}
170

            
171
#[test]
172
1
fn a_signal_while_the_cluster_starts_refuses_to_run_the_command() {
173
1
    let scratch = tempfile::tempdir().expect("tempdir");
174
1
    let marker = scratch.path().join("data_dir");
175
1
    let bin = scratch.path().join("bin");
176
1
    let go = scratch.path().join("go");
177
1
    std::fs::create_dir(&bin).expect("bin dir");
178
1
    held_initdb(&bin, &marker, &go);
179
1
    let path = format!(
180
        "{}:{}",
181
1
        bin.display(),
182
1
        std::env::var("PATH").unwrap_or_default()
183
    );
184
1
    let mut xtask = Command::new(env!("CARGO_BIN_EXE_xtask"))
185
1
        .args(["postgres", "--", "sleep", "120"])
186
1
        .env("PATH", path)
187
1
        .stdout(Stdio::piped())
188
1
        .stderr(Stdio::piped())
189
1
        .spawn()
190
1
        .expect("xtask starts");
191

            
192
2
    let data_dir = wait_for("initdb to begin", || {
193
2
        std::fs::read_to_string(&marker)
194
2
            .ok()
195
1
            .filter(|text| text.ends_with('\n'))
196
2
    });
197
1
    let data_dir = data_dir.trim();
198
1
    terminate(&mut xtask);
199
1
    std::fs::write(&go, "").expect("release initdb");
200
1
    let output = xtask.wait_with_output().expect("xtask exits");
201

            
202
1
    let stderr = String::from_utf8_lossy(&output.stderr);
203
1
    assert!(!output.status.success(), "{stderr}");
204
1
    assert!(
205
1
        stderr.contains("termination signal arrived first"),
206
        "{stderr}"
207
    );
208
1
    assert!(
209
1
        !Path::new(data_dir).exists() && !command_line_mentions(data_dir),
210
        "the cluster at {data_dir} leaked"
211
    );
212
1
}