Skip to content

Commit

Permalink
fix: Handle SIGTERM more gracefully in watchmedo
Browse files Browse the repository at this point in the history
This fixes some misbehaviour where the child process could be orphaned
if watchmedo received multiple SIGTERMs causing the `stop()` call to be
interrupted. By raising a semantic exception after neutering the signal
handler, we give ourselves a better chance of killing the child.
  • Loading branch information
maybe-sybr committed Oct 20, 2020
1 parent 60c57ae commit a2767ae
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/watchdog/watchmedo.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@
CONFIG_KEY_PYTHON_PATH = 'python-path'


class ShutdownWatchdog(Exception):
"""
Semantic exception used to signal an external shutdown event.
"""
pass


def path_split(pathname_spec, separator=os.pathsep):
"""
Splits a pathname specification separated by an OS-dependent separator.
Expand Down Expand Up @@ -531,10 +538,12 @@ def auto_restart(args):
else:
stop_signal = int(args.signal)

# Handle SIGTERM in the same manner as SIGINT so that
# this program has a chance to stop the child process.
# Handle SIGTERM by raising a semantic exception which will allow us to
# gracefully unwind and stop the observer
def handle_sigterm(_signum, _frame):
raise KeyboardInterrupt()
# Neuter this handler immediately so we don't raise more than once
signal.signal(signal.SIGTERM, signal.SIG_DFL)
raise ShutdownWatchdog

signal.signal(signal.SIGTERM, handle_sigterm)

Expand All @@ -550,8 +559,12 @@ def handle_sigterm(_signum, _frame):
kill_after=args.kill_after)
handler.start()
observer = Observer(timeout=args.timeout)
observe_with(observer, handler, args.directories, args.recursive)
handler.stop()
try:
observe_with(observer, handler, args.directories, args.recursive)
except ShutdownWatchdog:
pass
finally:
handler.stop()


epilog = """Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>.
Expand Down

0 comments on commit a2767ae

Please sign in to comment.