| 1 |
"""Verify that filelock holds mutual exclusion on a target filesystem, and exit non-zero when it does not. |
| 2 |
|
| 3 |
Point it at a directory on the filesystem under test (an NFS or SMB mount, say) and it runs a mutual-exclusion check: |
| 4 |
several processes each take the lock a fixed number of times and record the wall-clock interval they spend holding it. |
| 5 |
A correct lock never lets two holders overlap and lets every process finish its holds, so intervals never intersect and |
| 6 |
the completed count matches the expected total. Run with ``python tasks/verify_filesystem.py [directory]``. |
| 7 |
|
| 8 |
Overlap detection rather than a shared counter is deliberate. A lost-update counter conflates lock exclusion with data |
| 9 |
cache coherence: two independent NFS client caches can lose an update to a counter even under a perfectly exclusive |
| 10 |
lock, because a read-modify-write reads a stale cached copy. Each process here only returns its own intervals (no shared |
| 11 |
mutable state read across caches), so the check measures the lock and nothing else. CLOCK_MONOTONIC is system-wide on |
| 12 |
one host, so intervals from sibling processes are directly comparable. |
| 13 |
|
| 14 |
The contention is deliberately moderate and dispersed so the result is deterministic: a small process count, a short |
| 15 |
hold, and a randomized gap between holds keep any contender from being starved out, and the genuinely transient NFS |
| 16 |
errors (a stale handle or a momentary permission race under concurrent create and unlink, which robust NFS clients |
| 17 |
retry) are retried rather than treated as failures. A correct lock then finishes every hold on every run. |
| 18 |
|
| 19 |
Every lock type is always run and printed, so the output records the real behavior of each on the filesystem. |
| 20 |
FILELOCK_VERIFY_LOCKS narrows only which lock types failing turns the exit code non-zero: a filesystem where a type is |
| 21 |
known-unsupported (the strict claim over SMB) still reports its result without failing the gate. |
| 22 |
""" |
| 23 |
|
| 24 |
from __future__ import annotations |
| 25 |
|
| 26 |
import os |
| 27 |
import random |
| 28 |
import sys |
| 29 |
import time |
| 30 |
from concurrent.futures import ProcessPoolExecutor |
| 31 |
from errno import EACCES, ENOENT, ESTALE |
| 32 |
from pathlib import Path |
| 33 |
from tempfile import TemporaryDirectory |
| 34 |
from typing import TYPE_CHECKING, Final |
| 35 |
|
| 36 |
from filelock import FileLock, SoftFileLock, StrictSoftFileLock |
| 37 |
|
| 38 |
if TYPE_CHECKING: |
| 39 |
from collections.abc import Callable |
| 40 |
|
| 41 |
_PROCESSES: Final[int] = 4 |
| 42 |
_HOLDS: Final[int] = 100 |
| 43 |
_ACQUIRE_TIMEOUT: Final[float] = 60.0 |
| 44 |
_HOLD_SECONDS: Final[float] = 0.004 |
| 45 |
_GAP_MAX_SECONDS: Final[float] = 0.008 |
| 46 |
_TRANSIENT_RETRIES: Final[int] = 16 |
| 47 |
_RETRY_BACKOFF: Final[float] = 0.01 |
| 48 |
_TRANSIENT_ERRNOS: Final[frozenset[int]] = frozenset({EACCES, ENOENT, ESTALE}) |
| 49 |
_ALL_LOCKS: Final[tuple[str, ...]] = ("FileLock", "SoftFileLock", "StrictSoftFileLock") |
| 50 |
|
| 51 |
|
| 52 |
def main() -> int: |
| 53 |
# Each argument is a mount of the same filesystem. Two independent mounts (an NFS export mounted twice with |
| 54 |
# nosharecache, say) are two client caches over one server, so contending across them is a genuine multi-client |
| 55 |
# check, not two views of one cache. With no arguments a temporary directory checks the local single-mount case. |
| 56 |
if mounts := [Path(argument) for argument in sys.argv[1:]]: |
| 57 |
for mount in mounts: |
| 58 |
mount.mkdir(parents=True, exist_ok=True) |
| 59 |
return _verify_across(mounts) |
| 60 |
with TemporaryDirectory(prefix="filelock-verify-") as directory: |
| 61 |
return _verify_across([Path(directory)]) |
| 62 |
|
| 63 |
|
| 64 |
def _verify_across(mounts: list[Path]) -> int: |
| 65 |
where = str(mounts[0]) if len(mounts) == 1 else f"{len(mounts)} mounts of {mounts[0]} .. {mounts[-1]}" |
| 66 |
print(f"verifying mutual exclusion across {where} ({_PROCESSES} processes x {_HOLDS} holds)") |
| 67 |
gated = _gated_locks() |
| 68 |
failures = 0 |
| 69 |
for name in _ALL_LOCKS: |
| 70 |
counts, overlaps, reason = _run_one(name, mounts) |
| 71 |
expected = _PROCESSES * _HOLDS |
| 72 |
# A correct lock never overlaps, finishes every hold, and raises no error the retries could not clear. |
| 73 |
ok = overlaps == 0 and sum(counts) == expected and reason is None |
| 74 |
failures += (not ok) and name in gated |
| 75 |
note = "" if name in gated else " (ungated)" |
| 76 |
tail = f"{note}{f' {reason}' if reason else ''}" |
| 77 |
stats = f"held={sum(counts)}/{expected} overlaps={overlaps}" |
| 78 |
print(f" {name:20} {'PASS' if ok else 'FAIL'} {stats}{tail}") |
| 79 |
return 1 if failures else 0 |
| 80 |
|
| 81 |
|
| 82 |
def _gated_locks() -> frozenset[str]: |
| 83 |
if not (requested := os.environ.get("FILELOCK_VERIFY_LOCKS")): |
| 84 |
return frozenset(_ALL_LOCKS) |
| 85 |
return frozenset(requested.split(",")) |
| 86 |
|
| 87 |
|
| 88 |
def _run_one(name: str, mounts: list[Path]) -> tuple[list[int], int, str | None]: |
| 89 |
# Same basename on every mount, so the mounts contend on one server file through their independent caches. |
| 90 |
lock_paths = [str(mounts[index % len(mounts)] / f"{name}.lock") for index in range(_PROCESSES)] |
| 91 |
with ProcessPoolExecutor(max_workers=_PROCESSES) as pool: |
| 92 |
results = list(pool.map(_hammer, [name] * _PROCESSES, lock_paths)) |
| 93 |
counts = [len(intervals) for intervals, _ in results] |
| 94 |
reason = next((reason for _, reason in results if reason is not None), None) |
| 95 |
return counts, _count_overlaps([intervals for intervals, _ in results]), reason |
| 96 |
|
| 97 |
|
| 98 |
def _count_overlaps(per_process: list[list[tuple[float, float]]]) -> int: |
| 99 |
# Sweep the intervals in start order: a hold that begins before the latest end seen so far, and belongs to another |
| 100 |
# process, means two holders were inside the lock at once. A correct lock hands off strictly, so nothing overlaps. |
| 101 |
intervals = sorted((enter, leave, owner) for owner, held in enumerate(per_process) for enter, leave in held) |
| 102 |
overlaps = 0 |
| 103 |
latest_leave = float("-inf") |
| 104 |
latest_owner = -1 |
| 105 |
for enter, leave, owner in intervals: |
| 106 |
if enter < latest_leave and owner != latest_owner: |
| 107 |
overlaps += 1 |
| 108 |
if leave > latest_leave: |
| 109 |
latest_leave, latest_owner = leave, owner |
| 110 |
return overlaps |
| 111 |
|
| 112 |
|
| 113 |
def _hammer(name: str, lock_path: str) -> tuple[list[tuple[float, float]], str | None]: |
| 114 |
lock = _build(name, lock_path) |
| 115 |
intervals: list[tuple[float, float]] = [] |
| 116 |
for _ in range(_HOLDS): |
| 117 |
if (reason := _resiliently(lambda: lock.acquire(timeout=_ACQUIRE_TIMEOUT))) is not None: |
| 118 |
return intervals, reason |
| 119 |
enter = time.monotonic() |
| 120 |
# Hold briefly so a broken lock lets a second holder in during an observable window; a correct lock serializes |
| 121 |
# the holds regardless. enter is stamped after acquire and leave before release, so a correct hand-off can never |
| 122 |
# look like an overlap even though release and the next acquire race. |
| 123 |
time.sleep(_HOLD_SECONDS) |
| 124 |
leave = time.monotonic() |
| 125 |
if (reason := _resiliently(lock.release)) is not None: |
| 126 |
intervals.append((enter, leave)) |
| 127 |
return intervals, reason |
| 128 |
intervals.append((enter, leave)) |
| 129 |
# A randomized gap outside the lock breaks the lock-step herd, so a poll-based lock hands off fairly and no |
| 130 |
# contender is starved out of finishing its holds. |
| 131 |
time.sleep(random.uniform(0, _GAP_MAX_SECONDS)) # ruff:ignore[suspicious-non-cryptographic-random-usage] - test dispersion, not cryptographic |
| 132 |
return intervals, None |
| 133 |
|
| 134 |
|
| 135 |
def _resiliently(action: Callable[[], object]) -> str | None: |
| 136 |
# Retry the genuinely transient NFS errors (a stale handle, a create/unlink permission race under contention) that |
| 137 |
# a robust client retries, so one hiccup never aborts a hold. A Timeout from starvation or a rejection the |
| 138 |
# filesystem always makes (EINVAL for the strict claim on CIFS) is not transient and ends this process's run. |
| 139 |
for attempt in range(_TRANSIENT_RETRIES): |
| 140 |
if (error := _attempt(action)) is None: |
| 141 |
return None |
| 142 |
if not _has_transient(error) or attempt == _TRANSIENT_RETRIES - 1: |
| 143 |
return _describe(error) |
| 144 |
time.sleep(_RETRY_BACKOFF * (attempt + 1)) |
| 145 |
return "transient errors exhausted retries" |
| 146 |
|
| 147 |
|
| 148 |
def _attempt(action: Callable[[], object]) -> BaseException | None: |
| 149 |
try: |
| 150 |
action() |
| 151 |
except Exception as error: # ruff:ignore[blind-except] - the caller classifies transient versus terminal; a harness must not die |
| 152 |
return error |
| 153 |
return None |
| 154 |
|
| 155 |
|
| 156 |
def _has_transient(error: BaseException) -> bool: |
| 157 |
# An ExceptionGroup (the strict claim wraps its cleanup failures in one) exposes leaves via ``exceptions``; recurse |
| 158 |
# rather than name BaseExceptionGroup, which is not a builtin on the 3.10 floor this script is linted against. |
| 159 |
if (leaves := getattr(error, "exceptions", None)) is not None: |
| 160 |
return any(_has_transient(leaf) for leaf in leaves) |
| 161 |
return isinstance(error, OSError) and not isinstance(error, TimeoutError) and error.errno in _TRANSIENT_ERRNOS |
| 162 |
|
| 163 |
|
| 164 |
def _describe(error: BaseException) -> str: |
| 165 |
return f"{type(error).__name__}: {error}"[:160] |
| 166 |
|
| 167 |
|
| 168 |
def _build(name: str, lock_path: str) -> FileLock | SoftFileLock | StrictSoftFileLock: |
| 169 |
if name == "FileLock": |
| 170 |
return FileLock(lock_path) |
| 171 |
if name == "SoftFileLock": |
| 172 |
return SoftFileLock(lock_path) |
| 173 |
return StrictSoftFileLock(lock_path) |
| 174 |
|
| 175 |
|
| 176 |
if __name__ == "__main__": |
| 177 |
raise SystemExit(main()) |