0

I am sending SIGTERM signal to my server via start-stop-daemon. As expected the server shuts down when signal is received. Now I want to halt my server for 10 sec after receiving SIGTERM and then shut it down. To achieve this I wrote

def sigterm_handler(signum):
    time.sleep(10)
    sys.exit(0)    

Class server(object):
    .
    .

    def __call__()
        signal.signal(signal.SIGTERM, sigterm_handler)
        #some code

    .
    .

Now the server never waits for 10 secs after receiving signal. As soon as the signal is send, it shuts down (checked in loggers).

Also the following message halts for 10 secs on my terminal.

* Stopping Server:

I think my code is not able to tell python that the signal is being handled and so, the default handler is also being called along with my handler. Any idea what needs to be done?

akipro
  • 188
  • 1
  • 2
  • 11

1 Answers1

1

The problem is your sigterm_handler. It blocks your server as soon as it recieves the SIGTERM for 10s and then shut it down.

What you really want is "ignoring" the signal and then exit the server after 10s (for example with another signal):

shutdown_mode=False

def alarm_handler(signum, frame):
        sys.exit(0)

def sigterm_handler(signum):
     global shutdown_mode
     if not shutdown_mode:
            shutdown_mode=True
            signal.signal(signal.SIGALRM, alarm_handler)
            signal.alarm(10)

You want also switch into a "shutdown mode", where e.g. the server should not accept new connections etc.

jofel
  • 3,297
  • 17
  • 31
  • Thanks it worked. Regarding the "shutdown mode", the code seems to stop working as soon as I introduced it (corrected the "shutdownMode" ,"shutdown_mode" typo). Even making a log of shutdown_mode at the beginning of sigterm_handler stopped the functionality. – akipro Jan 08 '16 at 12:33
  • @akipro Thanks. "shutdown_mode" did not work as its `global` declaration was missing. It should work now. – jofel Jan 08 '16 at 12:39
  • ahhh... should have noticed that. Thanks again. – akipro Jan 08 '16 at 12:42
  • hey, it seems that doing any other operation in sigterm_handler other than setting alarm, like setting shutdown_mode or any other variable, the server again stops immediately. – akipro Jan 08 '16 at 13:00
  • For debugging, run the server inside a shell. Probably, you get an python error. For me, e.g. setting variables work. – jofel Jan 08 '16 at 13:04