Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_sys/tests/notify.rs

18.1 KiB, 5 runs

created by r1870400018:76757, 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::notify`: the host-path resolver on given mount tables and the live one,
2//! the Follower against real renames, saves, unlinks and a real queue overflow, and the fanotify
3//! group.
4//!
5//! The fanotify arms need `CAP_SYS_ADMIN`. They are ignored here and run as root in the VM (BR-4e
6//! S6) with `cargo test --features notify -- --ignored`.
7
8#![cfg(all(target_os = "linux", feature = "notify"))]
9
10use oxedyne_fe2o3_core::prelude::*;
11use oxedyne_fe2o3_sys::notify::{
12 fan::{
13 FanEvent,
14 FanGroup,
15 Writer,
16 },
17 follow::{
18 Change,
19 Followed,
20 FollowId,
21 Follower,
22 Limit,
23 },
24 mounts::{
25 mount_id,
26 resolve,
27 unescape,
28 FsClass,
29 HostPath,
30 MountTable,
31 Unresolved,
32 },
33};
34
35use nix::poll::{
36 poll,
37 PollFd,
38 PollFlags,
39 PollTimeout,
40};
41
42use std::{
43 env,
44 fs::{
45 self,
46 File,
47 },
48 os::fd::AsFd,
49 os::unix::fs::PermissionsExt,
50 path::PathBuf,
51 process::Command,
52 time::{
53 Duration,
54 Instant,
55 },
56};
57
58// ── Resolver ──
59
60const OWN: &str = "\
6122 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw
6230 22 8:1 /home/jason/x /mnt/b rw,relatime shared:1 - ext4 /dev/sda1 rw
6331 22 8:2 /data /srv rw,relatime - ext4 /dev/sdb1 rw
6440 22 0:5 / /dev rw - devtmpfs udev rw
65";
66
67const WRITER: &str = "\
68500 400 8:1 /home/jason/x /x rw,relatime - ext4 /dev/sda1 rw
69501 400 8:2 /data/proj /p rw - ext4 /dev/sdb1 rw
70502 400 8:9 / /other rw - ext4 /dev/sdz rw
71";
72
73fn tables() -> Outcome<(MountTable, MountTable)> {
74 Ok((res!(MountTable::parse(OWN)), res!(MountTable::parse(WRITER))))
75}
76
77fn expect(got: HostPath, want: HostPath) -> Outcome<()> {
78 if got != want {
79 return Err(err!("Resolved to {:?}, wanted {:?}.", got, want; Test));
80 }
81 Ok(())
82}
83
84#[test]
85fn a_file_on_an_own_mount_is_its_link() -> Outcome<()> {
86 let (own, w) = res!(tables());
87 expect(resolve("/mnt/b/w3", 30, &own, Some(&w)), HostPath::Own(PathBuf::from("/mnt/b/w3")))
88}
89
90#[test]
91fn a_container_bind_maps_through_the_shortest_host_root() -> Outcome<()> {
92 // Both host mounts 22 (root "/") and 30 (root "/home/jason/x") hold it; "/" wins.
93 let (own, w) = res!(tables());
94 expect(resolve("/x/w5", 500, &own, Some(&w)), HostPath::Mapped(PathBuf::from("/home/jason/x/w5")))
95}
96
97#[test]
98fn a_bind_maps_under_a_host_bind_when_no_whole_mount_exists() -> Outcome<()> {
99 let (own, w) = res!(tables());
100 expect(resolve("/p/src/f", 501, &own, Some(&w)), HostPath::Mapped(PathBuf::from("/srv/proj/src/f")))
101}
102
103#[test]
104fn a_mount_absent_from_the_writer_table_is_never_mapped() -> Outcome<()> {
105 // N1: a pid reused in another namespace must not give a host path.
106 let (own, w) = res!(tables());
107 expect(resolve("/x/w5", 777, &own, Some(&w)), HostPath::Unresolved(Unresolved::MountNotInWriter { mnt: 777 }))
108}
109
110#[test]
111fn a_writer_gone_is_unresolved() -> Outcome<()> {
112 let (own, _) = res!(tables());
113 expect(resolve("/x/w5", 500, &own, None), HostPath::Unresolved(Unresolved::WriterGone))
114}
115
116#[test]
117fn a_superblock_the_host_lacks_is_unresolved() -> Outcome<()> {
118 let (own, w) = res!(tables());
119 expect(resolve("/other/f", 502, &own, Some(&w)), HostPath::Unresolved(Unresolved::NoHostMount {
120 dev: "8:9".to_string(), fs_path: "/f".to_string() }))
121}
122
123#[test]
124fn a_link_outside_its_mount_point_is_unresolved() -> Outcome<()> {
125 let (own, w) = res!(tables());
126 expect(resolve("/y/f", 500, &own, Some(&w)), HostPath::Unresolved(Unresolved::NotUnderMount {
127 link: "/y/f".to_string(), point: "/x".to_string() }))
128}
129
130#[test]
131fn a_deleted_file_is_unresolved() -> Outcome<()> {
132 let (own, w) = res!(tables());
133 expect(resolve("/mnt/b/w3 (deleted)", 30, &own, Some(&w)), HostPath::Unresolved(Unresolved::Deleted {
134 link: "/mnt/b/w3 (deleted)".to_string() }))
135}
136
137#[test]
138fn mountinfo_escapes_are_undone_and_parsed() -> Outcome<()> {
139 if unescape("/a\\040b\\011c\\134d\\012") != "/a b\tc\\d\n" {
140 return Err(err!("unescape gave {:?}.", unescape("/a\\040b\\011c\\134d\\012"); Test));
141 }
142 if unescape("/no\\escape\\99") != "/no\\escape\\99" {
143 return Err(err!("unescape changed a non-escape."; Test));
144 }
145 let t = res!(MountTable::parse("7 1 8:1 /my\\040dir /mnt/my\\040point rw - ext4 /dev/sda1 rw\n"));
146 let m = res!(t.get(7).ok_or_else(|| err!("Mount 7 missing."; Test)));
147 if m.root != "/my dir" || m.point != "/mnt/my point" || m.fstype != "ext4" || m.source != "/dev/sda1" {
148 return Err(err!("Parsed {:?}.", m; Test));
149 }
150 Ok(())
151}
152
153#[test]
154fn writability_and_class_are_read_from_the_line() -> Outcome<()> {
155 let t = res!(MountTable::parse("\
1561 0 0:1 / /a rw - fuse.sshfs h:/ rw
1572 0 0:2 / /b ro,relatime - ext4 /dev/sda1 rw
1583 0 0:3 / /c rw - ext4 /dev/sda1 ro
1594 0 0:4 / /d rw - nfs4 h:/ rw
1605 0 0:5 / /proc rw - proc proc rw
1616 0 0:6 / /tmp rw,nosuid - tmpfs tmpfs rw,size=1k
162"));
163 let got: Vec<(bool, FsClass)> = t.mounts.values().map(|m| (m.rw, m.class())).collect();
164 let want = vec![(true, FsClass::Fuse), (false, FsClass::Local), (false, FsClass::Local),
165 (true, FsClass::Network), (true, FsClass::Pseudo), (true, FsClass::Local)];
166 if got != want {
167 return Err(err!("Mounts read as {:?}, not {:?}.", got, want; Test));
168 }
169 Ok(())
170}
171
172#[test]
173fn a_malformed_mountinfo_line_is_refused() -> Outcome<()> {
174 if MountTable::parse("22 1 8:1 / / rw\n").is_ok() {
175 return Err(err!("A line without the separator parsed."; Test));
176 }
177 if MountTable::parse("x 1 8:1 / / rw - ext4 /dev/sda1 rw\n").is_ok() {
178 return Err(err!("A line with a bad id parsed."; Test));
179 }
180 Ok(())
181}
182
183#[test]
184fn new_mounts_are_found_against_an_older_table() -> Outcome<()> {
185 let (own, _) = res!(tables());
186 let more = res!(MountTable::parse(&format!("{}55 22 8:1 / /mnt/loop rw - ext4 /dev/loop0 rw\n", OWN)));
187 let added = more.added_since(&own);
188 if added.len() != 1 || added[0].point != "/mnt/loop" {
189 return Err(err!("Added {:?}.", added; Test));
190 }
191 Ok(())
192}
193
194#[test]
195fn the_live_mount_id_of_a_file_is_in_the_live_table() -> Outcome<()> {
196 let exe = res!(env::current_exe());
197 let f = res!(File::open(&exe));
198 let (mnt, ino) = res!(mount_id(f.as_fd()));
199 let own = res!(MountTable::of_self());
200 if own.get(mnt).is_none() || ino == 0 {
201 return Err(err!("Mount id {} (ino {}) is not in the live table.", mnt, ino; Test));
202 }
203 let link = res!(fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(&f))));
204 expect(resolve(&link.to_string_lossy(), mnt, &own, None), HostPath::Own(link))
205}
206
207// ── Follower ──
208
209fn scratch(tag: &str) -> Outcome<PathBuf> {
210 let dir = env::temp_dir().join(format!("fe2o3-sys-notify-{}-{}", tag, std::process::id()));
211 let _ = fs::remove_dir_all(&dir);
212 res!(fs::create_dir_all(dir.join("sub")));
213 Ok(dir)
214}
215
216fn held(f: Followed) -> Outcome<FollowId> {
217 match f {
218 Followed::Held(id) => Ok(id),
219 other => Err(err!("Expected a held file, got {:?}.", other; Test)),
220 }
221}
222
223/// Reads changes until one arrives or a second passes.
224fn changes(fo: &mut Follower) -> Outcome<Vec<Change>> {
225 let end = Instant::now() + Duration::from_secs(1);
226 loop {
227 let mut p = [PollFd::new(fo.fd(), PollFlags::POLLIN)];
228 res!(poll(&mut p, PollTimeout::from(100u16)));
229 let c = res!(fo.read());
230 if !c.is_empty() || Instant::now() > end { return Ok(c); }
231 }
232}
233
234#[test]
235fn a_rename_across_directories_is_reported_old_and_new() -> Outcome<()> {
236 let d = res!(scratch("mv"));
237 let a = d.join("a");
238 res!(fs::write(&a, b"1"));
239 let mut fo = res!(Follower::new(8));
240 let id = res!(held(res!(fo.follow_path(&a))));
241 let b = d.join("sub").join("b");
242 res!(fs::rename(&a, &b));
243 let c = res!(changes(&mut fo));
244 let _ = fs::remove_dir_all(&d);
245 if c != vec![Change::Moved { id, old: a.clone(), new: b.clone() }] || fo.path(id) != Some(b.as_path()) {
246 return Err(err!("Changes {:?}.", c; Test));
247 }
248 Ok(())
249}
250
251#[test]
252fn a_file_followed_by_its_descriptor_is_followed_wherever_it_went() -> Outcome<()> {
253 // As with a fanotify event fd: the rename comes before the follow.
254 let d = res!(scratch("fd"));
255 let part = d.join("f.part");
256 res!(fs::write(&part, b"1"));
257 let open = res!(File::open(&part));
258 let f = d.join("f");
259 res!(fs::rename(&part, &f));
260 let mut fo = res!(Follower::new(8));
261 let id = res!(held(res!(fo.follow_fd(open.as_fd()))));
262 drop(open);
263 if fo.path(id) != Some(f.as_path()) {
264 return Err(err!("Followed at {:?}, not {:?}.", fo.path(id), f; Test));
265 }
266 let g = d.join("g");
267 res!(fs::rename(&f, &g));
268 let c = res!(changes(&mut fo));
269 let _ = fs::remove_dir_all(&d);
270 if c != vec![Change::Moved { id, old: f, new: g }] {
271 return Err(err!("Changes {:?}.", c; Test));
272 }
273 Ok(())
274}
275
276#[test]
277fn an_atomic_save_over_the_file_is_gone() -> Outcome<()> {
278 let d = res!(scratch("save"));
279 let f = d.join("doc");
280 res!(fs::write(&f, b"1"));
281 let mut fo = res!(Follower::new(8));
282 let id = res!(held(res!(fo.follow_path(&f))));
283 let tmp = d.join(".doc.swp");
284 res!(fs::write(&tmp, b"2"));
285 res!(fs::rename(&tmp, &f));
286 let c = res!(changes(&mut fo));
287 let _ = fs::remove_dir_all(&d);
288 if c != vec![Change::Gone { id, last: f }] || !fo.is_empty() {
289 return Err(err!("Changes {:?}, {} still held.", c, fo.len(); Test));
290 }
291 Ok(())
292}
293
294#[test]
295fn an_unlink_is_gone() -> Outcome<()> {
296 let d = res!(scratch("rm"));
297 let f = d.join("x");
298 res!(fs::write(&f, b"1"));
299 let mut fo = res!(Follower::new(8));
300 let id = res!(held(res!(fo.follow_path(&f))));
301 res!(fs::remove_file(&f));
302 let c = res!(changes(&mut fo));
303 let _ = fs::remove_dir_all(&d);
304 if c != vec![Change::Gone { id, last: f }] {
305 return Err(err!("Changes {:?}.", c; Test));
306 }
307 Ok(())
308}
309
310#[test]
311fn a_chmod_alone_changes_nothing() -> Outcome<()> {
312 let d = res!(scratch("chmod"));
313 let f = d.join("x");
314 res!(fs::write(&f, b"1"));
315 let mut fo = res!(Follower::new(8));
316 res!(held(res!(fo.follow_path(&f))));
317 res!(fs::set_permissions(&f, fs::Permissions::from_mode(0o600)));
318 let c = res!(changes(&mut fo));
319 let _ = fs::remove_dir_all(&d);
320 if !c.is_empty() || fo.len() != 1 {
321 return Err(err!("Changes {:?}.", c; Test));
322 }
323 Ok(())
324}
325
326#[test]
327fn the_same_file_twice_is_held_once() -> Outcome<()> {
328 let d = res!(scratch("twice"));
329 let f = d.join("x");
330 res!(fs::write(&f, b"1"));
331 let mut fo = res!(Follower::new(8));
332 let id = res!(held(res!(fo.follow_path(&f))));
333 let again = res!(fo.follow_path(&f));
334 let _ = fs::remove_dir_all(&d);
335 if again != Followed::Already(id) || fo.len() != 1 {
336 return Err(err!("Second follow gave {:?}, {} held.", again, fo.len(); Test));
337 }
338 Ok(())
339}
340
341#[test]
342fn follow_max_is_reported_not_swallowed() -> Outcome<()> {
343 let d = res!(scratch("max"));
344 let mut fo = res!(Follower::new(2));
345 let mut last = Followed::Full(Limit::Watches);
346 for i in 0..3 {
347 let f = d.join(format!("f{}", i));
348 res!(fs::write(&f, b"1"));
349 last = res!(fo.follow_path(&f));
350 }
351 let _ = fs::remove_dir_all(&d);
352 if last != Followed::Full(Limit::FollowMax(2)) || fo.len() != 2 {
353 return Err(err!("Third follow gave {:?}, {} held.", last, fo.len(); Test));
354 }
355 Ok(())
356}
357
358#[test]
359fn unfollow_under_releases_every_file_below_a_prefix() -> Outcome<()> {
360 let d = res!(scratch("under"));
361 let a = d.join("sub").join("a");
362 let b = d.join("b");
363 res!(fs::write(&a, b"1"));
364 res!(fs::write(&b, b"1"));
365 let mut fo = res!(Follower::new(8));
366 let ia = res!(held(res!(fo.follow_path(&a))));
367 res!(held(res!(fo.follow_path(&b))));
368 let gone = fo.unfollow_under(&d.join("sub"));
369 // Renaming the released file afterwards reports nothing.
370 res!(fs::rename(&a, d.join("sub").join("a2")));
371 let c = res!(changes(&mut fo));
372 let _ = fs::remove_dir_all(&d);
373 if gone != vec![(ia, a)] || fo.len() != 1 || !c.is_empty() {
374 return Err(err!("Released {:?}, {} held, changes {:?}.", gone, fo.len(), c; Test));
375 }
376 Ok(())
377}
378
379#[test]
380fn resync_reports_the_final_path_after_many_renames() -> Outcome<()> {
381 let d = res!(scratch("resync"));
382 let f = d.join("v0");
383 res!(fs::write(&f, b"1"));
384 let mut fo = res!(Follower::new(8));
385 let id = res!(held(res!(fo.follow_path(&f))));
386 let mut at = f.clone();
387 for i in 1..20 {
388 let next = d.join(format!("v{}", i));
389 res!(fs::rename(&at, &next));
390 at = next;
391 }
392 let c = res!(fo.resync());
393 let _ = fs::remove_dir_all(&d);
394 if c != vec![Change::Moved { id, old: f, new: at }] {
395 return Err(err!("Resync gave {:?}.", c; Test));
396 }
397 Ok(())
398}
399
400#[test]
401fn a_queue_overflow_is_reported_and_resynced() -> Outcome<()> {
402 let max: usize = res!(res!(fs::read_to_string("/proc/sys/fs/inotify/max_queued_events")).trim().parse());
403 if max > 1 << 20 {
404 return Err(err!("fs.inotify.max_queued_events is {}; this arm needs it at most {}.", max, 1 << 20; Test));
405 }
406 let d = res!(scratch("ovf"));
407 let f = d.join("o");
408 res!(fs::write(&f, b"1"));
409 let mut fo = res!(Follower::new(8));
410 let id = res!(held(res!(fo.follow_path(&f))));
411 // A chmod between renames keeps consecutive events distinct, so the kernel cannot merge them.
412 let (a, b) = (d.join("p"), d.join("q"));
413 res!(fs::rename(&f, &a));
414 for i in 0..(max / 2 + 64) {
415 res!(fs::set_permissions(&a, fs::Permissions::from_mode(if i % 2 == 0 { 0o600 } else { 0o644 })));
416 res!(fs::rename(&a, &b));
417 res!(fs::rename(&b, &a));
418 }
419 let end = d.join("final");
420 res!(fs::rename(&a, &end));
421 let mut all = Vec::new();
422 loop {
423 let c = res!(fo.read());
424 if c.is_empty() { break; }
425 all.extend(c);
426 }
427 let _ = fs::remove_dir_all(&d);
428 if !all.contains(&Change::Overflow) {
429 return Err(err!("No overflow among {} changes.", all.len(); Test));
430 }
431 if fo.path(id) != Some(end.as_path()) {
432 return Err(err!("Followed at {:?} after the overflow, not {:?}.", fo.path(id), end; Test));
433 }
434 Ok(())
435}
436
437// ── Fanotify (root) ──
438
439#[test]
440fn an_unprivileged_group_fails_loudly() -> Outcome<()> {
441 if nix::unistd::geteuid().is_root() { return Ok(()); }
442 match FanGroup::new() {
443 Ok(_) => Err(err!("fanotify_init succeeded without CAP_SYS_ADMIN."; Test)),
444 Err(e) => {
445 let msg = format!("{}", e);
446 if msg.contains("fanotify_init") { Ok(()) }
447 else { Err(err!("Unexpected refusal: {}", msg; Test)) }
448 }
449 }
450}
451
452fn fan_until<F: Fn(&FanEvent) -> bool>(g: &FanGroup, want: F) -> Outcome<Option<FanEvent>> {
453 let end = Instant::now() + Duration::from_secs(5);
454 while Instant::now() < end {
455 let mut p = [PollFd::new(g.fd(), PollFlags::POLLIN)];
456 res!(poll(&mut p, PollTimeout::from(200u16)));
457 for ev in res!(g.read()) {
458 if want(&ev) { return Ok(Some(ev)); }
459 }
460 }
461 Ok(None)
462}
463
464fn root_scratch(tag: &str) -> Outcome<PathBuf> {
465 // Cargo's scratch directory for integration tests, inside the target directory.
466 let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fe2o3-sys-notify").join(tag);
467 let _ = fs::remove_dir_all(&dir);
468 res!(fs::create_dir_all(&dir));
469 Ok(dir)
470}
471
472#[test]
473#[ignore = "needs CAP_SYS_ADMIN for fanotify; BR-4e S6 runs it as root in the VM"]
474fn root_hears_a_write_on_its_own_mount_with_its_writer() -> Outcome<()> {
475 let d = res!(root_scratch("own"));
476 let mut g = res!(FanGroup::new());
477 res!(g.mark_filesystem(&d));
478 let _ = res!(g.refresh_mounts());
479 let f = d.join("w1");
480 res!(fs::write(&f, b"x"));
481 let ev = res!(fan_until(&g, |e| matches!(e, FanEvent::Written(w) if w.link.ends_with("/w1"))));
482 res!(g.unmark_filesystem(&d));
483 let _ = fs::remove_dir_all(&d);
484 match ev {
485 Some(FanEvent::Written(w)) => {
486 if w.host != HostPath::Own(f.clone()) || w.fd().is_none() {
487 return Err(err!("Heard {:?}.", w; Test));
488 }
489 match w.writer {
490 Writer::Live { pid, uid: 0, .. } if pid == std::process::id() as i32 => Ok(()),
491 other => Err(err!("Writer {:?}.", other; Test)),
492 }
493 }
494 other => Err(err!("No write heard: {:?}.", other; Test)),
495 }
496}
497
498#[test]
499#[ignore = "needs root for a mount namespace and fanotify; BR-4e S6 runs it in the VM"]
500fn root_maps_a_write_through_another_namespace_bind_to_the_host_path() -> Outcome<()> {
501 let d = res!(root_scratch("ns"));
502 let src = d.join("src");
503 let dst = d.join("dst");
504 res!(fs::create_dir_all(&src));
505 res!(fs::create_dir_all(&dst));
506 let g = res!(FanGroup::new());
507 res!(g.mark_filesystem(&d));
508 // The bind exists only in the child's namespace; the writer stays alive to be read.
509 let script = format!("mount --bind '{}' '{}' && echo x > '{}/w3' && sleep 3", src.display(), dst.display(), dst.display());
510 let mut child = res!(Command::new("unshare").args(["-m", "--propagation", "private", "sh", "-c", &script]).spawn());
511 let ev = res!(fan_until(&g, |e| matches!(e, FanEvent::Written(w) if w.link.ends_with("/w3"))));
512 let _ = child.wait();
513 let _ = fs::remove_dir_all(&d);
514 let want = HostPath::Mapped(src.join("w3"));
515 match ev {
516 Some(FanEvent::Written(w)) if w.host == want => Ok(()),
517 Some(FanEvent::Written(w)) => Err(err!("Heard {:?}, wanted {:?}.", w, want; Test)),
518 other => Err(err!("No write heard: {:?}.", other; Test)),
519 }
520}
521
522#[test]
523#[ignore = "needs CAP_SYS_ADMIN for fanotify; BR-4e S6 runs it as root in the VM"]
524fn root_sees_overflow_on_the_bounded_queue() -> Outcome<()> {
525 let max = res!(FanGroup::max_queued_events());
526 let d = res!(root_scratch("ovf"));
527 let g = res!(FanGroup::new());
528 res!(g.mark_filesystem(&d));
529 // Distinct files, so the kernel cannot merge the events.
530 for i in 0..(max + 256) {
531 res!(fs::write(d.join(format!("f{}", i)), b"x"));
532 }
533 let ev = res!(fan_until(&g, |e| matches!(e, FanEvent::Overflow)));
534 let _ = fs::remove_dir_all(&d);
535 match ev {
536 Some(FanEvent::Overflow) => Ok(()),
537 other => Err(err!("No overflow after {} writes: {:?}.", max + 256, other; Test)),
538 }
539}