-
-
Notifications
You must be signed in to change notification settings - Fork 716
Add optional event debouncing for auto-restart #940
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7d441d9
Add a test for auto-restart on file changes
taleinat 59b20fd
Implement auto-restart event debouncing
taleinat d3f258a
lint
taleinat ab3d33a
Also protect _stop_process from running in parallel
taleinat 7493cf5
Add changlog entry
taleinat 03039e0
Move input value checking to beginning of method
taleinat e46f162
Add restart counter and improve test
taleinat c70a721
Add test doc-strings
taleinat 2ad37b5
Update tests/test_0_watchmedo.py
taleinat de0df29
Instantly handle shutdown during debouncing
taleinat 032697d
Merge branch 'master' into event-debouncing
taleinat b064b47
Lint
taleinat File filter
Filter by extension
8000
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -46,10 +46,12 @@ | |
import os | ||
import signal | ||
import subprocess | ||
import threading | ||
import time | ||
|
||
from watchdog.events import PatternMatchingEventHandler | ||
from watchdog.utils import echo | ||
from watchdog.utils.event_debouncer import EventDebouncer | ||
from watchdog.utils.process_watcher import ProcessWatcher | ||
|
||
logger = logging.getLogger(__name__) | ||
|
@@ -177,60 +179,117 @@ class AutoRestartTrick(Trick): | |
|
||
def __init__(self, command, patterns=None, ignore_patterns=None, | ||
ignore_directories=False, stop_signal=signal.SIGINT, | ||
kill_after=10): | ||
kill_after=10, debounce_interval_seconds=0): | ||
if kill_after < 0: | ||
raise ValueError("kill_after must be non-negative.") | ||
if debounce_interval_seconds < 0: | ||
raise ValueError("debounce_interval_seconds must be non-negative.") | ||
|
||
super().__init__( | ||
patterns=patterns, ignore_patterns=ignore_patterns, | ||
ignore_directories=ignore_directories) | ||
|
||
self.command = command | ||
self.stop_signal = stop_signal | ||
self.kill_after = kill_after | ||
self.debounce_interval_seconds = debounce_interval_seconds | ||
|
||
self.process = None | ||
self.process_watcher = None | ||
self.event_debouncer = None | ||
self.restart_count = 0 | ||
|
||
self._is_process_stopping = False | ||
self._is_trick_stopping = False | ||
self._stopping_lock = threading.RLock() | ||
|
||
def start(self): | ||
# windows doesn't have setsid | ||
self.process = subprocess.Popen(self.command, preexec_fn=getattr(os, 'setsid', None)) | ||
self.process_watcher = ProcessWatcher(self.process, self._restart) | ||
self.process_watcher.start() | ||
if self.debounce_interval_seconds: | ||
self.event_debouncer = EventDebouncer( | ||
debounce_interval_seconds=self.debounce_interval_seconds, | ||
events_callback=lambda events: self._restart_process(), | ||
) | ||
self.event_debouncer.start() | ||
self._start_process() | ||
|
||
def stop(self): | ||
if self.process is None: | ||
# Ensure the body of the function is only run once. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we need to ensure that it runs only once? It seems like it should behave OK even if called multiple times. |
||
with self._stopping_lock: | ||
if self._is_trick_stopping: | ||
return | ||
self._is_trick_stopping = True | ||
|
||
process_watcher = self.process_watcher | ||
if self.event_debouncer is not None: | ||
self.event_debouncer.stop() | ||
self._stop_process() | ||
|
||
# Don't leak threads: Wait for background threads to stop. | ||
if self.event_debouncer is not None: | ||
self.event_debouncer.join() | ||
process_watcher.join() | ||
|
||
def _start_process(self): | ||
if self._is_trick_stopping: | ||
return | ||
|
||
if self.process_watcher is not None: | ||
self.process_watcher.stop() | ||
self.process_watcher = None | ||
# windows doesn't have setsid | ||
self.process = subprocess.Popen(self.command, preexec_fn=getattr(os, 'setsid', None)) | ||
self.process_watcher = ProcessWatcher(self.process, self._restart_process) | ||
self.process_watcher.start() | ||
|
||
def kill_process(stop_signal): | ||
if hasattr(os, 'getpgid') and hasattr(os, 'killpg'): | ||
os.killpg(os.getpgid(self.process.pid), stop_signal) | ||
else: | ||
os.kill(self.process.pid, self.stop_signal) | ||
def _stop_process(self): | ||
# Ensure the body of the function is not run in parallel in different threads. | ||
with self._stopping_lock: | ||
if self._is_process_stopping: | ||
return | ||
self._is_process_stopping = True | ||
|
||
try: | ||
kill_process(self.stop_signal) | ||
except OSError: | ||
# Process is already gone | ||
pass | ||
else: | ||
kill_time = time.time() + self.kill_after | ||
while time.time() < kill_time: | ||
if self.process.poll() is not None: | ||
break | ||
time.sleep(0.25) | ||
else: | ||
if self.process_watcher is not None: | ||
self.process_watcher.stop() | ||
self.process_watcher = None | ||
|
||
if self.process is not None: | ||
try: | ||
kill_process(9) | ||
kill_process(self.process.pid, self.stop_signal) | ||
except OSError: | ||
# Process is already gone | ||
pass | ||
self.process = None | ||
else: | ||
kill_time = time.time() + self.kill_after | ||
while time.time() < kill_time: | ||
if self.process.poll() is not None: | ||
break | ||
time.sleep(0.25) | ||
else: | ||
try: | ||
kill_process(self.process.pid, 9) | ||
except OSError: | ||
# Process is already gone | ||
pass | ||
self.process = None | ||
finally: | ||
self._is_process_stopping = False | ||
|
||
@echo_events | ||
def on_any_event(self, event): | ||
self._restart() | ||
if self.event_debouncer is not None: | ||
self.event_debouncer.handle_event(event) | ||
else: | ||
self._restart_process() | ||
|
||
def _restart_process(self): | ||
if self._is_trick_stopping: | ||
return | ||
self._stop_process() | ||
self._start_process() | ||
self.restart_count += 1 | ||
|
||
|
||
def _restart(self): | ||
self.stop() | ||
self.start() | ||
if hasattr(os, 'getpgid') and hasattr(os, 'killpg'): | ||
def kill_process(pid, stop_signal): | ||
os.killpg(os.getpgid(pid), stop_signal) | ||
else: | ||
def kill_process(pid, stop_signal): | ||
os.kill(pid, stop_signal) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import logging | ||
import threading | ||
|
||
from watchdog.utils import BaseThread | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class EventDebouncer(BaseThread): | ||
"""Background thread for debouncing event handling. | ||
|
||
When an event is received, wait until the configured debounce interval | ||
passes before calling the callback. If additional events are received | ||
before the interval passes, reset the timer and keep waiting. When the | ||
debouncing interval passes, the callback will be called with a list of | ||
events in the order in which they were received. | ||
""" | ||
def __init__(self, debounce_interval_seconds, events_callback): | ||
super().__init__() | ||
self.debounce_interval_seconds = debounce_interval_seconds | ||
self.events_callback = events_callback | ||
|
||
self._events = [] | ||
self._cond = threading.Condition() | ||
|
||
def handle_event(self, event): | ||
with self._cond: | ||
self._events.append(event) | ||
self._cond.notify() | ||
|
||
def stop(self): | ||
with self._cond: | ||
super().stop() | ||
self._cond.notify() | ||
|
||
def run(self): | ||
with self._cond: | ||
while True: | ||
# Wait for first event (or shutdown). | ||
self._cond.wait() | ||
|
||
if self.debounce_interval_seconds: | ||
# Wait for additional events (or shutdown) until the debounce interval passes. | ||
while self.should_keep_running(): | ||
if not self._cond.wait(timeout=self.debounce_interval_seconds): | ||
break | ||
|
||
if not self.should_keep_running(): | ||
break | ||
|
||
events = self._events | ||
self._events = [] | ||
self.events_callback(events) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.