Skip to content

Commit

Permalink
Correctly handle SIGHUP when using the reload option (#376)
Browse files Browse the repository at this point in the history
* don't shutdown on reload (SIGHUP)

* apply review suggestions

* Minor code refactor

---------

Co-authored-by: Giovanni Barillari <[email protected]>
  • Loading branch information
hendrikmuhs and gi0baro authored Aug 13, 2024
1 parent 0d87c2f commit 88811b3
Showing 1 changed file with 25 additions and 15 deletions.
40 changes: 25 additions & 15 deletions granian/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,14 @@ def shutdown(self, exit_code=0):
if exit_code:
sys.exit(exit_code)

def _reload(self, sock, spawn_target, target_loader):
logger.info('HUP signal received, gracefully respawning workers..')
workers = list(range(self.workers))
self.reload_signal = False
self.respawned_procs.clear()
self.main_loop_interrupt.clear()
self._respawn_workers(workers, sock, spawn_target, target_loader, delay=self.respawn_interval)

def _serve_loop(self, sock, spawn_target, target_loader):
while True:
self.main_loop_interrupt.wait()
Expand All @@ -560,12 +568,7 @@ def _serve_loop(self, sock, spawn_target, target_loader):
self._respawn_workers(workers, sock, spawn_target, target_loader)

if self.reload_signal:
logger.info('HUP signal received, gracefully respawning workers..')
workers = list(range(self.workers))
self.reload_signal = False
self.respawned_procs.clear()
self.main_loop_interrupt.clear()
self._respawn_workers(workers, sock, spawn_target, target_loader, delay=self.respawn_interval)
self._reload(sock, spawn_target, target_loader)

def _serve(self, spawn_target, target_loader):
sock = self.startup(spawn_target, target_loader)
Expand All @@ -580,15 +583,22 @@ def _serve_with_reloader(self, spawn_target, target_loader):
reload_path = Path.cwd()
sock = self.startup(spawn_target, target_loader)

try:
for changes in watchfiles.watch(reload_path, stop_event=self.main_loop_interrupt):
logger.info('Changes detected, reloading workers..')
for change, file in changes:
logger.info(f'{change.raw_str().capitalize()}: {file}')
self._stop_workers()
self._spawn_workers(sock, spawn_target, target_loader)
except StopIteration:
pass
serve_loop = True
while serve_loop:
try:
for changes in watchfiles.watch(reload_path, stop_event=self.main_loop_interrupt):
logger.info('Changes detected, reloading workers..')
for change, file in changes:
logger.info(f'{change.raw_str().capitalize()}: {file}')
self._stop_workers()
self._spawn_workers(sock, spawn_target, target_loader)
except StopIteration:
pass

if self.reload_signal:
self._reload(sock, spawn_target, target_loader)
else:
serve_loop = False

self.shutdown()

Expand Down

0 comments on commit 88811b3

Please sign in to comment.