33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
"""One root-owned lock shared by image cutover and rollback."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import fcntl
|
|
import os
|
|
import stat
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
LOCK_FILE = Path("/run/akyldash-deploy.lock")
|
|
|
|
|
|
@contextmanager
|
|
def deployment_lock():
|
|
descriptor = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
|
try:
|
|
info = os.fstat(descriptor)
|
|
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o600:
|
|
raise ValueError("deployment lock must be a regular mode-0600 file")
|
|
if os.geteuid() == 0 and info.st_uid != 0:
|
|
raise ValueError("deployment lock must be root-owned")
|
|
try:
|
|
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError as error:
|
|
raise ValueError("another deployment or rollback holds the shared lock") from error
|
|
try:
|
|
yield
|
|
finally:
|
|
fcntl.flock(descriptor, fcntl.LOCK_UN)
|
|
finally:
|
|
os.close(descriptor)
|