Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changelog/1029.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
On POSIX, if a full filesystem prevents :class:`~filelock.SoftFileLock` from removing a failed marker, cleanup tries
to leave a one-byte record. On filesystems with atomic exchange, a later caller can reclaim it once space is available.
3 changes: 3 additions & 0 deletions docs/how-to.rst
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,9 @@ them unchanged for two seconds. An empty marker, which is all a ``SoftFileLock``
this way; remove a leftover one with ``break_lock()``.
That recovery path is not fail closed.

If a POSIX filesystem fills during acquisition, cleanup tries to leave a one-byte marker when it cannot remove the
failed record. Free space so the next caller can reclaim the marker on filesystems that support atomic exchange.

A contender breaks a stale marker without the lock path ever standing empty. Where it cannot (NFS, SMB and platforms
without an atomic exchange, other than Windows) it leaves the marker in place; see :ref:`concepts:How does stale lock
detection work across platforms?` for the details.
Expand Down
14 changes: 10 additions & 4 deletions src/filelock/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import sys
import time
from contextlib import contextmanager, suppress
from errno import EACCES, EINVAL, EIO, EISDIR, ENOSYS, EXDEV
from errno import EACCES, EINVAL, EIO, EISDIR, ENOSPC, ENOSYS, EXDEV
from functools import cache
from pathlib import Path
from typing import TYPE_CHECKING, Final, cast
Expand Down Expand Up @@ -119,9 +119,15 @@ def remove_own_file(lock_file: str, fd: int) -> None: # pragma: win32 no cover
# :raises OSError: if the descriptor cannot be read or the unlink fails.
own: Final[os.stat_result] = os.fstat(fd)
with suppress(FileNotFoundError):
break_lock_file(lock_file, own.st_mtime, own.st_ino)
if os.path.samestat(os.lstat(lock_file), own):
Path(lock_file).unlink()
try:
break_lock_file(lock_file, own.st_mtime, own.st_ino)
if os.path.samestat(os.lstat(lock_file), own):
Path(lock_file).unlink()
except OSError as exc:
if exc.errno == ENOSPC:
# A sparse byte makes our failed marker reclaimable without allocating a data block.
os.ftruncate(fd, 1)
raise


def break_lock_file(lock_file: str, mtime_before: float, ino_before: int) -> None:
Expand Down
43 changes: 43 additions & 0 deletions tests/test_soft_stale.py
Original file line number Diff line number Diff line change
Expand Up @@ -1530,6 +1530,49 @@ def test_write_failure_rolls_back_acquire(lock_path: Path, mocker: MockerFixture
assert not lock_path.exists()


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX rolls back before closing the descriptor")
@NEEDS_STALE_RECLAIM
@pytest.mark.usefixtures("unchanged_past_grace")
@pytest.mark.parametrize(
("cleanup_errno", "fail_unlink", "record"),
[
pytest.param(ENOSPC, False, b"\0", id="create-full"),
pytest.param(ENOSPC, True, b"\0", id="unlink-full"),
pytest.param(EIO, False, b"", id="io-error"),
],
)
def test_rollback_on_full_filesystem(
lock_path: Path, mocker: MockerFixture, cleanup_errno: int, record: bytes, *, fail_unlink: bool
) -> None: # pragma: win32 no cover
open_file = os.open

def open_with_full_directory(path: str, flags: int, mode: int = 0o777) -> int:
if not fail_unlink and ".break." in path:
raise OSError(cleanup_errno, os.strerror(cleanup_errno))
return open_file(path, flags, mode)

unlink = Path.unlink

def unlink_on_full_filesystem(path: Path, *, missing_ok: bool = False) -> None:
if fail_unlink and path == lock_path:
raise OSError(ENOSPC, os.strerror(ENOSPC))
unlink(path, missing_ok=missing_ok)

unlinks = mocker.patch.object(Path, "unlink", side_effect=unlink_on_full_filesystem, autospec=True)
opens = mocker.patch("filelock._util.os.open", side_effect=open_with_full_directory, autospec=True)
writes = mocker.patch("filelock._util.os.write", side_effect=OSError(ENOSPC, "record write failed"), autospec=True)
with pytest.raises(OSError, match="record write failed"):
SoftFileLock(lock_path).acquire(timeout=0)
mocker.stop(opens)
mocker.stop(writes)
mocker.stop(unlinks)
assert lock_path.read_bytes() == record
lock = SoftFileLock(lock_path)
acquire_after_reclaim(lock)
assert lock.is_locked == (cleanup_errno == ENOSPC)
lock.release()


def _hold_reports_foreign_identity(mocker: MockerFixture) -> None:
# Make the held descriptor report a different inode than the file on disk, as if a peer replaced the marker at the
# path. fstat runs only on our own lock fd, so nothing else in acquire or release is disturbed.
Expand Down
Loading