Skip to content
This repository has been archived by the owner on Jul 22, 2023. It is now read-only.

Detect kill signal and log it. #79

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion arenaclient/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import aiohttp
import psutil
from .match.matches import MatchSourceFactory, MatchSource
from .utl import Utl
from .utl import Utl, KillSignalDetector
from .match.result import Result


Expand Down Expand Up @@ -265,6 +265,8 @@ async def main(self, match: MatchSource.Match):
bot2_process = None
pids = []
try:
kill_signal_detector = KillSignalDetector() # for exiting gracefully when terminated

self._ws, self._session = await connect(address=self.address, headers=self.headers)

if await self.connected():
Expand Down Expand Up @@ -442,6 +444,11 @@ async def main(self, match: MatchSource.Match):
pass

if not result.has_result():
# todo: implemented now simply to log for testing.
# todo: if this works, don't submit the result.
if kill_signal_detector.signal_received:
self._utl.printout(f"{kill_signal_detector.signal_name} signal received.")

result.parse_result(init_error(match))
self._utl.pid_cleanup(pids)
return result
Expand Down
32 changes: 32 additions & 0 deletions arenaclient/utl.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,35 @@ def clean_dir(self, directory):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)


# How to process SIGTERM signal gracefully?
# https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully
import signal
import time


class KillSignalDetector:
signal_received = False
signal_name = "none"

def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully_sigint)
signal.signal(signal.SIGTERM, self.exit_gracefully_sigterm)

def exit_gracefully_sigint(self, *args):
self.signal_name = "SIGINT"
self.signal_received = True

def exit_gracefully_sigterm(self, *args):
self.signal_name = "SIGTERM"
self.signal_received = True


# if __name__ == '__main__':
# killer = GracefulKiller()
# while not killer.kill_now:
# time.sleep(1)
# print("doing something in a loop ...")
#
# print("End of the program. I was killed gracefully :)")