mirror of
https://gitlab.archlinux.org/archlinux/aurweb.git
synced 2025-02-03 10:43:03 +01:00
We were running into data race issues where the `fn.is_file()` check would occur twice before writing the file in the `else` clause. For this reason, a new aurweb.lock.Lock class has been added which doubles as a thread and process lock. We can use this elsewhere in the future, but we are also able to use it to solve this kind of data race issue. That being said, we still need the lock file state to tell us when the first caller acquired the lock. Signed-off-by: Kevin Morris <kevr@0cost.org>
32 lines
837 B
Python
32 lines
837 B
Python
import hashlib
|
|
import os
|
|
|
|
from typing import Callable
|
|
|
|
from posix_ipc import O_CREAT, Semaphore
|
|
|
|
from aurweb import logging
|
|
|
|
logger = logging.get_logger(__name__)
|
|
|
|
|
|
def default_on_create(path):
|
|
logger.info(f"Filelock at {path} acquired.")
|
|
|
|
|
|
class FileLock:
|
|
def __init__(self, tmpdir, name: str):
|
|
self.root = tmpdir
|
|
self.path = str(self.root / name)
|
|
self._file = str(self.root / (f"{name}.1"))
|
|
|
|
def lock(self, on_create: Callable = default_on_create):
|
|
hash = hashlib.sha1(self.path.encode()).hexdigest()
|
|
with Semaphore(f"/{hash}-lock", flags=O_CREAT, initial_value=1):
|
|
retval = os.path.exists(self._file)
|
|
if not retval:
|
|
with open(self._file, "w") as f:
|
|
f.write("1")
|
|
on_create(self.path)
|
|
|
|
return retval
|