Skip to content

Commit

Permalink
Add SIGTERM handling to geographic gatherer
Browse files Browse the repository at this point in the history
  • Loading branch information
lahtinep committed Nov 12, 2024
1 parent acc2631 commit b4c1c48
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pytroll_collectors/geographic_gatherer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"""Geographic segment gathering."""

import logging
import signal
import time

from configparser import NoOptionError, ConfigParser
Expand Down Expand Up @@ -56,6 +57,8 @@ def __init__(self, opts):
self.triggers = []
self.return_status = 0

self._sigterm_caught = False

self._clean_config()
self._setup_publisher()
try:
Expand Down Expand Up @@ -103,8 +106,10 @@ def _setup_triggers(self):

def run(self):
"""Run granule triggers."""
signal.signal(signal.SIGTERM, self._handle_sigterm)
try:
while True:
self._check_sigterm()
time.sleep(1)
for trigger in self.triggers:
if not trigger.is_alive():
Expand All @@ -119,6 +124,18 @@ def run(self):

return self.return_status

def _handle_sigterm(self, signum, frame):
logger.info("Caught SIGTERM, shutting down when all collections are finished.")
self._sigterm_caught = True

def _check_sigterm(self):
if self._sigterm_caught:
for t in self.triggers:
for c in t.collectors:
if c.granules:
return
raise KeyboardInterrupt("No ongoing collections.")

def stop(self):
"""Stop the gatherer."""
logger.info('Ending publication the gathering of granules...')
Expand Down
24 changes: 24 additions & 0 deletions pytroll_collectors/tests/test_geographic_gatherer.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,27 @@ def test_full_pass(self, sub_factory, monkeypatch, tmp_tle):
assert snd_msg.data == expected_msg.data
finally:
gatherer.stop()


def test_sigterm(tmp_config_file, tmp_config_parser):
"""Test that SIGTERM signal is handled."""
import os
import signal
import time
from multiprocessing import Process

from pytroll_collectors.geographic_gatherer import GeographicGatherer

with open(tmp_config_file, mode="w") as fp:
tmp_config_parser.write(fp)

opts = arg_parse(["-c", "minimal_config", "-p", "40000", "-n", "false", "-i", "localhost:12345",
str(tmp_config_file)])
gatherer = GeographicGatherer(opts)
proc = Process(target=gatherer.run)
proc.start()
time.sleep(1)
os.kill(proc.pid, signal.SIGTERM)
proc.join()

assert proc.exitcode == 0

0 comments on commit b4c1c48

Please sign in to comment.