| 1 |
//! Watcher implementation for the kqueue API |
| 2 |
//! |
| 3 |
//! The kqueue() system call provides a generic method of notifying the user |
| 4 |
//! when an event happens or a condition holds, based on the results of small |
| 5 |
//! pieces of kernel code termed filters. |
| 6 |
|
| 7 |
use super::event::*; |
| 8 |
use super::{Config, Error, EventHandler, RecursiveMode, Result, Watcher}; |
| 9 |
use crate::{unbounded, Receiver, Sender}; |
| 10 |
use kqueue::{EventData, EventFilter, FilterFlag, Ident}; |
| 11 |
use std::collections::HashMap; |
| 12 |
use std::env; |
| 13 |
use std::fs::metadata; |
| 14 |
use std::os::unix::io::AsRawFd; |
| 15 |
use std::path::{Path, PathBuf}; |
| 16 |
use std::sync::Arc; |
| 17 |
use std::thread; |
| 18 |
use walkdir::WalkDir; |
| 19 |
|
| 20 |
const KQUEUE: mio::Token = mio::Token(0); |
| 21 |
const MESSAGE: mio::Token = mio::Token(1); |
| 22 |
|
| 23 |
// The EventLoop will set up a mio::Poll and use it to wait for the following: |
| 24 |
// |
| 25 |
// - messages telling it what to do |
| 26 |
// |
| 27 |
// - events telling it that something has happened on one of the watched files. |
| 28 |
struct EventLoop { |
| 29 |
running: bool, |
| 30 |
poll: mio::Poll, |
| 31 |
event_loop_waker: Arc<mio::Waker>, |
| 32 |
event_loop_tx: Sender<EventLoopMsg>, |
| 33 |
event_loop_rx: Receiver<EventLoopMsg>, |
| 34 |
kqueue: kqueue::Watcher, |
| 35 |
event_handler: Box<dyn EventHandler>, |
| 36 |
watches: HashMap<PathBuf, bool>, |
| 37 |
follow_symlinks: bool, |
| 38 |
} |
| 39 |
|
| 40 |
/// Watcher implementation based on inotify |
| 41 |
#[derive(Debug)] |
| 42 |
pub struct KqueueWatcher { |
| 43 |
channel: Sender<EventLoopMsg>, |
| 44 |
waker: Arc<mio::Waker>, |
| 45 |
} |
| 46 |
|
| 47 |
enum EventLoopMsg { |
| 48 |
AddWatch(PathBuf, RecursiveMode, Sender<Result<()>>), |
| 49 |
RemoveWatch(PathBuf, Sender<Result<()>>), |
| 50 |
Shutdown, |
| 51 |
} |
| 52 |
|
| 53 |
impl EventLoop { |
| 54 |
pub fn new( |
| 55 |
kqueue: kqueue::Watcher, |
| 56 |
event_handler: Box<dyn EventHandler>, |
| 57 |
follow_symlinks: bool, |
| 58 |
) -> Result<Self> { |
| 59 |
let (event_loop_tx, event_loop_rx) = unbounded::<EventLoopMsg>(); |
| 60 |
let poll = mio::Poll::new()?; |
| 61 |
|
| 62 |
let event_loop_waker = Arc::new(mio::Waker::new(poll.registry(), MESSAGE)?); |
| 63 |
|
| 64 |
let kqueue_fd = kqueue.as_raw_fd(); |
| 65 |
let mut evented_kqueue = mio::unix::SourceFd(&kqueue_fd); |
| 66 |
poll.registry() |
| 67 |
.register(&mut evented_kqueue, KQUEUE, mio::Interest::READABLE)?; |
| 68 |
|
| 69 |
let event_loop = EventLoop { |
| 70 |
running: true, |
| 71 |
poll, |
| 72 |
event_loop_waker, |
| 73 |
event_loop_tx, |
| 74 |
event_loop_rx, |
| 75 |
kqueue, |
| 76 |
event_handler, |
| 77 |
watches: HashMap::new(), |
| 78 |
follow_symlinks, |
| 79 |
}; |
| 80 |
Ok(event_loop) |
| 81 |
} |
| 82 |
|
| 83 |
// Run the event loop. |
| 84 |
pub fn run(self) { |
| 85 |
let _ = thread::Builder::new() |
| 86 |
.name("notify-rs kqueue loop".to_string()) |
| 87 |
.spawn(|| self.event_loop_thread()); |
| 88 |
} |
| 89 |
|
| 90 |
fn event_loop_thread(mut self) { |
| 91 |
let mut events = mio::Events::with_capacity(16); |
| 92 |
loop { |
| 93 |
// Wait for something to happen. |
| 94 |
match self.poll.poll(&mut events, None) { |
| 95 |
Err(ref e) if matches!(e.kind(), std::io::ErrorKind::Interrupted) => { |
| 96 |
// System call was interrupted, we will retry |
| 97 |
// TODO: Not covered by tests (to reproduce likely need to setup signal handlers) |
| 98 |
} |
| 99 |
Err(e) => panic!("poll failed: {}", e), |
| 100 |
Ok(()) => {} |
| 101 |
} |
| 102 |
|
| 103 |
// Process whatever happened. |
| 104 |
for event in &events { |
| 105 |
self.handle_event(event); |
| 106 |
} |
| 107 |
|
| 108 |
// Stop, if we're done. |
| 109 |
if !self.running { |
| 110 |
break; |
| 111 |
} |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
// Handle a single event. |
| 116 |
fn handle_event(&mut self, event: &mio::event::Event) { |
| 117 |
match event.token() { |
| 118 |
MESSAGE => { |
| 119 |
// The channel is readable - handle messages. |
| 120 |
self.handle_messages() |
| 121 |
} |
| 122 |
KQUEUE => { |
| 123 |
// inotify has something to tell us. |
| 124 |
self.handle_kqueue() |
| 125 |
} |
| 126 |
_ => unreachable!(), |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
fn handle_messages(&mut self) { |
| 131 |
while let Ok(msg) = self.event_loop_rx.try_recv() { |
| 132 |
match msg { |
| 133 |
EventLoopMsg::AddWatch(path, recursive_mode, tx) => { |
| 134 |
let _ = tx.send(self.add_watch(path, recursive_mode.is_recursive())); |
| 135 |
} |
| 136 |
EventLoopMsg::RemoveWatch(path, tx) => { |
| 137 |
let _ = tx.send(self.remove_watch(path, false)); |
| 138 |
} |
| 139 |
EventLoopMsg::Shutdown => { |
| 140 |
self.running = false; |
| 141 |
break; |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
fn handle_kqueue(&mut self) { |
| 148 |
let mut add_watches = Vec::new(); |
| 149 |
let mut remove_watches = Vec::new(); |
| 150 |
|
| 151 |
while let Some(event) = self.kqueue.poll(None) { |
| 152 |
log::trace!("kqueue event: {event:?}"); |
| 153 |
|
| 154 |
match event { |
| 155 |
kqueue::Event { |
| 156 |
data: EventData::Vnode(data), |
| 157 |
ident: Ident::Filename(_, path), |
| 158 |
} => { |
| 159 |
let path = PathBuf::from(path); |
| 160 |
let event = match data { |
| 161 |
/* |
| 162 |
TODO: Differentiate folders and files |
| 163 |
kqueue doesn't tell us if this was a file or a dir, so we |
| 164 |
could only emulate this inotify behavior if we keep track of |
| 165 |
all files and directories internally and then perform a |
| 166 |
lookup. |
| 167 |
*/ |
| 168 |
kqueue::Vnode::Delete => { |
| 169 |
remove_watches.push(path.clone()); |
| 170 |
Ok(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path)) |
| 171 |
} |
| 172 |
|
| 173 |
// a write to a directory means that a new file was created in it, let's |
| 174 |
// figure out which file this was |
| 175 |
kqueue::Vnode::Write if path.is_dir() => { |
| 176 |
// find which file is new in the directory by comparing it with our |
| 177 |
// list of known watches |
| 178 |
std::fs::read_dir(&path) |
| 179 |
.map(|dir| { |
| 180 |
dir.filter_map(std::result::Result::ok) |
| 181 |
.map(|f| f.path()) |
| 182 |
.find(|f| !self.watches.contains_key(f)) |
| 183 |
}) |
| 184 |
.map(|file| { |
| 185 |
if let Some(file) = file { |
| 186 |
// watch this new file |
| 187 |
add_watches.push(file.clone()); |
| 188 |
|
| 189 |
Event::new(EventKind::Create(if file.is_dir() { |
| 190 |
CreateKind::Folder |
| 191 |
} else if file.is_file() { |
| 192 |
CreateKind::File |
| 193 |
} else { |
| 194 |
CreateKind::Other |
| 195 |
})) |
| 196 |
.add_path(file) |
| 197 |
} else { |
| 198 |
Event::new(EventKind::Modify(ModifyKind::Data( |
| 199 |
DataChange::Any, |
| 200 |
))) |
| 201 |
.add_path(path) |
| 202 |
} |
| 203 |
}) |
| 204 |
.map_err(Into::into) |
| 205 |
} |
| 206 |
|
| 207 |
// data was written to this file |
| 208 |
kqueue::Vnode::Write => Ok(Event::new(EventKind::Modify( |
| 209 |
ModifyKind::Data(DataChange::Any), |
| 210 |
)) |
| 211 |
.add_path(path)), |
| 212 |
|
| 213 |
/* |
| 214 |
Extend and Truncate are just different names for the same |
| 215 |
operation, extend is only used on FreeBSD, truncate everywhere |
| 216 |
else |
| 217 |
*/ |
| 218 |
kqueue::Vnode::Extend | kqueue::Vnode::Truncate => Ok(Event::new( |
| 219 |
EventKind::Modify(ModifyKind::Data(DataChange::Size)), |
| 220 |
) |
| 221 |
.add_path(path)), |
| 222 |
|
| 223 |
/* |
| 224 |
this kevent has the same problem as the delete kevent. The |
| 225 |
only way i can think of providing "better" event with more |
| 226 |
information is to do the diff our self, while this maybe do |
| 227 |
able of delete. In this case it would somewhat expensive to |
| 228 |
keep track and compare ever peace of metadata for every file |
| 229 |
*/ |
| 230 |
kqueue::Vnode::Attrib => Ok(Event::new(EventKind::Modify( |
| 231 |
ModifyKind::Metadata(MetadataKind::Any), |
| 232 |
)) |
| 233 |
.add_path(path)), |
| 234 |
|
| 235 |
/* |
| 236 |
The link count on a file changed => subdirectory created or |
| 237 |
delete. |
| 238 |
*/ |
| 239 |
kqueue::Vnode::Link => { |
| 240 |
// As we currently don't have a solution that would allow us |
| 241 |
// to only add/remove the new/delete directory and that dosn't include a |
| 242 |
// possible race condition. On possible solution would be to |
| 243 |
// create a `HashMap<PathBuf, Vec<PathBuf>>` which would |
| 244 |
// include every directory and this content add the time of |
| 245 |
// adding it to kqueue. While this should allow us to do the |
| 246 |
// diff and only add/remove the files necessary. This would |
| 247 |
// also introduce a race condition, where multiple files could |
| 248 |
// all ready be remove from the directory, and we could get out |
| 249 |
// of sync. |
| 250 |
// So for now, until we find a better solution, let remove and |
| 251 |
// readd the whole directory. |
| 252 |
// This is a expensive operation, as we recursive through all |
| 253 |
// subdirectories. |
| 254 |
remove_watches.push(path.clone()); |
| 255 |
add_watches.push(path.clone()); |
| 256 |
Ok(Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path)) |
| 257 |
} |
| 258 |
|
| 259 |
// Kqueue not provide us with the information necessary to provide |
| 260 |
// the new file name to the event. |
| 261 |
kqueue::Vnode::Rename => { |
| 262 |
remove_watches.push(path.clone()); |
| 263 |
Ok( |
| 264 |
Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Any))) |
| 265 |
.add_path(path), |
| 266 |
) |
| 267 |
} |
| 268 |
|
| 269 |
// Access to the file was revoked via revoke(2) or the underlying file system was unmounted. |
| 270 |
kqueue::Vnode::Revoke => { |
| 271 |
remove_watches.push(path.clone()); |
| 272 |
Ok(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path)) |
| 273 |
} |
| 274 |
|
| 275 |
// On different BSD variants, different extra events may be present |
| 276 |
#[allow(unreachable_patterns)] |
| 277 |
_ => Ok(Event::new(EventKind::Other)), |
| 278 |
}; |
| 279 |
self.event_handler.handle_event(event); |
| 280 |
} |
| 281 |
// as we don't add any other EVFILTER to kqueue we should never get here |
| 282 |
kqueue::Event { ident: _, data: _ } => unreachable!(), |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
for path in remove_watches { |
| 287 |
self.remove_watch(path, true).ok(); |
| 288 |
} |
| 289 |
|
| 290 |
for path in add_watches { |
| 291 |
self.add_watch(path, true).ok(); |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
fn add_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<()> { |
| 296 |
// If the watch is not recursive, or if we determine (by stat'ing the path to get its |
| 297 |
// metadata) that the watched path is not a directory, add a single path watch. |
| 298 |
if !is_recursive || !metadata(&path).map_err(Error::io)?.is_dir() { |
| 299 |
self.add_single_watch(path, false)?; |
| 300 |
} else { |
| 301 |
for entry in WalkDir::new(path) |
| 302 |
.follow_links(self.follow_symlinks) |
| 303 |
.into_iter() |
| 304 |
{ |
| 305 |
let entry = entry.map_err(map_walkdir_error)?; |
| 306 |
self.add_single_watch(entry.into_path(), is_recursive)?; |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
// Only make a single `kevent` syscall to add all the watches. |
| 311 |
self.kqueue.watch()?; |
| 312 |
|
| 313 |
Ok(()) |
| 314 |
} |
| 315 |
|
| 316 |
/// Adds a single watch to the kqueue. |
| 317 |
/// |
| 318 |
/// The caller of this function must call `self.kqueue.watch()` afterwards to register the new watch. |
| 319 |
fn add_single_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<()> { |
| 320 |
let event_filter = EventFilter::EVFILT_VNODE; |
| 321 |
let filter_flags = FilterFlag::NOTE_DELETE |
| 322 |
| FilterFlag::NOTE_WRITE |
| 323 |
| FilterFlag::NOTE_EXTEND |
| 324 |
| FilterFlag::NOTE_ATTRIB |
| 325 |
| FilterFlag::NOTE_LINK |
| 326 |
| FilterFlag::NOTE_RENAME |
| 327 |
| FilterFlag::NOTE_REVOKE; |
| 328 |
|
| 329 |
log::trace!("adding kqueue watch: {}", path.display()); |
| 330 |
|
| 331 |
self.kqueue |
| 332 |
.add_filename(&path, event_filter, filter_flags) |
| 333 |
.map_err(|e| Error::io(e).add_path(path.clone()))?; |
| 334 |
self.watches.insert(path, is_recursive); |
| 335 |
|
| 336 |
Ok(()) |
| 337 |
} |
| 338 |
|
| 339 |
fn remove_watch(&mut self, path: PathBuf, remove_recursive: bool) -> Result<()> { |
| 340 |
log::trace!("removing kqueue watch: {}", path.display()); |
| 341 |
|
| 342 |
match self.watches.remove(&path) { |
| 343 |
None => return Err(Error::watch_not_found()), |
| 344 |
Some(is_recursive) => { |
| 345 |
if is_recursive || remove_recursive { |
| 346 |
for entry in WalkDir::new(path) |
| 347 |
.follow_links(self.follow_symlinks) |
| 348 |
.into_iter() |
| 349 |
{ |
| 350 |
let p = entry.map_err(map_walkdir_error)?.into_path(); |
| 351 |
self.kqueue |
| 352 |
.remove_filename(&p, EventFilter::EVFILT_VNODE) |
| 353 |
.map_err(|e| Error::io(e).add_path(p))?; |
| 354 |
} |
| 355 |
} else { |
| 356 |
self.kqueue |
| 357 |
.remove_filename(&path, EventFilter::EVFILT_VNODE) |
| 358 |
.map_err(|e| Error::io(e).add_path(path.clone()))?; |
| 359 |
} |
| 360 |
|
| 361 |
self.kqueue.watch()?; |
| 362 |
} |
| 363 |
} |
| 364 |
Ok(()) |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
fn map_walkdir_error(e: walkdir::Error) -> Error { |
| 369 |
if e.io_error().is_some() { |
| 370 |
// save to unwrap otherwise we whouldn't be in this branch |
| 371 |
Error::io(e.into_io_error().unwrap()) |
| 372 |
} else { |
| 373 |
Error::generic(&e.to_string()) |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
impl KqueueWatcher { |
| 378 |
fn from_event_handler( |
| 379 |
event_handler: Box<dyn EventHandler>, |
| 380 |
follow_symlinks: bool, |
| 381 |
) -> Result<Self> { |
| 382 |
let kqueue = kqueue::Watcher::new()?; |
| 383 |
let event_loop = EventLoop::new(kqueue, event_handler, follow_symlinks)?; |
| 384 |
let channel = event_loop.event_loop_tx.clone(); |
| 385 |
let waker = event_loop.event_loop_waker.clone(); |
| 386 |
event_loop.run(); |
| 387 |
Ok(KqueueWatcher { channel, waker }) |
| 388 |
} |
| 389 |
|
| 390 |
fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 391 |
let pb = if path.is_absolute() { |
| 392 |
path.to_owned() |
| 393 |
} else { |
| 394 |
let p = env::current_dir().map_err(Error::io)?; |
| 395 |
p.join(path) |
| 396 |
}; |
| 397 |
let (tx, rx) = unbounded(); |
| 398 |
let msg = EventLoopMsg::AddWatch(pb, recursive_mode, tx); |
| 399 |
|
| 400 |
self.channel |
| 401 |
.send(msg) |
| 402 |
.map_err(|e| Error::generic(&e.to_string()))?; |
| 403 |
self.waker |
| 404 |
.wake() |
| 405 |
.map_err(|e| Error::generic(&e.to_string()))?; |
| 406 |
rx.recv() |
| 407 |
.unwrap() |
| 408 |
.map_err(|e| Error::generic(&e.to_string())) |
| 409 |
} |
| 410 |
|
| 411 |
fn unwatch_inner(&mut self, path: &Path) -> Result<()> { |
| 412 |
let pb = if path.is_absolute() { |
| 413 |
path.to_owned() |
| 414 |
} else { |
| 415 |
let p = env::current_dir().map_err(Error::io)?; |
| 416 |
p.join(path) |
| 417 |
}; |
| 418 |
let (tx, rx) = unbounded(); |
| 419 |
let msg = EventLoopMsg::RemoveWatch(pb, tx); |
| 420 |
|
| 421 |
self.channel |
| 422 |
.send(msg) |
| 423 |
.map_err(|e| Error::generic(&e.to_string()))?; |
| 424 |
self.waker |
| 425 |
.wake() |
| 426 |
.map_err(|e| Error::generic(&e.to_string()))?; |
| 427 |
rx.recv() |
| 428 |
.unwrap() |
| 429 |
.map_err(|e| Error::generic(&e.to_string())) |
| 430 |
} |
| 431 |
} |
| 432 |
|
| 433 |
impl Watcher for KqueueWatcher { |
| 434 |
/// Create a new watcher. |
| 435 |
fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> { |
| 436 |
Self::from_event_handler(Box::new(event_handler), config.follow_symlinks()) |
| 437 |
} |
| 438 |
|
| 439 |
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 440 |
self.watch_inner(path, recursive_mode) |
| 441 |
} |
| 442 |
|
| 443 |
fn unwatch(&mut self, path: &Path) -> Result<()> { |
| 444 |
self.unwatch_inner(path) |
| 445 |
} |
| 446 |
|
| 447 |
fn kind() -> crate::WatcherKind { |
| 448 |
crate::WatcherKind::Kqueue |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
impl Drop for KqueueWatcher { |
| 453 |
fn drop(&mut self) { |
| 454 |
// we expect the event loop to live => unwrap must not panic |
| 455 |
self.channel.send(EventLoopMsg::Shutdown).unwrap(); |
| 456 |
self.waker.wake().unwrap(); |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
mod tests { |
| 461 |
use super::{Config, KqueueWatcher, RecursiveMode}; |
| 462 |
use crate::Watcher; |
| 463 |
use std::error::Error; |
| 464 |
use std::path::PathBuf; |
| 465 |
use std::result::Result; |
| 466 |
|
| 467 |
#[test] |
| 468 |
fn test_remove_recursive() -> Result<(), Box<dyn Error>> { |
| 469 |
let path = PathBuf::from("src"); |
| 470 |
|
| 471 |
let mut watcher = KqueueWatcher::new(|event| println!("{:?}", event), Config::default())?; |
| 472 |
watcher.watch(&path, RecursiveMode::Recursive)?; |
| 473 |
let result = watcher.unwatch(&path); |
| 474 |
assert!( |
| 475 |
result.is_ok(), |
| 476 |
"unwatch yielded error: {}", |
| 477 |
result.unwrap_err() |
| 478 |
); |
| 479 |
Ok(()) |
| 480 |
} |
| 481 |
} |