From 3c6c4e384bb4dca2933a4f22d6f562b1e1676c21 Mon Sep 17 00:00:00 2001 From: patrick Date: Thu, 5 Mar 2026 20:12:17 -0500 Subject: [PATCH] fix(main,reporter): handle SIGTERM gracefully and normalize history file path --- main.py | 23 ++++++++++++++++++----- reporter.py | 6 +++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/main.py b/main.py index 1f213d0..2033de6 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,6 @@ import logging -import time +import signal +import threading try: from dotenv import load_dotenv @@ -26,6 +27,15 @@ def main(): state_file=settings.state_file, node_name=settings.node_name, ) + stop_event = threading.Event() + + def _handle_stop_signal(signum, _frame): + sig_name = signal.Signals(signum).name + logging.info(f"Stop signal received: {sig_name}. Shutting down.") + stop_event.set() + + signal.signal(signal.SIGTERM, _handle_stop_signal) + signal.signal(signal.SIGINT, _handle_stop_signal) print(f"[*] Agent started. Check interval: {settings.check_interval}s") logging.info( @@ -34,7 +44,7 @@ def main(): f"log_path={settings.log_path} state_file={settings.state_file}" ) - while True: + while not stop_event.is_set(): try: is_synced, count, drift = auditor.reconcile() reporter.update_status(is_synced, count) @@ -56,7 +66,7 @@ def main(): f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']})." ) - history_file = reporter.state_file.replace(".json", ".history") + history_file = reporter.get_history_file() if should_heal( history_file, @@ -88,7 +98,7 @@ def main(): logging.info(f"Audit Success: {count} IPs in sync.") print(f"[*] Sleeping for {settings.check_interval} seconds...") - time.sleep(settings.check_interval) + stop_event.wait(settings.check_interval) except KeyboardInterrupt: logging.info("Agent shutting down manually.") @@ -103,7 +113,10 @@ def main(): "Reporter update failed during exception handling: " f"{reporter_error}" ) - time.sleep(60) + if stop_event.wait(60): + break + + logging.info("Agent shutdown complete.") if __name__ == "__main__": diff --git a/reporter.py b/reporter.py index f967022..ea4c1cc 100644 --- a/reporter.py +++ b/reporter.py @@ -42,6 +42,10 @@ class LocalStateReporter: except Exception as e: logging.error(f"Reporter: Failed to write state file: {e}") + def get_history_file(self): + base, _ = os.path.splitext(self.state_file) + return f"{base}.history" + def log_heal_event( self, kernel_count, @@ -56,7 +60,7 @@ class LocalStateReporter: """ Records a specific healing event in a persistent history log. """ - history_file = self.state_file.replace(".json", ".history") + history_file = self.get_history_file() timestamp = datetime.now().isoformat() try: