This is a great request for monitoring file changes using inotify on Linux. The user wants to:
Use epoll with pyinotify to efficiently monitor file changes
Watch a directory recursively
Wait for IN_CLOSE_WRITE events to ensure files are complete before processing
Handle the events efficiently
Let me create a comprehensive solution that includes:
A FileMonitor class that uses pyinotify with epoll
Recursive directory watching
Proper event handling with IN_CLOSE_WRITE
Example usage and error handling
Clean shutdown mechanisms
Thread-safe operations if needed
Here's what I'll include:
Basic file monitor with epoll and pyinotify
Recursive directory watching
IN_CLOSE_WRITE event handling
Processing callbacks
Proper resource cleanup
Logging
Example usage
Tests
Let me write comprehensive code:
python Copy code
import pyinotify
import os
import sys
import logging
from typing import Callable, Optional, List, Set
from pathlib import Path
import select
import time
from datetime import datetime
# ... code continues
I should create:
A FileMonitorHandler class to handle inotify events
A FileMonitor class that sets up epoll and recursively watches directories
Utility functions for processing
Example demonstrating the usage
Error handling and cleanup
File Monitoring with epoll and pyinotify
Here's a comprehensive solution for monitoring file changes recursively with efficient epoll-based event handling:
Installation
bash Copy code
pip install pyinotify
Complete Implementation
python Copy code
import pyinotify
import os
import sys
import logging
from typing import Callable, Optional, List, Set, Dict
from pathlib import Path
import select
import signal
from datetime import datetime
from threading import Lock
import traceback
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class FileMonitorEventHandler(pyinotify.ProcessEvent):
"""Handle inotify events with processing callback."""
def __init__(self, callback: Callable, extensions: Optional[List[str]] = None):
"""
Initialize event handler.
Args:
callback: Function to call when files are closed after writing
extensions: List of file extensions to monitor (e.g., ['.txt', '.json'])
If None, monitor all files
"""
super().__init__()
self.callback = callback
self.extensions = set(extensions) if extensions else None
self.processing_lock = Lock()
self.processed_files: Set[str] = set()
def _should_process(self, pathname: str) -> bool:
"""Check if file should be processed based on extension."""
if self.extensions is None:
return True
_, ext = os.path.splitext(pathname)
return ext.lower() in self.extensions
def process_IN_CLOSE_WRITE(self, event):
"""Handle IN_CLOSE_WRITE event (file closed after writing)."""
if event.dir:
return
pathname = event.pathname
if not self._should_process(pathname):
return
with self.processing_lock:
# Avoid duplicate processing
if pathname in self.processed_files:
return
self.processed_files.add(pathname)
try:
logger.info(f"File closed after writing: {pathname}")
# Verify file exists and is readable
if os.path.exists(pathname) and os.path.isfile(pathname):
file_size = os.path.getsize(pathname)
logger.info(f"File size: {file_size} bytes")
# Call the processing callback
if callable(self.callback):
self.callback(pathname)
else:
logger.warning(f"File no longer accessible: {pathname}")
except Exception as e:
logger.error(f"Error processing file {pathname}: {e}")
traceback.print_exc()
finally:
# Remove from tracking set after timeout to allow reprocessing
import threading
def cleanup():
time.sleep(5)
with self.processing_lock:
self.processed_files.discard(pathname)
threading.Thread(target=cleanup, daemon=True).start()
def process_IN_CREATE(self, event):
"""Handle IN_CREATE event (directory created)."""
if event.dir:
logger.debug(f"Directory created: {event.pathname}")
def process_IN_DELETE(self, event):
"""Handle IN_DELETE event."""
logger.info(f"File/Directory deleted: {event.pathname}")
with self.processing_lock:
self.processed_files.discard(event.pathname)
class FileMonitor:
"""Monitor files recursively using epoll and pyinotify."""
def __init__(
self,
watch_path: str,
callback: Callable,
extensions: Optional[List[str]] = None,
exclude_dirs: Optional[List[str]] = None
):
"""
Initialize file monitor.
Args:
watch_path: Root directory to watch
callback: Function to call when files are ready for processing
extensions: File extensions to monitor (None for all)
exclude_dirs: Directories to exclude from monitoring
"""
self.watch_path = Path(watch_path)
self.callback = callback
self.extensions = extensions
self.exclude_dirs = set(exclude_dirs or [])
self.watch_manager = pyinotify.WatchManager()
self.handler = FileMonitorEventHandler(callback, extensions)
# Create notifier with auto_add=True for recursive watching
self.notifier = pyinotify.Notifier(
self.watch_manager,
self.handler,
read_freq_ms=1000
)
self.watches: Dict[str, int] = {}
self.running = False
self._setup_signal_handlers()
def _setup_signal_handlers(self):
"""Setup signal handlers for graceful shutdown."""
signal.signal(signal.SIGINT, self._handle_signal)
signal.signal(signal.SIGTERM, self._handle_signal)
def _handle_signal(self, signum, frame):
"""Handle shutdown signals."""
logger.info(f"Received signal {signum}, shutting down...")
self.stop()
sys.exit(0)
def _get_watch_mask(self) -> int:
"""Get the mask for inotify events to watch."""
# IN_CLOSE_WRITE: file closed after writing
# IN_CREATE: file/directory created
# IN_DELETE: file/directory deleted
# IN_MOVED_TO: file/dir moved into watched area
return pyinotify.IN_CLOSE_WRITE | \
pyinotify.IN_CREATE | \
pyinotify.IN_DELETE | \
pyinotify.IN_MOVED_TO
def _should_exclude(self, path: str) -> bool:
"""Check if path should be excluded."""
path_obj = Path(path)
# Check against exclude patterns
for exclude in self.exclude_dirs:
if exclude in path_obj.parts:
return True
# Exclude hidden directories
for part in path_obj.parts:
if part.startswith('.'):
return True
return False
def _watch_directory(self, directory: str) -> bool:
"""
Watch a directory.
Args:
directory: Path to watch
Returns:
True if watch was added successfully
"""
if not os.path.isdir(directory):
return False
if self._should_exclude(directory):
logger.debug(f"Excluding directory: {directory}")
return False
try:
watch_descriptor = self.watch_manager.add_watch(
directory,
self._get_watch_mask(),
auto_add=True,
rec=True
)
self.watches[directory] = watch_descriptor[directory]
logger.info(f"Watching directory: {directory}")
return True
except pyinotify.InotifyError as e:
logger.error(f"Failed to watch {directory}: {e}")
return False
def start(self):
"""Start monitoring."""
if not self.watch_path.exists():
raise ValueError(f"Watch path does not exist: {self.watch_path}")
if not self.watch_path.is_dir():
raise ValueError(f"Watch path is not a directory: {self.watch_path}")
logger.info(f"Starting file monitor on {self.watch_path}")
self.running = True
# Initial watch of root directory (includes subdirectories recursively)
self._watch_directory(str(self.watch_path))
# Use epoll for efficient event monitoring
self._monitor_with_epoll()
def _monitor_with_epoll(self):
"""Monitor using epoll for efficient event handling."""
try:
# Get the file descriptor from the notifier
inotify_fd = self.notifier._fd
# Create an epoll object
epoll = select.epoll()
epoll.register(inotify_fd, select.EPOLLIN)
logger.info("Monitoring started (Press Ctrl+C to stop)")
while self.running:
try:
# Wait for events with timeout
events = epoll.poll(timeout=1000, maxevents=10)
if events:
# Process pending events
if self.notifier.check_events():
self.notifier.read_events()
self.notifier.process_events()
# Periodic status check
logger.debug(f"Active watches: {len(self.watches)}")
except Exception as e:
logger.error(f"Error in event loop: {e}")
except Exception as e:
logger.error(f"Error in epoll monitoring: {e}")
traceback.print_exc()
finally:
epoll.close()
def stop(self):
"""Stop monitoring and cleanup."""
logger.info("Stopping file monitor...")
self.running = False
if self.notifier:
self.notifier.stop()
self.watch_manager.close()
logger.info("File monitor stopped")
def add_watch(self, path: str) -> bool:
"""
Add a new directory to watch.
Args:
path: Path to directory to watch
Returns:
True if watch was added
"""
return self._watch_directory(path)
def remove_watch(self, path: str) -> bool:
"""
Remove a directory from watch.
Args:
path: Path to directory to stop watching
Returns:
True if watch was removed
"""
if path not in self.watches:
return False
try:
watch_descriptor = self.watches[path]
self.watch_manager.del_watch(watch_descriptor)
del self.watches[path]
logger.info(f"Removed watch: {path}")
return True
except Exception as e:
logger.error(f"Failed to remove watch {path}: {e}")
return False
Example Usage
python Copy code
import time
from pathlib import Path
import json
def process_json_file(filepath: str):
"""Process a JSON file."""
logger.info(f"Processing JSON file: {filepath}")
try:
with open(filepath, 'r') as f:
data = json.load(f)
logger.info(f"Successfully loaded JSON: {json.dumps(data, indent=2)}")
# Perform your processing here
# Example: validate, transform, upload, etc.
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in {filepath}: {e}")
except Exception as e:
logger.error(f"Error processing {filepath}: {e}")
def process_text_file(filepath: str):
"""Process a text file."""
logger.info(f"Processing text file: {filepath}")
try:
with open(filepath, 'r') as f:
lines = f.readlines()
logger.info(f"File contains {len(lines)} lines")
# Perform your processing here
for i, line in enumerate(lines[:5], 1): # Show first 5 lines
logger.info(f" Line {i}: {line.strip()}")
except Exception as e:
logger.error(f"Error processing {filepath}: {e}")
def main():
"""Main function."""
# Create test directory structure
test_dir = Path("/tmp/file_monitor_test")
test_dir.mkdir(exist_ok=True)
subdir = test_dir / "subdir"
subdir.mkdir(exist_ok=True)
exclude_dir = test_dir / ".cache"
exclude_dir.mkdir(exist_ok=True)
# Create file monitor for JSON files
monitor = FileMonitor(
watch_path=str(test_dir),
callback=process_json_file,
extensions=['.json', '.txt'],
exclude_dirs=['.cache', '__pycache__']
)
try:
# Start monitoring in a separate thread
import threading
monitor_thread = threading.Thread(target=monitor.start, daemon=False)
monitor_thread.start()
# Simulate file creation
time.sleep(2)
print("\n=== Creating test files ===\n")
# Test 1: Create JSON file
json_file = test_dir / "test.json"
with open(json_file, 'w') as f:
json.dump({"status": "success", "timestamp": datetime.now().isoformat()}, f)
time.sleep(1)
# Test 2: Create file in subdirectory
json_file2 = subdir / "data.json"
with open(json_file2, 'w') as f:
json.dump({"user": "alice", "id": 123}, f)
time.sleep(1)
# Test 3: Create text file
txt_file = test_dir / "notes.txt"
with open(txt_file, 'w') as f:
f.write("Line 1: Hello\n")
f.write("Line 2: World\n")
time.sleep(1)
# Test 4: Modify JSON file
with open(json_file, 'w') as f:
json.dump({"status": "updated", "value": 42}, f)
time.sleep(2)
# Keep running
monitor_thread.join()
except KeyboardInterrupt:
logger.info("Interrupted by user")
finally:
monitor.stop()
if __name__ == "__main__":
main()
Advanced Example with Thread Pool
python Copy code
from concurrent.futures import ThreadPoolExecutor
import queue
class ThreadedFileMonitor:
"""File monitor with thread pool for processing."""
def __init__(
self,
watch_path: str,
callback: Callable,
extensions: Optional[List[str]] = None,
max_workers: int = 4
):
self.monitor = FileMonitor(watch_path, self._queue_callback, extensions)
self.callback = callback
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.queue: queue.Queue = queue.Queue()
def _queue_callback(self, filepath: str):
"""Queue file for processing."""
self.queue.put(filepath)
def start(self):
"""Start monitoring and processing."""
import threading
# Start monitor
monitor_thread = threading.Thread(
target=self.monitor.start,
daemon=True
)
monitor_thread.start()
# Start processor
processor_thread = threading.Thread(
target=self._process_queue,
daemon=False
)
processor_thread.start()
return processor_thread
def _process_queue(self):
"""Process files from queue."""
while True:
try:
filepath = self.queue.get(timeout=1)
self.executor.submit(self.callback, filepath)
except queue.Empty:
continue
except Exception as e:
logger.error(f"Error in processor: {e}")
def stop(self):
"""Stop monitoring."""
self.monitor.stop()
self.executor.shutdown(wait=True)
# Usage
def heavy_processing(filepath: str):
"""Simulate heavy processing."""
logger.info(f"Starting heavy processing of {filepath}")
time.sleep(2)
logger.info(f"Completed processing of {filepath}")
if __name__ == "__main__":
monitor = ThreadedFileMonitor(
watch_path="/tmp/file_monitor_test",
callback=heavy_processing,
extensions=['.json', '.txt'],
max_workers=2
)
processor = monitor.start()
processor.join()
Key Features
✅ epoll-based monitoring - Efficient event handling
✅ Recursive directory watching - Monitors subdirectories automatically
✅ IN_CLOSE_WRITE events - Processes only complete files
✅ File filtering - Filter by extension
✅ Directory exclusion - Skip certain directories
✅ Graceful shutdown - Signal handlers for clean exit
✅ Error handling - Comprehensive exception management
✅ Thread-safe operations - Lock-based synchronization
✅ Thread pool support - Process files concurrently
✅ Logging - Detailed operational logging
This solution efficiently monitors files with minimal CPU usage and processes complete files reliably!