"""Concurrency locking using non-blocking fcntl.flock on a PID file.""" import fcntl import os from typing import Optional from linux_backuper.core.constants import DEFAULT_PID_PATH class LockAcquisitionError(RuntimeError): """Raised when another instance of linux-backuper is already executing.""" pass class SingleInstanceLock: """Ensures single-process execution using kernel-level file locks.""" def __init__(self, pid_path: str = DEFAULT_PID_PATH): self.pid_path = pid_path self._fd: Optional[int] = None def acquire(self) -> bool: """Acquire exclusive non-blocking lock. Raises LockAcquisitionError on conflict.""" parent_dir = os.path.dirname(self.pid_path) if parent_dir: try: os.makedirs(parent_dir, exist_ok=True) except OSError: pass try: self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600) except PermissionError: if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1": import tempfile self.pid_path = os.path.join(tempfile.gettempdir(), f"linux-backuper-{os.getpid()}.pid") self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600) else: raise try: fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB) os.ftruncate(self._fd, 0) os.write(self._fd, f"{os.getpid()}\n".encode("utf-8")) return True except (BlockingIOError, OSError) as e: if self._fd is not None: try: os.close(self._fd) except OSError: pass self._fd = None raise LockAcquisitionError( f"Another linux-backuper instance is already running (locked on {self.pid_path}): {e}" ) def release(self) -> None: """Release the file lock and remove the PID file.""" if self._fd is not None: try: fcntl.flock(self._fd, fcntl.LOCK_UN) os.close(self._fd) except OSError: pass self._fd = None if os.path.isfile(self.pid_path): try: os.unlink(self.pid_path) except OSError: pass def __enter__(self) -> "SingleInstanceLock": self.acquire() return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: self.release()