From 6391b66c7947b06d48e485b99da32816390c865d Mon Sep 17 00:00:00 2001 From: inimaz <49730431+inimaz@users.noreply.github.com> Date: Mon, 4 Nov 2024 09:48:18 +0100 Subject: [PATCH] fix: lock release when there is a python error (#701) Signed-off-by: inimaz <93inigo93@gmail.com> --- codecarbon/lock.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/codecarbon/lock.py b/codecarbon/lock.py index 8fd86ddbc..edfbf3c0f 100644 --- a/codecarbon/lock.py +++ b/codecarbon/lock.py @@ -4,8 +4,10 @@ If the lock file already exists, it exits the program. """ +import atexit import errno import os +import signal import tempfile from codecarbon.external.logger import logger @@ -20,6 +22,19 @@ class Lock: def __init__(self): self._has_created_lock = False + atexit.register( + self.release + ) # Ensure release() is called on unexpected exit of the user's python code + # Register signal handlers to ensure lock release on interruption + signal.signal(signal.SIGINT, self._handle_exit) # Ctrl+C + signal.signal(signal.SIGTERM, self._handle_exit) # Termination signal + + def _handle_exit(self, signum, frame): + """Ensures the lock file is removed when the script is interrupted.""" + logger.debug(f"Signal {signum} received. Releasing lock and exiting.") + self.release() + os._exit(1) # Exit immediately to prevent further execution + def acquire(self): """Creates a lock file and ensures it's the only instance running.""" # Attempt to create the lock file @@ -41,6 +56,6 @@ def release(self): if self._has_created_lock: os.remove(LOCKFILE) except OSError as e: - logger.error("Error:", e) + logger.debug(f"Error: {e}") if e.errno != errno.ENOENT: raise