Skip to content

Commit

Permalink
chg: dev: SDK-299: Handle SIGTERM and other in commands.run() api (#233)
Browse files Browse the repository at this point in the history
Gracefully exit on receiving SIGINT, SIGQUIT and SIGTERM
  • Loading branch information
akaranjkar-qu authored and msumit committed Sep 17, 2018
1 parent 5b1d841 commit 79d7945
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions qds_sdk/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import pipes
import os
import json
import signal

log = logging.getLogger("qds_commands")

Expand Down Expand Up @@ -94,7 +95,14 @@ def run(cls, **kwargs):
print_logs_live = kwargs.pop("print_logs_live", None) # We don't want to send this to the API.

cmd = cls.create(**kwargs)

sighandler = SignalHandler()

while not Command.is_done(cmd.status):
if sighandler.received_term_signal:
logging.warning("Received signal {}. Canceling Qubole Command ID: {}".format(sighandler.last_signal, cmd.id))
cls.cancel(cmd)
exit()
time.sleep(Qubole.poll_interval)
cmd = cls.find(cmd.id)
if print_logs_live is True:
Expand Down Expand Up @@ -1252,6 +1260,23 @@ def parse(cls, args):
v["command_type"] = "DbTapQueryCommand"
return v

class SignalHandler:
"""
Catch terminate signals to allow graceful termination of run()
"""

def __init__(self):
self.last_signal = None
self.received_term_signal = False
self.term_signals = [signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]
for signum in self.term_signals:
signal.signal(signum, self.handler)

def handler(self, signum, frame):
self.last_signal = signum
if signum in self.term_signals:
self.received_term_signal = True

def _read_iteratively(key_instance, fp, delim):
key_instance.open_read()
while True:
Expand Down

0 comments on commit 79d7945

Please sign in to comment.