Repository navigation
Replies: 1 comment
|
Short answer: no, there is no configuration for this today; the all-or-nothing behavior on recursive watch is baked in. But the semantics you want (PollWatcher-style per-directory errors at inotify speed) fit in about 75 lines of userland code. I built it, then adversarially tested it against the failure modes a naive version has, so what follows is the version that survived, with the measured evidence. Why there is no knob: on current main (9.0.0-rc.4), The measured baseline comparison, run as an unprivileged user against a tree containing a root-only 0700 subdirectory:
The pattern (tested on notify 6.1; the APIs used are unchanged through 9.x): use notify::{Watcher, RecursiveMode, INotifyWatcher, Config, EventKind};
use notify::event::ModifyKind;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use walkdir::WalkDir;
fn plan(root: &Path) -> (Vec<PathBuf>, Vec<(PathBuf, String)>) {
let (mut ok, mut denied) = (vec![], vec![]);
let mut seen: HashSet<PathBuf> = HashSet::new();
for entry in WalkDir::new(root).follow_links(false) {
match entry {
Ok(e) if e.file_type().is_dir() => match std::fs::read_dir(e.path()) {
Ok(_) => ok.push(e.path().to_path_buf()),
Err(err) => { if seen.insert(e.path().to_path_buf()) { denied.push((e.path().to_path_buf(), err.to_string())); } }
},
Ok(_) => {}
Err(err) => {
let p = err.path().map(Path::to_path_buf).unwrap_or_default();
if seen.insert(p.clone()) { denied.push((p, err.to_string())); }
}
}
}
(ok, denied)
}
struct Tolerant { w: INotifyWatcher, watched: HashSet<PathBuf> }
impl Tolerant {
/// Watch `dir`, then scan it once: adopt sub-dirs created before the watch
/// landed and surface files already inside (this closes the create race and
/// is what makes newly-readable directories behave like PollWatcher's rescan).
fn adopt(&mut self, dir: &Path) {
if let Err(e) = self.w.watch(dir, RecursiveMode::NonRecursive) {
eprintln!("cannot watch {:?}: {}", dir, e);
return;
}
self.watched.insert(dir.to_path_buf());
let (dirs, denied) = plan(dir);
for (p, e) in denied { eprintln!("cannot watch {:?}: {}", p, e); }
for d in dirs {
if !self.watched.contains(&d) && self.w.watch(&d, RecursiveMode::NonRecursive).is_ok() {
self.watched.insert(d);
}
}
for f in WalkDir::new(dir).min_depth(1).into_iter()
.filter_map(|e| e.ok()).filter(|e| e.file_type().is_file()) {
println!("present at adoption: {:?}", f.path()); // emit as synthetic create if desired
}
}
}
fn main() -> notify::Result<()> {
let root = PathBuf::from(std::env::args().nth(1).expect("path"));
let (tx, rx) = mpsc::channel::<notify::Result<notify::Event>>();
let w = INotifyWatcher::new(tx, Config::default())?;
let mut t = Tolerant { w, watched: HashSet::new() };
let (dirs, denied) = plan(&root);
for (p, e) in &denied { eprintln!("cannot watch {:?}: {}", p, e); }
for d in &dirs {
if t.w.watch(d, RecursiveMode::NonRecursive).is_ok() { t.watched.insert(d.clone()); }
else { eprintln!("cannot watch {:?}", d); }
}
for res in rx {
match res {
Ok(ev) => {
println!("event: {:?} {:?}", ev.kind, ev.paths);
match ev.kind {
EventKind::Create(_) => {
for p in ev.paths.clone() {
if p.is_dir() && !t.watched.contains(&p) { t.adopt(&p); }
}
}
// a watched dir that disappears must be forgotten, or its
// recreation at the same path is never re-watched
EventKind::Remove(_) => { for p in &ev.paths { t.watched.remove(p); } }
// chmod making a dir readable arrives as a metadata change;
// adopting here is what PollWatcher gets for free by rescanning
EventKind::Modify(ModifyKind::Metadata(_)) => {
for p in ev.paths.clone() {
if p.is_dir() && !t.watched.contains(&p) { t.adopt(&p); }
}
}
_ => {}
}
}
Err(e) => eprintln!("watch error: {}", e),
}
}
Ok(())
}Why those three extra match arms exist: I first wrote the obvious version (initial walk plus adopt-on-Create only) and tested it against adversarial sequences; it failed three of them silently, which is the worst way to fail for a watcher. Measured, naive version vs. this one:
With those handled, the parity claim I can actually defend: this matches PollWatcher's visibility ceiling and its recovery behavior for newly readable directories. The ceiling itself is kernel-imposed and applies to every inotify consumer equally: Remaining honest caveats: directories renamed or moved into the tree arrive as rename events rather than Last thing: I searched the tracker and there is no open request for error-tolerant recursive watching; #353 (closed) covered only the reporting half. A feature request for a |
Uh oh!
There was an error while loading. Please reload this page.
If I use inotifywait from inotify-tools to monitor a directory where I have read permission on some but not all subdirectories, it will still run and emit events for files it can see. For instance, monitoring /etc for changes, and adding a user to a group via usermod:
However, trying this with notify-rs (slight modification from the README example):
It fails on the first directory my user doesn't have read permssion (root 700 in this case):
PollWatcher doesn't raise an error on initialization. Instead it sends Err events to the handler for each unpermitted directory. However, it's not performant enough to handle really large directory trees with millions of files.
Is there a way to configure INotifyWatcher to behave more like PollWatcher and send error events for directories it can't read?
All reactions