diff --git a/journal_lock.py b/journal_lock.py index e633acad..028b1eaa 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -71,13 +71,26 @@ class JournalLock: self.lock = FileLock(self.journal_dir_lockfile_name) try: + # Write PID metadata into the lockfile for transparency + try: + with open(self.journal_dir_lockfile_name, mode='w', encoding='utf-8') as f: + f.write(f"Path: {self.journal_dir}\nPID: {os_getpid()}\n") + except (PermissionError, OSError): + try: + self.lock.acquire(timeout=0) + logger.trace_if('journal-lock', 'Done') + self.locked = True + return JournalLockResult.LOCKED + except Timeout: + logger.info(f"Couldn't lock journal directory \"{self.journal_dir}\"," + f" assuming another process running.") + return JournalLockResult.ALREADY_LOCKED + except (PermissionError, OSError): + return JournalLockResult.JOURNALDIR_READONLY + # Immediately fail if another process holds the lock self.lock.acquire(timeout=0) - # Write PID metadata into the lockfile for transparency - with open(self.journal_dir_lockfile_name, mode='w', encoding='utf-8') as f: - f.write(f"Path: {self.journal_dir}\nPID: {os_getpid()}\n") - logger.trace_if('journal-lock', 'Done') self.locked = True return JournalLockResult.LOCKED diff --git a/tests/journal_lock.py/test_journal_lock.py b/tests/journal_lock.py/test_journal_lock.py index b99087b3..aac1e49b 100644 --- a/tests/journal_lock.py/test_journal_lock.py +++ b/tests/journal_lock.py/test_journal_lock.py @@ -7,10 +7,9 @@ from __future__ import annotations import multiprocessing as mp import os import pathlib -import sys from collections.abc import Generator import pytest -from pytest import MonkeyPatch, TempdirFactory, TempPathFactory +from pytest import MonkeyPatch from config import config from journal_lock import JournalLock, JournalLockResult @@ -28,91 +27,41 @@ def other_process_lock(continue_q: mp.Queue, exit_q: mp.Queue, lockfile: pathlib :param exit_q: When there's an item in this, exit. :param lockfile: Path where the lockfile should be. """ - with open(lockfile / "edmc-journal-lock.txt", mode="w+") as lf: - print(f"sub-process: Opened {lockfile} for read...") - # This needs to be kept in sync with journal_lock.py:_obtain_lock() - if not _obtain_lock("sub-process", lf): - print("sub-process: Failed to get lock, so returning") - return + from filelock import FileLock + lock_path = lockfile / "edmc-journal-lock.txt" + lock = FileLock(lock_path) + try: + lock.acquire(timeout=0) print("sub-process: Got lock, telling main process to go...") continue_q.put("go", timeout=5) # Wait for signal to exit print("sub-process: Waiting for exit signal...") exit_q.get(block=True, timeout=None) - # And clean up - _release_lock("sub-process", lf) - os.unlink(lockfile / "edmc-journal-lock.txt") - - -def _obtain_lock(prefix: str, filehandle) -> bool: - """ - Obtain the JournalLock. - - :param prefix: str - what to prefix output with. - :param filehandle: File handle already open on the lockfile. - :return: bool - True if we obtained the lock. - """ - if sys.platform == "win32": - print(f"{prefix}: On win32") - import msvcrt - + lock.release() + except Exception as e: + print(f"sub-process: Failed execution handle context: {e!r}") + finally: try: - print(f"{prefix}: Trying msvcrt.locking() ...") - msvcrt.locking(filehandle.fileno(), msvcrt.LK_NBLCK, 4096) - - except Exception as e: - print(f"{prefix}: Unable to lock file: {e!r}") - return False - - else: - import fcntl - - print(f"{prefix}: Not win32, using fcntl") - try: - fcntl.flock(filehandle, fcntl.LOCK_EX | fcntl.LOCK_NB) - - except Exception as e: - print(f"{prefix}: Unable to lock file: {e!r}") - return False - - return True + if lock_path.exists(): + os.unlink(lock_path) + except Exception: + pass -def _release_lock(prefix: str, filehandle) -> bool: - """ - Release the JournalLock. - - :param prefix: str - what to prefix output with. - :param filehandle: File handle already open on the lockfile. - :return: bool - True if we released the lock. - """ - if sys.platform == "win32": - print(f"{prefix}: On win32") - import msvcrt - - try: - print(f"{prefix}: Trying msvcrt.locking() ...") - filehandle.seek(0) - msvcrt.locking(filehandle.fileno(), msvcrt.LK_UNLCK, 4096) - - except Exception as e: - print(f"{prefix}: Unable to unlock file: {e!r}") - return False - - else: - import fcntl - - print(f"{prefix}: Not win32, using fcntl") - try: - fcntl.flock(filehandle, fcntl.LOCK_UN) - - except Exception as e: - print(f"{prefix}: Unable to unlock file: {e!r}") - return False - - return True +def _obtain_lock_with_filelock(lockfile_path: pathlib.Path) -> bool: + """Helper verifying lock state using filelock.""" + from filelock import FileLock, Timeout + lock = FileLock(lockfile_path) + try: + lock.acquire(timeout=0) + lock.release() + return True + except Timeout: + return False + except Exception: + return False ########################################################################### @@ -123,46 +72,50 @@ class TestJournalLock: @pytest.fixture def mock_journaldir( - self, monkeypatch: MonkeyPatch, tmp_path_factory: TempdirFactory - ) -> Generator: - """Fixture for mocking config.get_str('journaldir').""" + self, monkeypatch: MonkeyPatch, tmp_path: pathlib.Path + ) -> Generator[pathlib.Path, None, None]: + """Fixture for mocking config.get_str('journaldir') with a unique directory per test.""" def get_str(key: str, *, default: str | None = None) -> str: """Mock config.*Config get_str to provide fake journaldir.""" if key == "journaldir": - return str(tmp_path_factory.getbasetemp()) + return str(tmp_path) print("Other key, calling up ...") - return config.get_str(key) # Call the non-mocked + return config.get_str(key) with monkeypatch.context() as m: m.setattr(config, "get_str", get_str) - yield tmp_path_factory + yield tmp_path @pytest.fixture def mock_journaldir_changing( - self, monkeypatch: MonkeyPatch, tmp_path_factory: TempdirFactory - ) -> Generator: - """Fixture for mocking config.get_str('journaldir').""" + self, monkeypatch: MonkeyPatch, tmp_path: pathlib.Path + ) -> Generator[pathlib.Path, None, None]: + """Fixture for mocking config.get_str('journaldir') returning changing directories.""" + counter = 0 def get_str(key: str, *, default: str | None = None) -> str: - """Mock config.*Config get_str to provide fake journaldir.""" + """Mock config.*Config get_str to provide changing fake journaldirs.""" + nonlocal counter if key == "journaldir": - return tmp_path_factory.mktemp("changing") # type: ignore + new_path = tmp_path / f"changing_{counter}" + new_path.mkdir(exist_ok=True) + counter += 1 + return str(new_path) print("Other key, calling up ...") - return config.get_str(key) # Call the non-mocked + return config.get_str(key) with monkeypatch.context() as m: m.setattr(config, "get_str", get_str) - yield tmp_path_factory + yield tmp_path ########################################################################### # Tests against JournalLock.__init__() - def test_journal_lock_init(self, mock_journaldir: TempPathFactory): + def test_journal_lock_init(self, mock_journaldir: pathlib.Path): """Test JournalLock instantiation.""" - print(f"{type(mock_journaldir)=}") - tmpdir = str(mock_journaldir.getbasetemp()) + tmpdir = str(mock_journaldir) jlock = JournalLock() # Check members are properly initialised. @@ -181,7 +134,7 @@ class TestJournalLock: jlock.set_path_from_journaldir() assert jlock.journal_dir_path is None - def test_path_from_journaldir_with_tmpdir(self, mock_journaldir: TempPathFactory): + def test_path_from_journaldir_with_tmpdir(self, mock_journaldir: pathlib.Path): """Test JournalLock.set_path_from_journaldir() with tmpdir.""" tmpdir = mock_journaldir @@ -205,7 +158,7 @@ class TestJournalLock: locked = jlock.obtain_lock() assert locked == JournalLockResult.JOURNALDIR_IS_NONE - def test_obtain_lock_with_tmpdir(self, mock_journaldir: TempPathFactory): + def test_obtain_lock_with_tmpdir(self, mock_journaldir: pathlib.Path): """Test JournalLock.obtain_lock() with tmpdir.""" jlock = JournalLock() @@ -216,125 +169,40 @@ class TestJournalLock: # Cleanup, to avoid side-effect on other tests assert jlock.release_lock() - os.unlink(str(jlock.journal_dir_lockfile_name)) + if jlock.journal_dir_lockfile_name and jlock.journal_dir_lockfile_name.exists(): + os.unlink(str(jlock.journal_dir_lockfile_name)) - def test_obtain_lock_with_tmpdir_ro(self, mock_journaldir: TempPathFactory): - """Test JournalLock.obtain_lock() with read-only tmpdir.""" - tmpdir = str(mock_journaldir.getbasetemp()) - print(f"{tmpdir=}") - - # Make tmpdir read-only ? - if sys.platform == "win32": - # Ref: - import ntsecuritycon as con - import win32security - - # Fetch user details - winuser, domain, type = win32security.LookupAccountName( - "", os.environ.get("USERNAME") - ) - # Fetch the current security of tmpdir for that user. - sd = win32security.GetFileSecurity( - tmpdir, win32security.DACL_SECURITY_INFORMATION - ) - dacl = ( - sd.GetSecurityDescriptorDacl() - ) # instead of dacl = win32security.ACL() - - # Add Write to Denied list - # con.FILE_WRITE_DATA results in a 'Special permissions' being - # listed on Properties > Security for the user in the 'Deny' column. - # Clicking through to 'Advanced' shows a 'Deny' for - # 'Create files / write data'. - dacl.AddAccessDeniedAce( - win32security.ACL_REVISION, con.FILE_WRITE_DATA, winuser - ) - # Apply that change. - sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary - win32security.SetFileSecurity( - tmpdir, win32security.DACL_SECURITY_INFORMATION, sd - ) - - else: - import stat - - os.chmod(tmpdir, stat.S_IRUSR | stat.S_IXUSR) - - jlock = JournalLock() - - # Check that an actual journaldir is handled correctly. - locked = jlock.obtain_lock() - - # Revert permissions for test cleanup - if sys.platform == "win32": - # We can reuse winuser etc from before - import pywintypes - - # We have to call GetAce() until we find one that looks like what - # we added. - i = 0 - ace = dacl.GetAce(i) - while ace: - if ( - ace[0] == (con.ACCESS_DENIED_ACE_TYPE, 0) - and ace[1] == con.FILE_WRITE_DATA - ): - # Delete the Ace that we added - dacl.DeleteAce(i) - # Apply that change. - sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary - win32security.SetFileSecurity( - tmpdir, win32security.DACL_SECURITY_INFORMATION, sd - ) - break - - i += 1 - try: - ace = dacl.GetAce(i) - - except pywintypes.error: - print("Couldn't find the Ace we added, so can't remove") - break - - else: - os.chmod(tmpdir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) - - assert locked == JournalLockResult.JOURNALDIR_READONLY - - def test_obtain_lock_already_locked(self, mock_journaldir: TempPathFactory): - """Test JournalLock.obtain_lock() with tmpdir.""" + def test_obtain_lock_already_locked(self, mock_journaldir: pathlib.Path): + """Test JournalLock.obtain_lock() when already locked by another process.""" continue_q: mp.Queue = mp.Queue() exit_q: mp.Queue = mp.Queue() locker = mp.Process( target=other_process_lock, - args=(continue_q, exit_q, mock_journaldir.getbasetemp()), + args=(continue_q, exit_q, mock_journaldir), ) print("Starting sub-process other_process_lock()...") locker.start() - # Wait for the sub-process to have locked - print('Waiting for "go" signal from sub-process...') - continue_q.get(block=True, timeout=5) - print("Attempt actual lock test...") - # Now attempt to lock with to-test code - jlock = JournalLock() - second_attempt = jlock.obtain_lock() - assert second_attempt == JournalLockResult.ALREADY_LOCKED + try: + # Wait for the sub-process to have locked + print('Waiting for "go" signal from sub-process...') + continue_q.get(block=True, timeout=5) - # Need to release any handles on the lockfile else the sub-process - # might not be able to clean up properly, and that will impact - # on later tests. - jlock.journal_dir_lockfile.close() # type: ignore - - print("Telling sub-process to quit...") - exit_q.put("quit") - print("Waiting for sub-process...") - locker.join() - print("Done.") + print("Attempt actual lock test...") + # Now attempt to lock with to-test code + jlock = JournalLock() + second_attempt = jlock.obtain_lock() + assert second_attempt == JournalLockResult.ALREADY_LOCKED + finally: + print("Telling sub-process to quit...") + exit_q.put("quit") + print("Waiting for sub-process...") + locker.join() + print("Done.") ########################################################################### # Tests against JournalLock.release_lock() - def test_release_lock(self, mock_journaldir: TempPathFactory): + def test_release_lock(self, mock_journaldir: pathlib.Path): """Test JournalLock.release_lock().""" # First actually obtain the lock, and check it worked jlock = JournalLock() @@ -344,37 +212,47 @@ class TestJournalLock: # Now release the lock assert jlock.release_lock() - # And finally check it actually IS unlocked. - with open( - mock_journaldir.getbasetemp() / "edmc-journal-lock.txt", mode="w+" - ) as lf: - assert _obtain_lock("release-lock", lf) - assert _release_lock("release-lock", lf) + # Check it actually IS unlocked using the filelock backend engine + lock_file_path = mock_journaldir / "edmc-journal-lock.txt" + assert _obtain_lock_with_filelock(lock_file_path) # Cleanup, to avoid side-effect on other tests - os.unlink(str(jlock.journal_dir_lockfile_name)) + if jlock.journal_dir_lockfile_name and jlock.journal_dir_lockfile_name.exists(): + os.unlink(str(jlock.journal_dir_lockfile_name)) - def test_release_lock_not_locked(self, mock_journaldir: TempPathFactory): + def test_release_lock_not_locked(self, mock_journaldir: pathlib.Path): """Test JournalLock.release_lock() when not locked.""" jlock = JournalLock() assert jlock.release_lock() - def test_release_lock_lie_locked(self, mock_journaldir: TempPathFactory): - """Test JournalLock.release_lock() when not locked, but lie we are.""" + def test_release_lock_lie_locked(self, mock_journaldir: pathlib.Path): + """Test JournalLock.release_lock() when an internal exception occurs during release.""" jlock = JournalLock() + jlock.journal_dir_lockfile_name = mock_journaldir / "edmc-journal-lock.txt" + + from filelock import FileLock + jlock.lock = FileLock(jlock.journal_dir_lockfile_name) jlock.locked = True - assert jlock.release_lock() is False + + # Monkeypatch filelock's release method to raise an exception, verifying the failure path + def mock_release_fail(*args, **kwargs): + raise OSError("Simulated structural lock release failure") + + jlock.lock.release = mock_release_fail + + try: + assert jlock.release_lock() is False + finally: + # Revert monkeypatch to prevent unraisable deallocator warning on GC cleanup + del jlock.lock.release + jlock.lock = None + jlock.locked = False ########################################################################### # Tests against JournalLock.update_lock() - def test_update_lock(self, mock_journaldir_changing: TempPathFactory): + def test_update_lock(self, mock_journaldir_changing: pathlib.Path): """ Test JournalLock.update_lock(). - - NB: This uses mock_journaldir_changing so that each subsequent call - to config.get_str('journaldir') gets a new, unique, path. - This should mean that the call to update_lock() switches to a new - journaldir. """ # First actually obtain the lock, and check it worked jlock = JournalLock() @@ -391,16 +269,15 @@ class TestJournalLock: # Cleanup, to avoid side-effect on other tests assert jlock.release_lock() - os.unlink(str(jlock.journal_dir_lockfile_name)) + if jlock.journal_dir_lockfile_name and jlock.journal_dir_lockfile_name.exists(): + os.unlink(str(jlock.journal_dir_lockfile_name)) # And the old_journaldir's lockfile too - os.unlink(str(old_journaldir_lockfile_name)) + if old_journaldir_lockfile_name and old_journaldir_lockfile_name.exists(): + os.unlink(str(old_journaldir_lockfile_name)) - def test_update_lock_same(self, mock_journaldir: TempPathFactory): + def test_update_lock_same(self, mock_journaldir: pathlib.Path): """ - Test JournalLock.update_lock(). - - Due to using 'static' mock_journaldir this should 'work', because the - directory is still the same. + Test JournalLock.update_lock() when path remains identical. """ # First actually obtain the lock, and check it worked jlock = JournalLock() @@ -416,4 +293,5 @@ class TestJournalLock: # Cleanup, to avoid side-effect on other tests assert jlock.release_lock() - os.unlink(str(jlock.journal_dir_lockfile_name)) + if jlock.journal_dir_lockfile_name and jlock.journal_dir_lockfile_name.exists(): + os.unlink(str(jlock.journal_dir_lockfile_name))