Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_sys/tests/clock.rs

11.9 KiB, 1 run

created by r1870400018:65728, 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::clock` against the kernel and against readings a suspend would leave.
2//!
3//! The kernel is the oracle for the two things it can attest on any machine: the first
4//! field of `/proc/uptime` is `CLOCK_BOOTTIME`, and a process stopped by a real `SIGSTOP`
5//! (whose state the kernel reports in `/proc/<pid>/status`) is not a suspend, since both
6//! clocks run through it. A suspend itself cannot be produced from a test, so what a
7//! suspend leaves is given to `Asleep` as readings, 3 s apart, and the arithmetic is
8//! checked on those. On a machine that has never been suspended the boot and monotonic
9//! clocks agree, so these tests cannot tell which of the two `since_boot` asks the kernel
10//! for.
11
12#![cfg(all(target_os = "linux", feature = "clock"))]
13
14use oxedyne_fe2o3_core::prelude::*;
15use oxedyne_fe2o3_sys::clock::{
16 since_boot,
17 slept,
18 Asleep,
19 LEAST,
20};
21
22use std::{
23 fs,
24 io::{
25 BufRead,
26 BufReader,
27 },
28 process::{
29 Child,
30 Command,
31 Stdio,
32 },
33 time::{
34 Duration,
35 Instant,
36 },
37};
38
39const CHILD: &str = "FE2O3_SYS_CLOCK_CHILD";
40const SECOND: Duration = Duration::from_secs(1);
41
42fn io<T>(r: std::io::Result<T>, what: &str) -> Outcome<T> {
43 match r {
44 Ok(v) => Ok(v),
45 Err(e) => Err(err!("{}: {}.", what, e; IO, File)),
46 }
47}
48
49// The first field of /proc/uptime, in seconds, as the kernel prints it (two decimals).
50fn uptime() -> Outcome<f64> {
51 let text = res!(io(fs::read_to_string("/proc/uptime"), "read /proc/uptime"));
52 let field = res!(text.split_whitespace().next()
53 .ok_or_else(|| err!("/proc/uptime is empty."; Missing)));
54 match field.parse::<f64>() {
55 Ok(v) => Ok(v),
56 Err(e) => Err(err!("/proc/uptime says {:?}: {}.", field, e; Input, Invalid)),
57 }
58}
59
60#[test]
61fn since_boot_agrees_with_the_kernels_own_uptime() -> Outcome<()> {
62 // Read either side of the call. The two reads of /proc/uptime must themselves be
63 // close (a loaded machine can stretch them), or the bracket proves nothing.
64 for _ in 0..20 {
65 let before = res!(uptime());
66 let boot = res!(since_boot()).as_secs_f64();
67 let after = res!(uptime());
68 if after - before > 0.05 {
69 continue;
70 }
71 println!("uptime {} <= since_boot {:.3} <= uptime {}", before, boot, after);
72 // /proc/uptime prints two decimals, so each end may be a hundredth short.
73 assert!(boot >= before - 0.02,
74 "since_boot {} is behind the kernel's uptime {} read before it", boot, before);
75 assert!(boot <= after + 0.02,
76 "since_boot {} is ahead of the kernel's uptime {} read after it", boot, after);
77 return Ok(());
78 }
79 Err(err!("Twenty tries and /proc/uptime was never read twice within 50 ms."; Test, Timeout))
80}
81
82#[test]
83fn since_boot_keeps_the_kernels_rate() -> Outcome<()> {
84 let up0 = res!(uptime());
85 let boot0 = res!(since_boot());
86 std::thread::sleep(Duration::from_millis(400));
87 let boot1 = res!(since_boot());
88 let up1 = res!(uptime());
89 let moved = (boot1 - boot0).as_secs_f64();
90 let kernel = up1 - up0;
91 println!("since_boot moved {:.3} s while /proc/uptime moved {:.2} s", moved, kernel);
92 assert!((moved - kernel).abs() < 0.03,
93 "since_boot moved {} s where /proc/uptime moved {} s", moved, kernel);
94 assert!(moved >= 0.4, "since_boot moved {} s over a 400 ms sleep", moved);
95 Ok(())
96}
97
98#[test]
99fn a_stretch_the_boot_clock_counted_and_the_monotonic_clock_did_not_is_a_suspend() -> Outcome<()> {
100 // The boot clock ran 5 s and the monotonic clock 2 s: the machine slept for 3.
101 let base = Instant::now();
102 let mut a = Asleep::at(Duration::from_secs(1_000), base, LEAST);
103 assert_eq!(
104 a.check_at(Duration::from_secs(1_005), base + Duration::from_secs(2)),
105 Some(Duration::from_secs(3)));
106 assert_eq!(
107 slept(Duration::from_secs(5), Duration::from_secs(2), LEAST),
108 Some(Duration::from_secs(3)));
109 Ok(())
110}
111
112#[test]
113fn a_stretch_both_clocks_counted_is_not_a_suspend() -> Outcome<()> {
114 // A stalled process, a debugger, a long swap-out: both clocks go on, and agree.
115 let base = Instant::now();
116 for n in [1, 3, 600, 86_400] {
117 let mut a = Asleep::at(Duration::from_secs(1_000), base, LEAST);
118 let found = a.check_at(Duration::from_secs(1_000 + n), base + Duration::from_secs(n));
119 assert_eq!(found, None, "a {} s stretch on both clocks", n);
120 }
121 Ok(())
122}
123
124#[test]
125fn a_gap_is_reported_from_the_threshold_up() -> Outcome<()> {
126 let ms = Duration::from_millis;
127 assert_eq!(slept(ms(7_999), ms(6_000), LEAST), None, "1.999 s asleep");
128 assert_eq!(slept(ms(8_000), ms(6_000), LEAST), Some(ms(2_000)), "2 s asleep");
129 assert_eq!(slept(ms(8_001), ms(6_000), LEAST), Some(ms(2_001)), "2.001 s asleep");
130 // Another threshold, and a threshold of nothing reports nothing for no gap.
131 assert_eq!(slept(ms(6_500), ms(6_000), ms(500)), Some(ms(500)));
132 assert_eq!(slept(ms(6_499), ms(6_000), ms(500)), None);
133 assert_eq!(slept(ms(6_000), ms(6_000), Duration::ZERO), None);
134 Ok(())
135}
136
137#[test]
138fn a_suspend_is_reported_once_and_the_next_stretch_starts_afresh() -> Outcome<()> {
139 let s = Duration::from_secs;
140 let base = Instant::now();
141 let mut a = Asleep::at(s(100), base, LEAST);
142 // Asleep for 10 s inside a 12 s turn.
143 assert_eq!(a.check_at(s(112), base + s(2)), Some(s(10)));
144 // The turn after is ordinary: 5 s on both clocks.
145 assert_eq!(a.check_at(s(117), base + s(7)), None);
146 // And a second suspend is reported at its own length, not the sum.
147 assert_eq!(a.check_at(s(130), base + s(9)), Some(s(11)));
148 Ok(())
149}
150
151#[test]
152fn a_monotonic_clock_ahead_of_the_boot_clock_reports_nothing() -> Outcome<()> {
153 // It cannot be, but two reads a moment apart can say it; it must not underflow.
154 let s = Duration::from_secs;
155 let base = Instant::now();
156 let mut a = Asleep::at(s(100), base, LEAST);
157 assert_eq!(a.check_at(s(101), base + s(30)), None);
158 // And a boot clock that went backwards is nothing either.
159 assert_eq!(a.check_at(s(90), base + s(31)), None);
160 Ok(())
161}
162
163#[test]
164fn the_real_clocks_a_short_pause_apart_report_no_suspend() -> Outcome<()> {
165 let mut a = res!(Asleep::new());
166 for _ in 0..4 {
167 std::thread::sleep(Duration::from_millis(150));
168 assert_eq!(a.check(), None);
169 }
170 // A threshold that would catch a millisecond of difference still catches nothing here.
171 let mut a = res!(Asleep::with_least(Duration::from_millis(50)));
172 std::thread::sleep(Duration::from_millis(300));
173 assert_eq!(a.check(), None, "both real clocks ran through a 300 ms sleep");
174 Ok(())
175}
176
177// The child of the SIGSTOP test: it checks every 50 ms for 6 s, says each suspend it is
178// told of, and at the end says the longest gap between two of its turns by each clock. Each
179// line starts with a newline, since the test harness has left its own words on the line.
180fn watching_child() -> Outcome<()> {
181 let mut a = res!(Asleep::new());
182 let began = Instant::now();
183 println!("\nCHILD ready");
184 let mut top_mono = Duration::ZERO;
185 let mut top_boot = Duration::ZERO;
186 let mut last_mono = Instant::now();
187 let mut last_boot = res!(since_boot());
188 while began.elapsed() < Duration::from_secs(6) {
189 std::thread::sleep(Duration::from_millis(50));
190 if let Some(d) = a.check() {
191 println!("\nCHILD slept {}", d.as_millis());
192 }
193 let m = Instant::now();
194 let b = res!(since_boot());
195 top_mono = top_mono.max(m.duration_since(last_mono));
196 top_boot = top_boot.max(b.saturating_sub(last_boot));
197 last_mono = m;
198 last_boot = b;
199 }
200 println!("\nCHILD gaps mono {} boot {}", top_mono.as_millis(), top_boot.as_millis());
201 Ok(())
202}
203
204// Whatever happens to the test, a stopped child must not be left stopped.
205struct Reap(Child);
206
207impl Drop for Reap {
208 fn drop(&mut self) {
209 let _ = Command::new("kill").arg("-CONT").arg(self.0.id().to_string()).output();
210 let _ = self.0.kill();
211 let _ = self.0.wait();
212 }
213}
214
215fn signal(sig: &str, child: &Child) -> Outcome<()> {
216 let out = res!(io(Command::new("kill").arg(fmt!("-{}", sig)).arg(fmt!("{}", child.id()))
217 .output(), "run kill"));
218 if !out.status.success() {
219 return Err(err!("kill -{} {} answered {:?}.", sig, child.id(), out.status; Test, System));
220 }
221 Ok(())
222}
223
224// The kernel's own word for the process: the letter after "State:".
225fn state(child: &Child) -> Outcome<char> {
226 let text = res!(io(fs::read_to_string(fmt!("/proc/{}/status", child.id())), "read the child's status"));
227 for line in text.lines() {
228 if let Some(rest) = line.strip_prefix("State:") {
229 if let Some(c) = rest.trim().chars().next() {
230 return Ok(c);
231 }
232 }
233 }
234 Err(err!("No State line in the child's /proc status."; Test, Missing))
235}
236
237#[test]
238fn a_process_stopped_by_sigstop_for_three_seconds_is_not_a_suspend() -> Outcome<()> {
239 if std::env::var(CHILD).is_ok() {
240 return watching_child();
241 }
242 let exe = res!(io(std::env::current_exe(), "find this test binary"));
243 let child = res!(io(Command::new(&exe)
244 .args(["--exact", "a_process_stopped_by_sigstop_for_three_seconds_is_not_a_suspend",
245 "--test-threads=1", "--nocapture"])
246 .env(CHILD, "1")
247 .stdout(Stdio::piped())
248 .spawn(), "start the child"));
249 let mut child = Reap(child);
250 let out = match child.0.stdout.take() {
251 Some(o) => o,
252 None => return Err(err!("The child has no stdout."; Test, Missing)),
253 };
254 let mut lines = BufReader::new(out).lines();
255 loop {
256 match lines.next() {
257 Some(Ok(l)) if l == "CHILD ready" => break,
258 Some(Ok(_)) => continue,
259 _ => return Err(err!("The child never said ready."; Test, Missing)),
260 }
261 }
262 std::thread::sleep(SECOND);
263 // A real stop, and the kernel's confirmation that the child is stopped.
264 let up0 = res!(uptime());
265 let t0 = Instant::now();
266 res!(signal("STOP", &child.0));
267 std::thread::sleep(Duration::from_millis(200));
268 assert_eq!(res!(state(&child.0)), 'T', "the kernel does not call the child stopped");
269 std::thread::sleep(Duration::from_millis(2_800));
270 assert_eq!(res!(state(&child.0)), 'T', "the child ran while it was meant to be stopped");
271 res!(signal("CONT", &child.0));
272 let stopped = t0.elapsed();
273 let up1 = res!(uptime());
274 println!("stopped for {:?} by the monotonic clock, {:.2} s by /proc/uptime", stopped, up1 - up0);
275 assert!(stopped >= Duration::from_secs(3));
276 assert!(up1 - up0 >= 3.0 - 0.02, "the kernel's boot clock moved {} s", up1 - up0);
277
278 let mut said = Vec::new();
279 for l in lines {
280 match l {
281 Ok(l) => said.push(l),
282 Err(_) => break,
283 }
284 }
285 let _ = child.0.wait();
286 println!("the child said: {:?}", said);
287 for l in &said {
288 assert!(!l.starts_with("CHILD slept"), "a stop was read as a suspend: {:?}", said);
289 }
290 // Each clock saw the stop as one gap of about three seconds in the child's own turns,
291 // so a stop that only one clock saw would be told apart from this one.
292 let gaps = match said.iter().find(|l| l.starts_with("CHILD gaps")) {
293 Some(g) => g.clone(),
294 None => return Err(err!("The child never reported its gaps: {:?}.", said; Test, Missing)),
295 };
296 let words: Vec<&str> = gaps.split_whitespace().collect();
297 assert_eq!(words.len(), 6, "{:?}", gaps);
298 let mono: u64 = res!(words[3].parse::<u64>().map_err(|e| err!("{}: {:?}", e, gaps; Test, Input)));
299 let boot: u64 = res!(words[5].parse::<u64>().map_err(|e| err!("{}: {:?}", e, gaps; Test, Input)));
300 assert!(mono >= 2_900, "the monotonic clock saw a {} ms gap across the stop", mono);
301 assert!(boot >= 2_900, "the boot clock saw a {} ms gap across the stop", boot);
302 assert!(boot.abs_diff(mono) < 50, "the clocks disagreed over the stop: {} ms and {} ms", mono, boot);
303 Ok(())
304}