Skip to main content

notify/
inotify.rs

1//! Watcher implementation for the inotify Linux API
2//!
3//! The inotify API provides a mechanism for monitoring filesystem events.  Inotify can be used to
4//! monitor individual files, or to monitor directories.  When a directory is monitored, inotify
5//! will return events for the directory itself, and for files inside the directory.
6
7use super::event::*;
8use super::{Config, Error, ErrorKind, EventHandler, RecursiveMode, Result, Watcher};
9use crate::{bounded, unbounded, BoundSender, Receiver, Sender};
10use inotify as inotify_sys;
11use inotify_sys::{EventMask, Inotify, WatchDescriptor, WatchMask};
12use std::collections::HashMap;
13use std::env;
14use std::ffi::OsStr;
15use std::fs::metadata;
16use std::os::unix::io::AsRawFd;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::thread;
20use walkdir::WalkDir;
21
22const INOTIFY: mio::Token = mio::Token(0);
23const MESSAGE: mio::Token = mio::Token(1);
24
25// The EventLoop will set up a mio::Poll and use it to wait for the following:
26//
27// -  messages telling it what to do
28//
29// -  events telling it that something has happened on one of the watched files.
30
31struct EventLoop {
32    running: bool,
33    poll: mio::Poll,
34    event_loop_waker: Arc<mio::Waker>,
35    event_loop_tx: Sender<EventLoopMsg>,
36    event_loop_rx: Receiver<EventLoopMsg>,
37    inotify: Option<Inotify>,
38    event_handler: Box<dyn EventHandler>,
39    /// PathBuf -> (WatchDescriptor, WatchMask, is_recursive, is_dir)
40    watches: HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
41    paths: HashMap<WatchDescriptor, PathBuf>,
42    rename_event: Option<Event>,
43    follow_links: bool,
44}
45
46/// Watcher implementation based on inotify
47#[derive(Debug)]
48pub struct INotifyWatcher {
49    channel: Sender<EventLoopMsg>,
50    waker: Arc<mio::Waker>,
51}
52
53enum EventLoopMsg {
54    AddWatch(PathBuf, RecursiveMode, Sender<Result<()>>),
55    RemoveWatch(PathBuf, Sender<Result<()>>),
56    Shutdown,
57    Configure(Config, BoundSender<Result<bool>>),
58}
59
60#[inline]
61fn add_watch_by_event(
62    path: &PathBuf,
63    event: &inotify_sys::Event<&OsStr>,
64    watches: &HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
65    add_watches: &mut Vec<PathBuf>,
66) {
67    if event.mask.contains(EventMask::ISDIR) {
68        if let Some(parent_path) = path.parent() {
69            if let Some(&(_, _, is_recursive, _)) = watches.get(parent_path) {
70                if is_recursive {
71                    add_watches.push(path.to_owned());
72                }
73            }
74        }
75    }
76}
77
78#[inline]
79fn remove_watch_by_event(
80    path: &PathBuf,
81    watches: &HashMap<PathBuf, (WatchDescriptor, WatchMask, bool, bool)>,
82    remove_watches: &mut Vec<PathBuf>,
83) {
84    if watches.contains_key(path) {
85        remove_watches.push(path.to_owned());
86    }
87}
88
89impl EventLoop {
90    pub fn new(
91        inotify: Inotify,
92        event_handler: Box<dyn EventHandler>,
93        follow_links: bool,
94    ) -> Result<Self> {
95        let (event_loop_tx, event_loop_rx) = unbounded::<EventLoopMsg>();
96        let poll = mio::Poll::new()?;
97
98        let event_loop_waker = Arc::new(mio::Waker::new(poll.registry(), MESSAGE)?);
99
100        let inotify_fd = inotify.as_raw_fd();
101        let mut evented_inotify = mio::unix::SourceFd(&inotify_fd);
102        poll.registry()
103            .register(&mut evented_inotify, INOTIFY, mio::Interest::READABLE)?;
104
105        let event_loop = EventLoop {
106            running: true,
107            poll,
108            event_loop_waker,
109            event_loop_tx,
110            event_loop_rx,
111            inotify: Some(inotify),
112            event_handler,
113            watches: HashMap::new(),
114            paths: HashMap::new(),
115            rename_event: None,
116            follow_links,
117        };
118        Ok(event_loop)
119    }
120
121    // Run the event loop.
122    pub fn run(self) {
123        let _ = thread::Builder::new()
124            .name("notify-rs inotify loop".to_string())
125            .spawn(|| self.event_loop_thread());
126    }
127
128    fn event_loop_thread(mut self) {
129        let mut events = mio::Events::with_capacity(16);
130        loop {
131            // Wait for something to happen.
132            match self.poll.poll(&mut events, None) {
133                Err(ref e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {
134                    // System call was interrupted, we will retry
135                    // TODO: Not covered by tests (to reproduce likely need to setup signal handlers)
136                }
137                Err(e) => panic!("poll failed: {}", e),
138                Ok(()) => {}
139            }
140
141            // Process whatever happened.
142            for event in &events {
143                self.handle_event(event);
144            }
145
146            // Stop, if we're done.
147            if !self.running {
148                break;
149            }
150        }
151    }
152
153    // Handle a single event.
154    fn handle_event(&mut self, event: &mio::event::Event) {
155        match event.token() {
156            MESSAGE => {
157                // The channel is readable - handle messages.
158                self.handle_messages()
159            }
160            INOTIFY => {
161                // inotify has something to tell us.
162                self.handle_inotify()
163            }
164            _ => unreachable!(),
165        }
166    }
167
168    fn handle_messages(&mut self) {
169        while let Ok(msg) = self.event_loop_rx.try_recv() {
170            match msg {
171                EventLoopMsg::AddWatch(path, recursive_mode, tx) => {
172                    let _ = tx.send(self.add_watch(path, recursive_mode.is_recursive(), true));
173                }
174                EventLoopMsg::RemoveWatch(path, tx) => {
175                    let _ = tx.send(self.remove_watch(path, false));
176                }
177                EventLoopMsg::Shutdown => {
178                    let _ = self.remove_all_watches();
179                    if let Some(inotify) = self.inotify.take() {
180                        let _ = inotify.close();
181                    }
182                    self.running = false;
183                    break;
184                }
185                EventLoopMsg::Configure(config, tx) => {
186                    self.configure_raw_mode(config, tx);
187                }
188            }
189        }
190    }
191
192    fn configure_raw_mode(&mut self, _config: Config, tx: BoundSender<Result<bool>>) {
193        tx.send(Ok(false))
194            .expect("configuration channel disconnected");
195    }
196
197    fn handle_inotify(&mut self) {
198        let mut add_watches = Vec::new();
199        let mut remove_watches = Vec::new();
200
201        if let Some(ref mut inotify) = self.inotify {
202            let mut buffer = [0; 1024];
203            // Read all buffers available.
204            loop {
205                match inotify.read_events(&mut buffer) {
206                    Ok(events) => {
207                        let mut num_events = 0;
208                        for event in events {
209                            log::trace!("inotify event: {event:?}");
210
211                            num_events += 1;
212                            if event.mask.contains(EventMask::Q_OVERFLOW) {
213                                let ev = Ok(Event::new(EventKind::Other).set_flag(Flag::Rescan));
214                                self.event_handler.handle_event(ev);
215                            }
216
217                            let path = match event.name {
218                                Some(name) => self.paths.get(&event.wd).map(|root| root.join(name)),
219                                None => self.paths.get(&event.wd).cloned(),
220                            };
221
222                            let path = match path {
223                                Some(path) => path,
224                                None => {
225                                    log::debug!("inotify event with unknown descriptor: {event:?}");
226                                    continue;
227                                }
228                            };
229
230                            let mut evs = Vec::new();
231
232                            if event.mask.contains(EventMask::MOVED_FROM) {
233                                remove_watch_by_event(&path, &self.watches, &mut remove_watches);
234
235                                let event = Event::new(EventKind::Modify(ModifyKind::Name(
236                                    RenameMode::From,
237                                )))
238                                .add_path(path.clone())
239                                .set_tracker(event.cookie as usize);
240
241                                self.rename_event = Some(event.clone());
242
243                                evs.push(event);
244                            } else if event.mask.contains(EventMask::MOVED_TO) {
245                                evs.push(
246                                    Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::To)))
247                                        .set_tracker(event.cookie as usize)
248                                        .add_path(path.clone()),
249                                );
250
251                                let trackers_match =
252                                    self.rename_event.as_ref().and_then(|e| e.tracker())
253                                        == Some(event.cookie as usize);
254
255                                if trackers_match {
256                                    let rename_event = self.rename_event.take().unwrap(); // unwrap is safe because `rename_event` must be set at this point
257                                    evs.push(
258                                        Event::new(EventKind::Modify(ModifyKind::Name(
259                                            RenameMode::Both,
260                                        )))
261                                        .set_tracker(event.cookie as usize)
262                                        .add_some_path(rename_event.paths.first().cloned())
263                                        .add_path(path.clone()),
264                                    );
265                                }
266                                add_watch_by_event(&path, &event, &self.watches, &mut add_watches);
267                            }
268                            if event.mask.contains(EventMask::MOVE_SELF) {
269                                evs.push(
270                                    Event::new(EventKind::Modify(ModifyKind::Name(
271                                        RenameMode::From,
272                                    )))
273                                    .add_path(path.clone()),
274                                );
275                                // TODO stat the path and get to new path
276                                // - emit To and Both events
277                                // - change prefix for further events
278                            }
279                            if event.mask.contains(EventMask::CREATE) {
280                                evs.push(
281                                    Event::new(EventKind::Create(
282                                        if event.mask.contains(EventMask::ISDIR) {
283                                            CreateKind::Folder
284                                        } else {
285                                            CreateKind::File
286                                        },
287                                    ))
288                                    .add_path(path.clone()),
289                                );
290                                add_watch_by_event(&path, &event, &self.watches, &mut add_watches);
291                            }
292                            if event.mask.contains(EventMask::DELETE) {
293                                evs.push(
294                                    Event::new(EventKind::Remove(
295                                        if event.mask.contains(EventMask::ISDIR) {
296                                            RemoveKind::Folder
297                                        } else {
298                                            RemoveKind::File
299                                        },
300                                    ))
301                                    .add_path(path.clone()),
302                                );
303                                remove_watch_by_event(&path, &self.watches, &mut remove_watches);
304                            }
305                            if event.mask.contains(EventMask::DELETE_SELF) {
306                                let remove_kind = match self.watches.get(&path) {
307                                    Some(&(_, _, _, true)) => RemoveKind::Folder,
308                                    Some(&(_, _, _, false)) => RemoveKind::File,
309                                    None => RemoveKind::Other,
310                                };
311                                evs.push(
312                                    Event::new(EventKind::Remove(remove_kind))
313                                        .add_path(path.clone()),
314                                );
315                                remove_watch_by_event(&path, &self.watches, &mut remove_watches);
316                            }
317                            if event.mask.contains(EventMask::MODIFY) {
318                                evs.push(
319                                    Event::new(EventKind::Modify(ModifyKind::Data(
320                                        DataChange::Any,
321                                    )))
322                                    .add_path(path.clone()),
323                                );
324                            }
325                            if event.mask.contains(EventMask::CLOSE_WRITE) {
326                                evs.push(
327                                    Event::new(EventKind::Access(AccessKind::Close(
328                                        AccessMode::Write,
329                                    )))
330                                    .add_path(path.clone()),
331                                );
332                            }
333                            if event.mask.contains(EventMask::CLOSE_NOWRITE) {
334                                evs.push(
335                                    Event::new(EventKind::Access(AccessKind::Close(
336                                        AccessMode::Read,
337                                    )))
338                                    .add_path(path.clone()),
339                                );
340                            }
341                            if event.mask.contains(EventMask::ATTRIB) {
342                                evs.push(
343                                    Event::new(EventKind::Modify(ModifyKind::Metadata(
344                                        MetadataKind::Any,
345                                    )))
346                                    .add_path(path.clone()),
347                                );
348                            }
349                            if event.mask.contains(EventMask::OPEN) {
350                                evs.push(
351                                    Event::new(EventKind::Access(AccessKind::Open(
352                                        AccessMode::Any,
353                                    )))
354                                    .add_path(path.clone()),
355                                );
356                            }
357
358                            for ev in evs {
359                                self.event_handler.handle_event(Ok(ev));
360                            }
361                        }
362
363                        // All events read. Break out.
364                        if num_events == 0 {
365                            break;
366                        }
367                    }
368                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
369                        // No events read. Break out.
370                        break;
371                    }
372                    Err(e) => {
373                        self.event_handler.handle_event(Err(Error::io(e)));
374                    }
375                }
376            }
377        }
378
379        for path in remove_watches {
380            if let Err(err) = self.remove_watch(path, true) {
381                log::warn!("Unable to remove the path from the watches: {err:?}");
382            }
383        }
384
385        for path in add_watches {
386            if let Err(add_watch_error) = self.add_watch(path, true, false) {
387                // The handler should be notified if we have reached the limit.
388                // Otherwise, the user might expect that a recursive watch
389                // is continuing to work correctly, but it's not.
390                if let ErrorKind::MaxFilesWatch = add_watch_error.kind {
391                    self.event_handler.handle_event(Err(add_watch_error));
392
393                    // After that kind of a error we should stop adding watches,
394                    // because the limit has already reached and all next calls
395                    // will return us only the same error.
396                    break;
397                }
398            }
399        }
400    }
401
402    fn add_watch(&mut self, path: PathBuf, is_recursive: bool, mut watch_self: bool) -> Result<()> {
403        // If the watch is not recursive, or if we determine (by stat'ing the path to get its
404        // metadata) that the watched path is not a directory, add a single path watch.
405        if !is_recursive || !metadata(&path).map_err(Error::io_watch)?.is_dir() {
406            return self.add_single_watch(path, false, true);
407        }
408
409        for entry in WalkDir::new(path)
410            .follow_links(self.follow_links)
411            .into_iter()
412            .filter_map(filter_dir)
413        {
414            self.add_single_watch(entry.into_path(), is_recursive, watch_self)?;
415            watch_self = false;
416        }
417
418        Ok(())
419    }
420
421    fn add_single_watch(
422        &mut self,
423        path: PathBuf,
424        is_recursive: bool,
425        watch_self: bool,
426    ) -> Result<()> {
427        let mut watchmask = WatchMask::ATTRIB
428            | WatchMask::CREATE
429            | WatchMask::OPEN
430            | WatchMask::DELETE
431            | WatchMask::CLOSE_WRITE
432            | WatchMask::MODIFY
433            | WatchMask::MOVED_FROM
434            | WatchMask::MOVED_TO;
435
436        if watch_self {
437            watchmask.insert(WatchMask::DELETE_SELF);
438            watchmask.insert(WatchMask::MOVE_SELF);
439        }
440
441        if let Some(&(_, old_watchmask, _, _)) = self.watches.get(&path) {
442            watchmask.insert(old_watchmask);
443            watchmask.insert(WatchMask::MASK_ADD);
444        }
445
446        if let Some(ref mut inotify) = self.inotify {
447            log::trace!("adding inotify watch: {}", path.display());
448
449            match inotify.watches().add(&path, watchmask) {
450                Err(e) => {
451                    Err(if e.raw_os_error() == Some(libc::ENOSPC) {
452                        // do not report inotify limits as "no more space" on linux #266
453                        Error::new(ErrorKind::MaxFilesWatch)
454                    } else if e.kind() == std::io::ErrorKind::NotFound {
455                        Error::new(ErrorKind::PathNotFound)
456                    } else {
457                        Error::io(e)
458                    }
459                    .add_path(path))
460                }
461                Ok(w) => {
462                    watchmask.remove(WatchMask::MASK_ADD);
463                    let is_dir = metadata(&path).map_err(Error::io)?.is_dir();
464                    self.watches
465                        .insert(path.clone(), (w.clone(), watchmask, is_recursive, is_dir));
466                    self.paths.insert(w, path);
467                    Ok(())
468                }
469            }
470        } else {
471            Ok(())
472        }
473    }
474
475    fn remove_watch(&mut self, path: PathBuf, remove_recursive: bool) -> Result<()> {
476        match self.watches.remove(&path) {
477            None => return Err(Error::watch_not_found().add_path(path)),
478            Some((w, _, is_recursive, _)) => {
479                if let Some(ref mut inotify) = self.inotify {
480                    let mut inotify_watches = inotify.watches();
481                    log::trace!("removing inotify watch for {path:?}, remove_recursive: {remove_recursive:?}");
482
483                    Self::remove_single_descriptor(&mut inotify_watches, w.clone());
484                    self.paths.remove(&w);
485
486                    if is_recursive || remove_recursive {
487                        let mut remove_list = Vec::new();
488                        for (w, p) in &self.paths {
489                            if p.starts_with(&path) {
490                                Self::remove_single_descriptor(&mut inotify_watches, w.clone());
491                                self.watches.remove(p);
492                                remove_list.push(w.clone());
493                            }
494                        }
495                        for w in remove_list {
496                            self.paths.remove(&w);
497                        }
498                    }
499                }
500            }
501        }
502        Ok(())
503    }
504
505    /// As long as we use the `inotify` crate its behaviour is specified by the documentation of
506    /// a [`inotify::Watches::remove`] method:
507    /// ```text
508    /// Directly returns the error from the call to [inotify_rm_watch].
509    /// Returns an [io::Error] with [ErrorKind]::InvalidInput,
510    /// if the given WatchDescriptor did not originate from this [Inotify] instance.
511    /// ```
512    ///
513    /// inotify documentation says, that `inotify_rm_watch` may fail with two specific errors:
514    /// * EBADF - fd is not a valid file descriptor.
515    /// * EINVAL - The watch descriptor wd is not valid or fd is not an inotify file descriptor.
516    ///
517    /// Therefore, we can ignore this errors (and log it), because
518    /// * in the case, when we are removing a watch because of an caught `DELETE` or `DELETE_SELF` event we want the
519    ///   path to be not watched, and in error cases it's already done (unknown file descriptor == it is not watched)
520    /// * in the case, when user is trying to remove the watch, they can do nothing with that kind of an error,
521    ///   it's totally internal. BUT, if there are no "strange" states (like races between user call and internal call,
522    ///   when internal inotify file descriptor has already been invalidated, but the event still hasn't been handled)
523    ///   they will get an [`ErrorKind::WatchNotFound`] error and can deal with it
524    ///
525    /// Log level is info, because it is not a "real" error. Expectedly, it may occurred only by race condition
526    /// (like described above), in other cases it is a bug (but we aren't able to distinguish that states)
527    fn remove_single_descriptor(watches: &mut inotify::Watches, wd: WatchDescriptor) {
528        if let Err(err) = watches.remove(wd) {
529            log::info!("unable to remove watch descriptor from inotify: {err:?}");
530        }
531    }
532
533    fn remove_all_watches(&mut self) -> Result<()> {
534        if let Some(ref mut inotify) = self.inotify {
535            let mut inotify_watches = inotify.watches();
536            for (w, p) in &self.paths {
537                inotify_watches
538                    .remove(w.clone())
539                    .map_err(|e| Error::io(e).add_path(p.into()))?;
540            }
541            self.watches.clear();
542            self.paths.clear();
543        }
544        Ok(())
545    }
546}
547
548/// return `DirEntry` when it is a directory
549fn filter_dir(e: walkdir::Result<walkdir::DirEntry>) -> Option<walkdir::DirEntry> {
550    if let Ok(e) = e {
551        if let Ok(metadata) = e.metadata() {
552            if metadata.is_dir() {
553                return Some(e);
554            }
555        }
556    }
557    None
558}
559
560impl INotifyWatcher {
561    fn from_event_handler(
562        event_handler: Box<dyn EventHandler>,
563        follow_links: bool,
564    ) -> Result<Self> {
565        let inotify = Inotify::init()?;
566        let event_loop = EventLoop::new(inotify, event_handler, follow_links)?;
567        let channel = event_loop.event_loop_tx.clone();
568        let waker = event_loop.event_loop_waker.clone();
569        event_loop.run();
570        Ok(INotifyWatcher { channel, waker })
571    }
572
573    fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
574        let pb = if path.is_absolute() {
575            path.to_owned()
576        } else {
577            let p = env::current_dir().map_err(Error::io)?;
578            p.join(path)
579        };
580        let (tx, rx) = unbounded();
581        let msg = EventLoopMsg::AddWatch(pb, recursive_mode, tx);
582
583        // we expect the event loop to live and reply => unwraps must not panic
584        self.channel.send(msg).unwrap();
585        self.waker.wake().unwrap();
586        rx.recv().unwrap()
587    }
588
589    fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
590        let pb = if path.is_absolute() {
591            path.to_owned()
592        } else {
593            let p = env::current_dir().map_err(Error::io)?;
594            p.join(path)
595        };
596        let (tx, rx) = unbounded();
597        let msg = EventLoopMsg::RemoveWatch(pb, tx);
598
599        // we expect the event loop to live and reply => unwraps must not panic
600        self.channel.send(msg).unwrap();
601        self.waker.wake().unwrap();
602        rx.recv().unwrap()
603    }
604}
605
606impl Watcher for INotifyWatcher {
607    /// Create a new watcher.
608    fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
609        Self::from_event_handler(Box::new(event_handler), config.follow_symlinks())
610    }
611
612    fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
613        self.watch_inner(path, recursive_mode)
614    }
615
616    fn unwatch(&mut self, path: &Path) -> Result<()> {
617        self.unwatch_inner(path)
618    }
619
620    fn configure(&mut self, config: Config) -> Result<bool> {
621        let (tx, rx) = bounded(1);
622        self.channel.send(EventLoopMsg::Configure(config, tx))?;
623        self.waker.wake()?;
624        rx.recv()?
625    }
626
627    fn kind() -> crate::WatcherKind {
628        crate::WatcherKind::Inotify
629    }
630}
631
632impl Drop for INotifyWatcher {
633    fn drop(&mut self) {
634        // we expect the event loop to live => unwrap must not panic
635        self.channel.send(EventLoopMsg::Shutdown).unwrap();
636        self.waker.wake().unwrap();
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    use std::{
643        path::{Path, PathBuf},
644        sync::{atomic::AtomicBool, mpsc, Arc},
645        thread::{self, available_parallelism},
646        time::Duration,
647    };
648
649    use super::{Config, Error, ErrorKind, Event, INotifyWatcher, RecursiveMode, Result, Watcher};
650
651    use crate::test::*;
652
653    fn watcher() -> (TestWatcher<INotifyWatcher>, Receiver) {
654        channel()
655    }
656
657    #[test]
658    fn inotify_watcher_is_send_and_sync() {
659        fn check<T: Send + Sync>() {}
660        check::<INotifyWatcher>();
661    }
662
663    #[test]
664    fn native_error_type_on_missing_path() {
665        let mut watcher = INotifyWatcher::new(|_| {}, Config::default()).unwrap();
666
667        let result = watcher.watch(
668            &PathBuf::from("/some/non/existant/path"),
669            RecursiveMode::NonRecursive,
670        );
671
672        assert!(matches!(
673            result,
674            Err(Error {
675                paths: _,
676                kind: ErrorKind::PathNotFound
677            })
678        ))
679    }
680
681    /// Runs manually.
682    ///
683    /// * Save actual value of the limit: `MAX_USER_WATCHES=$(sysctl -n fs.inotify.max_user_watches)`
684    /// * Run the test.
685    /// * Set the limit to 0: `sudo sysctl fs.inotify.max_user_watches=0` while test is running
686    /// * Wait for the test to complete
687    /// * Restore the limit `sudo sysctl fs.inotify.max_user_watches=$MAX_USER_WATCHES`
688    #[test]
689    #[ignore = "requires changing sysctl fs.inotify.max_user_watches while test is running"]
690    fn recursive_watch_calls_handler_if_creating_a_file_raises_max_files_watch() {
691        use std::time::Duration;
692
693        let tmpdir = tempfile::tempdir().unwrap();
694        let (tx, rx) = std::sync::mpsc::channel();
695        let (proc_changed_tx, proc_changed_rx) = std::sync::mpsc::channel();
696        let proc_path = Path::new("/proc/sys/fs/inotify/max_user_watches");
697        let mut watcher = INotifyWatcher::new(
698            move |result: Result<Event>| match result {
699                Ok(event) => {
700                    if event.paths.first().is_some_and(|path| path == proc_path) {
701                        proc_changed_tx.send(()).unwrap();
702                    }
703                }
704                Err(e) => tx.send(e).unwrap(),
705            },
706            Config::default(),
707        )
708        .unwrap();
709
710        watcher
711            .watch(tmpdir.path(), RecursiveMode::Recursive)
712            .unwrap();
713        watcher
714            .watch(proc_path, RecursiveMode::NonRecursive)
715            .unwrap();
716
717        // give the time to set the limit
718        proc_changed_rx
719            .recv_timeout(Duration::from_secs(30))
720            .unwrap();
721
722        let child_dir = tmpdir.path().join("child");
723        std::fs::create_dir(child_dir).unwrap();
724
725        let result = rx.recv_timeout(Duration::from_millis(500));
726
727        assert!(
728            matches!(
729                &result,
730                Ok(Error {
731                    kind: ErrorKind::MaxFilesWatch,
732                    paths: _,
733                })
734            ),
735            "expected {:?}, found: {:#?}",
736            ErrorKind::MaxFilesWatch,
737            result
738        );
739    }
740
741    /// https://github.com/notify-rs/notify/issues/678
742    #[test]
743    fn race_condition_on_unwatch_and_pending_events_with_deleted_descriptor() {
744        let tmpdir = tempfile::tempdir().expect("tmpdir");
745        let (tx, rx) = mpsc::channel();
746        let mut inotify = INotifyWatcher::new(
747            move |e: Result<Event>| {
748                let e = match e {
749                    Ok(e) if e.paths.is_empty() => e,
750                    Ok(_) | Err(_) => return,
751                };
752                let _ = tx.send(e);
753            },
754            Config::default(),
755        )
756        .expect("inotify creation");
757
758        let dir_path = tmpdir.path();
759        let file_path = dir_path.join("foo");
760        std::fs::File::create(&file_path).unwrap();
761
762        let stop = Arc::new(AtomicBool::new(false));
763
764        let handles: Vec<_> = (0..available_parallelism().unwrap().get().max(4))
765            .map(|_| {
766                let file_path = file_path.clone();
767                let stop = stop.clone();
768                thread::spawn(move || {
769                    while !stop.load(std::sync::atomic::Ordering::Relaxed) {
770                        let _ = std::fs::File::open(&file_path).unwrap();
771                    }
772                })
773            })
774            .collect();
775
776        let non_recursive = RecursiveMode::NonRecursive;
777        for _ in 0..(handles.len() * 4) {
778            inotify.watch(dir_path, non_recursive).unwrap();
779            inotify.unwatch(dir_path).unwrap();
780        }
781
782        stop.store(true, std::sync::atomic::Ordering::Relaxed);
783        handles
784            .into_iter()
785            .for_each(|handle| handle.join().ok().unwrap_or_default());
786
787        drop(inotify);
788
789        let events: Vec<_> = rx.into_iter().map(|e| format!("{e:?}")).collect();
790
791        const LOG_LEN: usize = 10;
792        let events_len = events.len();
793        assert!(
794            events.is_empty(),
795            "expected no events without path, but got {events_len}. first 10: {:#?}",
796            &events[..LOG_LEN.min(events_len)]
797        );
798    }
799
800    /// https://github.com/notify-rs/notify/issues/709
801    #[test]
802    fn remove_a_subdir_in_a_recursively_watched_parent() {
803        let tmpdir = tempfile::tempdir().expect("tmpdir");
804        let subdirectory_path_1 = tmpdir.path().join("subdir");
805        let subdirectory_path_2 = subdirectory_path_1.join("nested");
806        std::fs::create_dir(&subdirectory_path_1).expect("unable to create a subdir");
807        std::fs::create_dir(&subdirectory_path_2).expect("unable to create a nested dir");
808
809        let mut watcher =
810            INotifyWatcher::new(|_| (), Config::default()).expect("unable to create watcher");
811        watcher
812            .watch(tmpdir.path(), RecursiveMode::Recursive)
813            .expect("unable to watch");
814        std::fs::remove_dir_all(&subdirectory_path_1).expect("unable to remove a subdir");
815        let unwatch_result = watcher.unwatch(tmpdir.path());
816
817        assert!(
818            matches!(unwatch_result, Ok(())),
819            "error: {unwatch_result:#?}"
820        );
821    }
822
823    #[test]
824    fn create_file() {
825        let tmpdir = testdir();
826        let (mut watcher, mut rx) = watcher();
827        watcher.watch_recursively(&tmpdir);
828
829        let path = tmpdir.path().join("entry");
830        std::fs::File::create_new(&path).expect("create");
831
832        rx.wait_ordered_exact([
833            expected(&path).create_file(),
834            expected(&path).access_open_any(),
835            expected(&path).access_close_write(),
836        ]);
837    }
838
839    #[test]
840    fn write_file() {
841        let tmpdir = testdir();
842        let (mut watcher, mut rx) = watcher();
843
844        let path = tmpdir.path().join("entry");
845        std::fs::File::create_new(&path).expect("create");
846
847        watcher.watch_recursively(&tmpdir);
848        std::fs::write(&path, b"123").expect("write");
849
850        rx.wait_ordered_exact([
851            expected(&path).access_open_any(),
852            expected(&path).modify_data_any().multiple(),
853            expected(&path).access_close_write(),
854        ])
855        .ensure_no_tail();
856    }
857
858    #[test]
859    fn chmod_file() {
860        let tmpdir = testdir();
861        let (mut watcher, mut rx) = watcher();
862
863        let path = tmpdir.path().join("entry");
864        let file = std::fs::File::create_new(&path).expect("create");
865        let mut permissions = file.metadata().expect("metadata").permissions();
866        permissions.set_readonly(true);
867
868        watcher.watch_recursively(&tmpdir);
869        file.set_permissions(permissions).expect("set_permissions");
870
871        rx.wait_ordered_exact([expected(&path).modify_meta_any()]);
872    }
873
874    #[test]
875    fn rename_file() {
876        let tmpdir = testdir();
877        let (mut watcher, mut rx) = watcher();
878
879        let path = tmpdir.path().join("entry");
880        std::fs::File::create_new(&path).expect("create");
881
882        watcher.watch_recursively(&tmpdir);
883        let new_path = tmpdir.path().join("renamed");
884
885        std::fs::rename(&path, &new_path).expect("rename");
886
887        rx.wait_ordered_exact([
888            expected(&path).rename_from(),
889            expected(&new_path).rename_to(),
890            expected([path, new_path]).rename_both(),
891        ])
892        .ensure_trackers_len(1)
893        .ensure_no_tail();
894    }
895
896    #[test]
897    fn delete_file() {
898        let tmpdir = testdir();
899        let (mut watcher, mut rx) = watcher();
900        let file = tmpdir.path().join("file");
901        std::fs::write(&file, "").expect("write");
902
903        watcher.watch_nonrecursively(&tmpdir);
904
905        std::fs::remove_file(&file).expect("remove");
906
907        rx.wait_ordered_exact([expected(&file).remove_file()]);
908    }
909
910    #[test]
911    fn delete_self_file() {
912        let tmpdir = testdir();
913        let (mut watcher, mut rx) = watcher();
914        let file = tmpdir.path().join("file");
915        std::fs::write(&file, "").expect("write");
916
917        watcher.watch_nonrecursively(&file);
918
919        std::fs::remove_file(&file).expect("remove");
920
921        rx.wait_ordered_exact([
922            expected(&file).modify_meta_any(),
923            expected(&file).remove_file(),
924        ]);
925    }
926
927    #[test]
928    fn create_write_overwrite() {
929        let tmpdir = testdir();
930        let (mut watcher, mut rx) = watcher();
931        let overwritten_file = tmpdir.path().join("overwritten_file");
932        let overwriting_file = tmpdir.path().join("overwriting_file");
933        std::fs::write(&overwritten_file, "123").expect("write1");
934
935        watcher.watch_nonrecursively(&tmpdir);
936
937        std::fs::File::create(&overwriting_file).expect("create");
938        std::fs::write(&overwriting_file, "321").expect("write2");
939        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");
940
941        rx.wait_ordered_exact([
942            expected(&overwriting_file).create_file(),
943            expected(&overwriting_file).access_open_any(),
944            expected(&overwriting_file).access_close_write(),
945            expected(&overwriting_file).access_open_any(),
946            expected(&overwriting_file).modify_data_any().multiple(),
947            expected(&overwriting_file).access_close_write(),
948            expected(&overwriting_file).rename_from(),
949            expected(&overwritten_file).rename_to(),
950            expected([overwriting_file, overwritten_file]).rename_both(),
951        ])
952        .ensure_no_tail()
953        .ensure_trackers_len(1);
954    }
955
956    #[test]
957    fn create_dir() {
958        let tmpdir = testdir();
959        let (mut watcher, mut rx) = watcher();
960        watcher.watch_recursively(&tmpdir);
961
962        let path = tmpdir.path().join("entry");
963        std::fs::create_dir(&path).expect("create");
964
965        rx.wait_ordered_exact([expected(&path).create_folder()]);
966    }
967
968    #[test]
969    fn chmod_dir() {
970        let tmpdir = testdir();
971        let (mut watcher, mut rx) = watcher();
972
973        let path = tmpdir.path().join("entry");
974        std::fs::create_dir(&path).expect("create_dir");
975        let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
976        permissions.set_readonly(true);
977
978        watcher.watch_recursively(&tmpdir);
979        std::fs::set_permissions(&path, permissions).expect("set_permissions");
980
981        rx.wait_ordered_exact([
982            expected(&path).access_open_any().optional(),
983            expected(&path).modify_meta_any(),
984            expected(&path).modify_meta_any(),
985        ])
986        .ensure_no_tail();
987    }
988
989    #[test]
990    fn rename_dir() {
991        let tmpdir = testdir();
992        let (mut watcher, mut rx) = watcher();
993
994        let path = tmpdir.path().join("entry");
995        let new_path = tmpdir.path().join("new_path");
996        std::fs::create_dir(&path).expect("create_dir");
997
998        watcher.watch_recursively(&tmpdir);
999
1000        std::fs::rename(&path, &new_path).expect("rename");
1001
1002        rx.wait_ordered_exact([
1003            expected(&path).access_open_any().optional(),
1004            expected(&path).rename_from(),
1005            expected(&new_path).rename_to(),
1006            expected([path, new_path]).rename_both(),
1007        ])
1008        .ensure_trackers_len(1);
1009    }
1010
1011    #[test]
1012    fn delete_dir() {
1013        let tmpdir = testdir();
1014        let (mut watcher, mut rx) = watcher();
1015
1016        let path = tmpdir.path().join("entry");
1017        std::fs::create_dir(&path).expect("create_dir");
1018
1019        watcher.watch_recursively(&tmpdir);
1020        std::fs::remove_dir(&path).expect("remove");
1021
1022        rx.wait_ordered_exact([
1023            expected(&path).access_open_any().optional(),
1024            expected(&path).remove_folder(),
1025        ])
1026        .ensure_no_tail();
1027    }
1028
1029    #[test]
1030    fn rename_dir_twice() {
1031        let tmpdir = testdir();
1032        let (mut watcher, mut rx) = watcher();
1033
1034        let path = tmpdir.path().join("entry");
1035        let new_path = tmpdir.path().join("new_path");
1036        let new_path2 = tmpdir.path().join("new_path2");
1037        std::fs::create_dir(&path).expect("create_dir");
1038
1039        watcher.watch_recursively(&tmpdir);
1040        std::fs::rename(&path, &new_path).expect("rename");
1041        std::fs::rename(&new_path, &new_path2).expect("rename2");
1042
1043        rx.wait_ordered_exact([
1044            expected(&path).access_open_any().optional(),
1045            expected(&path).rename_from(),
1046            expected(&new_path).rename_to(),
1047            expected([&path, &new_path]).rename_both(),
1048            expected(&new_path).access_open_any().optional(),
1049            expected(&new_path).rename_from(),
1050            expected(&new_path2).rename_to(),
1051            expected([&new_path, &new_path2]).rename_both(),
1052        ])
1053        .ensure_trackers_len(2);
1054    }
1055
1056    #[test]
1057    fn move_out_of_watched_dir() {
1058        let tmpdir = testdir();
1059        let subdir = tmpdir.path().join("subdir");
1060        let (mut watcher, mut rx) = watcher();
1061
1062        let path = subdir.join("entry");
1063        std::fs::create_dir_all(&subdir).expect("create_dir_all");
1064        std::fs::File::create_new(&path).expect("create");
1065
1066        watcher.watch_recursively(&subdir);
1067        let new_path = tmpdir.path().join("entry");
1068
1069        std::fs::rename(&path, &new_path).expect("rename");
1070
1071        let event = rx.recv();
1072        let tracker = event.attrs.tracker();
1073        assert_eq!(event, expected(path).rename_from());
1074        assert!(tracker.is_some(), "tracker is none: [event:#?]");
1075        rx.ensure_empty();
1076    }
1077
1078    #[test]
1079    fn create_write_write_rename_write_remove() {
1080        let tmpdir = testdir();
1081        let (mut watcher, mut rx) = watcher();
1082
1083        let file1 = tmpdir.path().join("entry");
1084        let file2 = tmpdir.path().join("entry2");
1085        std::fs::File::create_new(&file2).expect("create file2");
1086        let new_path = tmpdir.path().join("renamed");
1087
1088        watcher.watch_recursively(&tmpdir);
1089        std::fs::write(&file1, "123").expect("write 1");
1090        std::fs::write(&file2, "321").expect("write 2");
1091        std::fs::rename(&file1, &new_path).expect("rename");
1092        std::fs::write(&new_path, b"1").expect("write 3");
1093        std::fs::remove_file(&new_path).expect("remove");
1094
1095        rx.wait_ordered_exact([
1096            expected(&file1).create_file(),
1097            expected(&file1).access_open_any(),
1098            expected(&file1).modify_data_any().multiple(),
1099            expected(&file1).access_close_write(),
1100            expected(&file2).access_open_any(),
1101            expected(&file2).modify_data_any().multiple(),
1102            expected(&file2).access_close_write(),
1103            expected(&file1).access_open_any().optional(),
1104            expected(&file1).rename_from(),
1105            expected(&new_path).rename_to(),
1106            expected([&file1, &new_path]).rename_both(),
1107            expected(&new_path).access_open_any(),
1108            expected(&new_path).modify_data_any().multiple(),
1109            expected(&new_path).access_close_write(),
1110            expected(&new_path).remove_file(),
1111        ]);
1112    }
1113
1114    #[test]
1115    fn rename_twice() {
1116        let tmpdir = testdir();
1117        let (mut watcher, mut rx) = watcher();
1118
1119        let path = tmpdir.path().join("entry");
1120        std::fs::File::create_new(&path).expect("create");
1121
1122        watcher.watch_recursively(&tmpdir);
1123        let new_path1 = tmpdir.path().join("renamed1");
1124        let new_path2 = tmpdir.path().join("renamed2");
1125
1126        std::fs::rename(&path, &new_path1).expect("rename1");
1127        std::fs::rename(&new_path1, &new_path2).expect("rename2");
1128
1129        rx.wait_ordered_exact([
1130            expected(&path).access_open_any().optional(),
1131            expected(&path).rename_from(),
1132            expected(&new_path1).rename_to(),
1133            expected([&path, &new_path1]).rename_both(),
1134            expected(&new_path1).access_open_any().optional(),
1135            expected(&new_path1).rename_from(),
1136            expected(&new_path2).rename_to(),
1137            expected([&new_path1, &new_path2]).rename_both(),
1138        ])
1139        .ensure_no_tail()
1140        .ensure_trackers_len(2);
1141    }
1142
1143    #[test]
1144    fn set_file_mtime() {
1145        let tmpdir = testdir();
1146        let (mut watcher, mut rx) = watcher();
1147
1148        let path = tmpdir.path().join("entry");
1149        let file = std::fs::File::create_new(&path).expect("create");
1150
1151        watcher.watch_recursively(&tmpdir);
1152
1153        file.set_modified(
1154            std::time::SystemTime::now()
1155                .checked_sub(Duration::from_secs(60 * 60))
1156                .expect("time"),
1157        )
1158        .expect("set_time");
1159
1160        assert_eq!(rx.recv(), expected(&path).modify_data_any());
1161        rx.ensure_empty();
1162    }
1163
1164    #[test]
1165    fn write_file_non_recursive_watch() {
1166        let tmpdir = testdir();
1167        let (mut watcher, mut rx) = watcher();
1168
1169        let path = tmpdir.path().join("entry");
1170        std::fs::File::create_new(&path).expect("create");
1171
1172        watcher.watch_nonrecursively(&path);
1173
1174        std::fs::write(&path, b"123").expect("write");
1175
1176        rx.wait_ordered_exact([
1177            expected(&path).access_open_any(),
1178            expected(&path).modify_data_any().multiple(),
1179            expected(&path).access_close_write(),
1180        ])
1181        .ensure_no_tail();
1182    }
1183
1184    #[test]
1185    fn watch_recursively_then_unwatch_child_stops_events_from_child() {
1186        let tmpdir = testdir();
1187        let (mut watcher, mut rx) = watcher();
1188
1189        let subdir = tmpdir.path().join("subdir");
1190        let file = subdir.join("file");
1191        std::fs::create_dir(&subdir).expect("create");
1192
1193        watcher.watch_recursively(&tmpdir);
1194
1195        std::fs::File::create(&file).expect("create");
1196
1197        rx.wait_ordered_exact([
1198            expected(&subdir).access_open_any().optional(),
1199            expected(&file).create_file(),
1200            expected(&file).access_open_any(),
1201            expected(&file).access_close_write(),
1202        ])
1203        .ensure_no_tail();
1204
1205        watcher.watcher.unwatch(&subdir).expect("unwatch");
1206
1207        std::fs::write(&file, b"123").expect("write");
1208
1209        std::fs::remove_dir_all(&subdir).expect("remove_dir_all");
1210
1211        rx.wait_ordered_exact([
1212            expected(&subdir).access_open_any().optional(),
1213            expected(&subdir).remove_folder(),
1214        ])
1215        .ensure_no_tail();
1216    }
1217
1218    #[test]
1219    fn write_to_a_hardlink_pointed_to_the_watched_file_triggers_an_event() {
1220        let tmpdir = testdir();
1221        let (mut watcher, mut rx) = watcher();
1222
1223        let subdir = tmpdir.path().join("subdir");
1224        let file = subdir.join("file");
1225        let hardlink = tmpdir.path().join("hardlink");
1226
1227        std::fs::create_dir(&subdir).expect("create");
1228        std::fs::write(&file, "").expect("file");
1229        std::fs::hard_link(&file, &hardlink).expect("hardlink");
1230
1231        watcher.watch_nonrecursively(&file);
1232
1233        std::fs::write(&hardlink, "123123").expect("write to the hard link");
1234
1235        rx.wait_ordered_exact([
1236            expected(&file).access_open_any(),
1237            expected(&file).modify_data_any().multiple(),
1238            expected(&file).access_close_write(),
1239        ]);
1240    }
1241
1242    #[test]
1243    fn write_to_a_hardlink_pointed_to_the_file_in_the_watched_dir_doesnt_trigger_an_event() {
1244        let tmpdir = testdir();
1245        let (mut watcher, mut rx) = watcher();
1246
1247        let subdir = tmpdir.path().join("subdir");
1248        let file = subdir.join("file");
1249        let hardlink = tmpdir.path().join("hardlink");
1250
1251        std::fs::create_dir(&subdir).expect("create");
1252        std::fs::write(&file, "").expect("file");
1253        std::fs::hard_link(&file, &hardlink).expect("hardlink");
1254
1255        watcher.watch_nonrecursively(&subdir);
1256
1257        std::fs::write(&hardlink, "123123").expect("write to the hard link");
1258
1259        let events = rx.iter().collect::<Vec<_>>();
1260        assert!(events.is_empty(), "unexpected events: {events:#?}");
1261    }
1262
1263    #[test]
1264    #[ignore = "see https://github.com/notify-rs/notify/issues/727"]
1265    fn recursive_creation() {
1266        let tmpdir = testdir();
1267        let nested1 = tmpdir.path().join("1");
1268        let nested2 = tmpdir.path().join("1/2");
1269        let nested3 = tmpdir.path().join("1/2/3");
1270        let nested4 = tmpdir.path().join("1/2/3/4");
1271        let nested5 = tmpdir.path().join("1/2/3/4/5");
1272        let nested6 = tmpdir.path().join("1/2/3/4/5/6");
1273        let nested7 = tmpdir.path().join("1/2/3/4/5/6/7");
1274        let nested8 = tmpdir.path().join("1/2/3/4/5/6/7/8");
1275        let nested9 = tmpdir.path().join("1/2/3/4/5/6/7/8/9");
1276
1277        let (mut watcher, mut rx) = watcher();
1278
1279        watcher.watch_recursively(&tmpdir);
1280
1281        std::fs::create_dir_all(&nested9).expect("create_dir_all");
1282        rx.wait_ordered([
1283            expected(&nested1).create_folder(),
1284            expected(&nested2).create_folder(),
1285            expected(&nested3).create_folder(),
1286            expected(&nested4).create_folder(),
1287            expected(&nested5).create_folder(),
1288            expected(&nested6).create_folder(),
1289            expected(&nested7).create_folder(),
1290            expected(&nested8).create_folder(),
1291            expected(&nested9).create_folder(),
1292        ]);
1293    }
1294}