Skip to content

Commit

Permalink
fix: lock release when there is a python error (#701)
Browse files Browse the repository at this point in the history
Signed-off-by: inimaz <93inigo93@gmail.com>
  • Loading branch information
inimaz authored Nov 4, 2024
1 parent 067e0ec commit 6391b66
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion codecarbon/lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

0 comments on commit 6391b66

Please sign in to comment.