diff --git a/pyproject.toml b/pyproject.toml index 5dd6f9c..9124b11 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pickmix" -version = "0.6.0" +version = "0.6.1" description = "Multi-kind particle picking GUI for cryo-ET sub-tomogram averaging workflows." readme = "README.md" authors = [ diff --git a/src/pickmix/gui/app.py b/src/pickmix/gui/app.py index 40a6c64..41fc50a 100644 --- a/src/pickmix/gui/app.py +++ b/src/pickmix/gui/app.py @@ -32,7 +32,7 @@ def apply() -> None: for widget in (top, *top.findChildren(QWidget)): app.style().unpolish(widget) app.style().polish(widget) - widget.update() + QWidget.update(widget) # item views override update() to take an index retint(top) window.project_tab.welcome.update_theme_button() QTimer.singleShot(1, apply) diff --git a/src/pickmix/lock.py b/src/pickmix/lock.py index 84fb643..eba2cdc 100644 --- a/src/pickmix/lock.py +++ b/src/pickmix/lock.py @@ -3,53 +3,58 @@ ''' # Import external dependencies -import os, socket, sys, time +import atexit, os, re, signal, socket, sys, threading, time from pathlib import Path -from typing import IO, Self - -# fcntl: Unix only so None on Windows -try: - import fcntl -except ImportError: - fcntl = None +from typing import Self # LOCK_NAME: lockfile in out_dir LOCK_NAME: str = '.pickmix.lock' +# BEAT_SECONDS: how often the holder touches the lockfile +BEAT_SECONDS: float = 30.0 + +# STALE_SECONDS: lockfile untouched this long means its holder was killed (4x BEAT_SECONDS to allow for clock skew and filesystem lag) +STALE_SECONDS: float = 120.0 + # ProjectBusy: another pickmix process has project open class ProjectBusy(Exception): pass -# ProjectLock: exclusive advisory lock on project, held until release or process ends, however it ends +# ProjectLock: lockfile made with O_EXCL and touched by a heartbeat thread while held, so a killed holder (SIGKILL, OOM) goes stale, and removed on release/normal exit/SIGTERM/SIGHUP class ProjectLock: # __init__: take lock or raise ProjectBusy naming holder def __init__(self, out_dir: Path, what: str) -> None: out_dir.mkdir(parents=True, exist_ok=True) self.path = out_dir / LOCK_NAME - # False when nothing can be locked, so project is open but unprotected - self.protected = fcntl is not None - self._handle: IO[str] | None = open(self.path, 'a+') - if fcntl is not None: + self._text = f'{what} (pid {os.getpid()} on {socket.gethostname()}, since {time.strftime("%Y-%m-%d %H:%M")})' + self._held = False + # second pass only after clearing a stale file + for _ in range(2): try: - fcntl.flock(self._handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - self._handle.close() - self._handle = None - raise ProjectBusy(f'{str(out_dir)!r} is in use by {self._holder()}; close it first') from None - except OSError: - self.protected = False - if not self.protected: - print('[pickmix] lock files are not supported on Windows, so do not open the GUI and candidate-search on one project at once', file=sys.stderr) - self._handle.seek(0) - self._handle.truncate() - self._handle.write(f'{what} (pid {os.getpid()} on {socket.gethostname()}, since {time.strftime("%Y-%m-%d %H:%M")})') - self._handle.flush() + fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + if self._stale(): + self.path.unlink(missing_ok=True) + continue + raise ProjectBusy(f'{str(out_dir)!r} is in use by {self._holder()}; close it first, or delete {str(self.path)!r} if that process is gone') from None + with os.fdopen(fd, 'w') as handle: + handle.write(self._text) + self._held = True + break + else: + raise ProjectBusy(f'{str(out_dir)!r} could not be locked; delete {str(self.path)!r} if no pickmix process is using it') + self._stop = threading.Event() + threading.Thread(target=self._beat, daemon=True).start() + atexit.register(self.release) + _exit_on_signals() - # release: let go of lock + # release: let go of lock, removing file only if it is still this processes def release(self) -> None: - if self._handle is not None: - self._handle.close() - self._handle = None + if self._held: + self._held = False + self._stop.set() + if self._holder() == self._text: + self.path.unlink(missing_ok=True) # __enter__, __exit__: hold lock for a with block def __enter__(self) -> Self: @@ -64,3 +69,39 @@ def _holder(self) -> str: return self.path.read_text().strip() or 'another pickmix process' except OSError: return 'another pickmix process' + + # _beat: touch lockfile until released + def _beat(self) -> None: + while not self._stop.wait(BEAT_SECONDS): + try: + os.utime(self.path) + except OSError: + pass + + # _stale: holder is a dead process or has not touched the lockfile for STALE_SECONDS + def _stale(self) -> bool: + try: + if time.time() - self.path.stat().st_mtime > STALE_SECONDS: + return True + except OSError: + return False + found = re.search(r'pid (\d+) on (\S+),', self._holder()) + # another host's pid cannot be checked, so only the age counts + if found is None or found[2] != socket.gethostname(): + return False + try: + os.kill(int(found[1]), 0) + except ProcessLookupError: + return True + except OSError: + pass + return False + +# _exit_on_signals: turn SIGTERM and SIGHUP into a normal exit so locks are released, leaving any handler already set alone +def _exit_on_signals() -> None: + if threading.current_thread() is not threading.main_thread(): + return + for name in ('SIGTERM', 'SIGHUP'): + number = getattr(signal, name, None) + if number is not None and signal.getsignal(number) == signal.SIG_DFL: + signal.signal(number, lambda *_: sys.exit(1)) diff --git a/tests/test_lock.py b/tests/test_lock.py index 9e194ce..0548432 100644 --- a/tests/test_lock.py +++ b/tests/test_lock.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import pytest +import os, pytest, socket, time from pathlib import Path # Import internal pickmix objects @@ -13,7 +13,6 @@ class TestProjectLock: # test_second_holder_is_refused: a held lock refuses another and names the holder def test_second_holder_is_refused(self, tmp_path: Path) -> None: with ProjectLock(tmp_path / 'out', 'GUI') as first: - assert first.protected with pytest.raises(ProjectBusy, match=r'GUI \(pid \d+ on '): ProjectLock(tmp_path / 'out', 'candidate-search') @@ -24,9 +23,36 @@ def test_release_frees_it(self, tmp_path: Path) -> None: lock.release() ProjectLock(tmp_path, 'GUI').release() - # test_no_fcntl_warns_and_opens: without fcntl (Windows) the project opens unprotected, with a warning on stderr - def test_no_fcntl_warns_and_opens(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: - monkeypatch.setattr('pickmix.lock.fcntl', None) - with ProjectLock(tmp_path, 'GUI') as first, ProjectLock(tmp_path, 'candidate-search') as second: - assert not first.protected and not second.protected - assert 'lock files are not supported' in capsys.readouterr().err + # test_dead_local_holder_is_replaced: a lockfile left by a dead process on this host is taken over + def test_dead_local_holder_is_replaced(self, tmp_path: Path) -> None: + (tmp_path / '.pickmix.lock').write_text(f'GUI (pid 2147483646 on {socket.gethostname()}, since 2020-01-01 00:00)') + ProjectLock(tmp_path, 'candidate-search').release() + assert not (tmp_path / '.pickmix.lock').exists() + + # test_other_host_holder_is_respected: a fresh lockfile from another host is respected and the error says how to clear it + def test_other_host_holder_is_respected(self, tmp_path: Path) -> None: + (tmp_path / '.pickmix.lock').write_text('candidate-search (pid 1 on elsewhere, since 2020-01-01 00:00)') + with pytest.raises(ProjectBusy, match='elsewhere.*delete'): + ProjectLock(tmp_path, 'GUI') + + # test_release_leaves_foreign_file: release does not delete a lockfile that another process has since written + def test_release_leaves_foreign_file(self, tmp_path: Path) -> None: + lock = ProjectLock(tmp_path, 'GUI') + lock.path.write_text('candidate-search (pid 1 on elsewhere, since 2020-01-01 00:00)') + lock.release() + assert lock.path.exists() + + # test_silent_other_host_holder_is_replaced: a lockfile from another host that has stopped being touched is taken over + def test_silent_other_host_holder_is_replaced(self, tmp_path: Path) -> None: + old = tmp_path / '.pickmix.lock' + old.write_text('candidate-search (pid 1 on elsewhere, since 2020-01-01 00:00)') + os.utime(old, (0, 0)) + ProjectLock(tmp_path, 'GUI').release() + + # test_held_lock_is_touched: the holder keeps touching the lockfile so it never looks stale + def test_held_lock_is_touched(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr('pickmix.lock.BEAT_SECONDS', 0.05) + with ProjectLock(tmp_path, 'GUI') as lock: + os.utime(lock.path, (0, 0)) + time.sleep(0.3) + assert lock.path.stat().st_mtime > 1 diff --git a/uv.lock b/uv.lock index afe5d8f..9c99745 100644 --- a/uv.lock +++ b/uv.lock @@ -137,7 +137,7 @@ wheels = [ [[package]] name = "pickmix" -version = "0.6.0" +version = "0.6.1" source = { editable = "." } dependencies = [ { name = "imageio" },