Skip to content

Commit

Permalink
enhanced signal handler
Browse files Browse the repository at this point in the history
  • Loading branch information
palto42 committed Oct 14, 2020
1 parent 6d90c2c commit 38c07f2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 21 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"IWRITE",
"RFEs",
"SIGKILL",
"SIGUSR",
"Xferd",
"cmds",
"datefmt",
Expand Down
41 changes: 20 additions & 21 deletions rguard
Original file line number Diff line number Diff line change
Expand Up @@ -310,24 +310,32 @@ class ConditionChecker:
class GracefulDeath:
"""Catch signals to allow graceful shutdown."""

def __init__(self):
self.receivedSignal = self.receivedTermSignal = False
def __init__(self, rguard):
self.rguard = rguard
catchSignals = [
1,
2,
3,
10,
12,
15,
signal.SIGHUP,
signal.SIGINT,
signal.SIGQUIT,
signal.SIGUSR1,
signal.SIGUSR2,
signal.SIGTERM,
]
for signum in catchSignals:
signal.signal(signum, self.handler)

def handler(self, signum, frame):
self.lastSignal = signum
self.receivedSignal = True
if signum in [2, 3, 15]:
self.receivedTermSignal = True
if signum in [
signal.SIGINT,
signal.SIGQUIT,
signal.SIGTERM,
]:
logging.warning(f"Gracefully exiting due to receipt of signal {signum}")
self.rguard.guard(enforce=False)
sys.exit()
else:
logging.warning(f"Ignoring signal {signum}")


class CustomFormatter(argparse.RawDescriptionHelpFormatter):
Expand Down Expand Up @@ -531,7 +539,6 @@ def parse_args():

def main():
"""Parse args, check conditions, install reboot-guard, setup infinite loop."""
sighandler = GracefulDeath()
opts = parse_args()
if opts.timestamps:
logging.basicConfig(
Expand Down Expand Up @@ -567,6 +574,8 @@ def main():
)
# Initialize reboot-guard
r = RebootGuard()
# Initialize signal handler
_ = GracefulDeath(r)
# Run initial check
if c.check_conditions():
if opts.exit_on_pass:
Expand All @@ -576,16 +585,6 @@ def main():
r.guard(enforce=True)
# Run forever-loop
while True:
if sighandler.receivedSignal:
if sighandler.receivedTermSignal and not opts.ignore_signals:
logging.warning(
f"Gracefully exiting due to receipt of signal {sighandler.lastSignal}"
)
r.guard(enforce=False)
sys.exit()
else:
logging.warning(f"Ignoring signal {sighandler.lastSignal}")
sighandler.receivedSignal = sighandler.receivedTermSignal = False
time.sleep(opts.interval)
if c.check_conditions():
r.guard(enforce=False)
Expand Down

0 comments on commit 38c07f2

Please sign in to comment.