Files

87 lines
2.9 KiB
Python

import os
from pathlib import Path
from typing import Optional
class InstanceLock:
def __init__(self, lock_path: Optional[Path] = None) -> None:
self.custom_path = lock_path is not None
self.lock_path = lock_path or Path("/var/run/linux-updater.pid")
self.fd: Optional[int] = None
self.acquired: bool = False
def acquire(self) -> bool:
"""Attempts to acquire exclusive advisory flock. Returns False if already locked."""
try:
import fcntl
except ImportError:
# Non-Unix environment fallback
self.acquired = True
return True
# Ensure parent directory exists or fallback to /tmp
try:
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
self.fd = os.open(str(self.lock_path), os.O_RDWR | os.O_CREAT, 0o644)
except (PermissionError, OSError):
if not self.custom_path:
uid = os.getuid() if hasattr(os, "getuid") else 0
self.lock_path = Path(f"/tmp/linux-updater-{uid}.pid")
try:
self.fd = os.open(str(self.lock_path), os.O_RDWR | os.O_CREAT, 0o644)
except Exception:
self.acquired = True
return True
else:
return False
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"))
try:
os.fsync(self.fd)
except Exception:
pass
self.acquired = True
return True
except (BlockingIOError, IOError, OSError):
self.acquired = False
return False
def get_holder_pid(self) -> Optional[int]:
try:
if self.lock_path.exists():
content = self.lock_path.read_text(encoding="utf-8").strip()
if content and content.isdigit():
return int(content)
except Exception:
pass
return None
def release(self) -> None:
if self.fd is not None and self.acquired:
try:
import fcntl
fcntl.flock(self.fd, fcntl.LOCK_UN)
os.close(self.fd)
except Exception:
pass
self.fd = None
self.acquired = False
try:
if self.lock_path.exists():
self.lock_path.unlink()
except Exception:
pass
def __enter__(self) -> "InstanceLock":
if not self.acquire():
holder = self.get_holder_pid()
holder_msg = f" (PID {holder})" if holder else ""
raise RuntimeError(f"Another instance of linux-updater is already running{holder_msg}.")
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.release()