"""OS-owned execution locks: a crashed worker cannot leave a live file lock.""" from contextlib import contextmanager import errno import os from pathlib import Path import re @contextmanager def execution_lock(database, job_key): if not re.fullmatch(r'[0-9a-f]{64}', job_key): raise ValueError('Invalid execution lock key') directory = Path(database).resolve().parent / (Path(database).name + '.bid-locks') directory.mkdir(parents=True, exist_ok=True) # Never unlink lock files: replacing an inode could admit a second worker. with (directory / (job_key + '.lock')).open('a+b') as handle: handle.seek(0, 2) if handle.tell() == 0: handle.write(b'0') handle.flush() handle.seek(0) try: if os.name == 'nt': import msvcrt msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as exc: if exc.errno not in {errno.EACCES, errno.EAGAIN, errno.EDEADLK}: raise yield False return try: yield True finally: handle.seek(0) if os.name == 'nt': msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) else: fcntl.flock(handle.fileno(), fcntl.LOCK_UN)