feat(profiles): implement slice 3 profile system, flock concurrency, and sanitize archiver
This commit is contained in:
1 parent
66ca179937
commit
646bd9d145
8 files changed
+536
-69
No files matched your search
@@ -0,0 +1,76 @@
|
||||
"""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()
|
||||
Reference in new issue
Block a user