RF: _rebindSignal helper to centralize assignment of new signal handlers + minor PEP8ing

pull/1483/head
Yaroslav Halchenko 2016-07-12 22:24:56 -04:00
parent 0dc3db1f43
commit 52cd8a9a96
1 changed files with 14 additions and 10 deletions

View File

@ -87,6 +87,11 @@ class Server:
logSys.debug("Caught signal %d. Flushing logs" % signum) logSys.debug("Caught signal %d. Flushing logs" % signum)
self.flushLogs() self.flushLogs()
def _rebindSignal(self, s, new):
"""Bind new signal handler while storing old one in _prev_signals"""
self.__prev_signals[s] = signal.getsignal(s)
signal.signal(s, new)
def start(self, sock, pidfile, force=False, conf={}): def start(self, sock, pidfile, force=False, conf={}):
# First set the mask to only allow access to owner # First set the mask to only allow access to owner
os.umask(0077) os.umask(0077)
@ -120,9 +125,10 @@ class Server:
# Install signal handlers # Install signal handlers
if _thread_name() == '_MainThread': if _thread_name() == '_MainThread':
for s in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1): for s in (signal.SIGTERM, signal.SIGINT):
self.__prev_signals[s] = signal.getsignal(s) self._rebindSignal(s, self.__sigTERMhandler)
signal.signal(s, self.__sigTERMhandler if s != signal.SIGUSR1 else self.__sigUSR1handler) self._rebindSignal(signal.SIGUSR1, self.__sigUSR1handler)
# Ensure unhandled exceptions are logged # Ensure unhandled exceptions are logged
sys.excepthook = excepthook sys.excepthook = excepthook
@ -501,7 +507,7 @@ class Server:
hdlr.setFormatter(formatter) hdlr.setFormatter(formatter)
logger.addHandler(hdlr) logger.addHandler(hdlr)
# Does not display this message at startup. # Does not display this message at startup.
if not self.__logTarget is None: if self.__logTarget is not None:
logSys.info("Start Fail2ban v%s", version.version) logSys.info("Start Fail2ban v%s", version.version)
logSys.info( logSys.info(
"Changed logging target to %s for Fail2ban v%s" "Changed logging target to %s for Fail2ban v%s"
@ -588,9 +594,7 @@ class Server:
# We need to set this in the parent process, so it gets inherited by the # We need to set this in the parent process, so it gets inherited by the
# child process, and this makes sure that it is effect even if the parent # child process, and this makes sure that it is effect even if the parent
# terminates quickly. # terminates quickly.
for s in (signal.SIGHUP,): self._rebindSignal(signal.SIGHUP, signal.SIG_IGN)
self.__prev_signals[s] = signal.getsignal(s)
signal.signal(s, signal.SIG_IGN)
try: try:
# Fork a child process so the parent can exit. This will return control # Fork a child process so the parent can exit. This will return control