| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import gc |
| 5 |
import os |
| 6 |
import subprocess # ruff:ignore[suspicious-subprocess-import] # fresh interpreter must register the callback before importing filelock |
| 7 |
import sys |
| 8 |
import threading |
| 9 |
from errno import EBADF |
| 10 |
from queue import Queue |
| 11 |
from typing import TYPE_CHECKING, Final, Literal, NoReturn |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
from filelock import ( |
| 16 |
AcquireReturnProxy, |
| 17 |
AsyncFileLock, |
| 18 |
AsyncSoftFileLock, |
| 19 |
BaseAsyncFileLock, |
| 20 |
BaseFileLock, |
| 21 |
FileLock, |
| 22 |
SoftFileLock, |
| 23 |
SoftReadWriteLock, |
| 24 |
Timeout, |
| 25 |
) |
| 26 |
from tests.capability_marks import NEEDS_FORK, NEEDS_REGISTER_AT_FORK |
| 27 |
from tests.fork_helpers import exit_child, fork_process |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from pathlib import Path |
| 31 |
|
| 32 |
from pytest_mock import MockerFixture |
| 33 |
|
| 34 |
_FORK_WARNING: Final[pytest.MarkDecorator] = pytest.mark.filterwarnings( |
| 35 |
"ignore:.*multi-threaded, use of fork.*:DeprecationWarning" |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
@NEEDS_FORK # pragma: needs fork |
| 40 |
@_FORK_WARNING |
| 41 |
@pytest.mark.parametrize( |
| 42 |
("lock_type", "action"), |
| 43 |
[ |
| 44 |
pytest.param(FileLock, "release", id="native-release"), |
| 45 |
pytest.param(FileLock, "context", id="native-context"), |
| 46 |
pytest.param(FileLock, "collect", id="native-collect"), |
| 47 |
pytest.param(SoftFileLock, "release", id="soft-release"), |
| 48 |
pytest.param(SoftFileLock, "context", id="soft-context"), |
| 49 |
pytest.param(SoftFileLock, "collect", id="soft-collect"), |
| 50 |
], |
| 51 |
) |
| 52 |
def test_child_cleanup_preserves_parent_lock( |
| 53 |
tmp_path: Path, |
| 54 |
lock_type: type[BaseFileLock], |
| 55 |
action: Literal["release", "context", "collect"], |
| 56 |
) -> None: |
| 57 |
path = str(tmp_path / "parent.lock") |
| 58 |
lock = lock_type(path, thread_local=False, is_singleton=False) |
| 59 |
proxy = lock.acquire() |
| 60 |
|
| 61 |
def cleanup_child() -> NoReturn: |
| 62 |
_run_child_cleanup(lock, proxy, action) |
| 63 |
|
| 64 |
child_pid = fork_process(cleanup_child) |
| 65 |
_, status = os.waitpid(child_pid, 0) |
| 66 |
|
| 67 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 68 |
assert not _probe_lock(lock_type, path) |
| 69 |
lock.release() |
| 70 |
assert _probe_lock(lock_type, path) |
| 71 |
|
| 72 |
|
| 73 |
@NEEDS_FORK # pragma: needs fork |
| 74 |
@_FORK_WARNING |
| 75 |
@pytest.mark.parametrize( |
| 76 |
("async_lock_type", "sync_lock_type"), |
| 77 |
[ |
| 78 |
pytest.param(AsyncFileLock, FileLock, id="native"), |
| 79 |
pytest.param(AsyncSoftFileLock, SoftFileLock, id="soft"), |
| 80 |
], |
| 81 |
) |
| 82 |
def test_async_child_release_preserves_parent_lock( |
| 83 |
tmp_path: Path, |
| 84 |
async_lock_type: type[BaseAsyncFileLock], |
| 85 |
sync_lock_type: type[BaseFileLock], |
| 86 |
) -> None: |
| 87 |
path = str(tmp_path / "parent.lock") |
| 88 |
lock = async_lock_type(path, thread_local=False, is_singleton=False) |
| 89 |
asyncio.run(lock.acquire()) |
| 90 |
|
| 91 |
def release_child() -> NoReturn: |
| 92 |
state = lock.is_locked, lock.lock_counter |
| 93 |
asyncio.run(lock.release(force=True)) |
| 94 |
exit_child(0 if state == (False, 0) else 1) |
| 95 |
|
| 96 |
child_pid = fork_process(release_child) |
| 97 |
_, status = os.waitpid(child_pid, 0) |
| 98 |
|
| 99 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 100 |
assert not _probe_lock(sync_lock_type, path) |
| 101 |
asyncio.run(lock.release()) |
| 102 |
assert _probe_lock(sync_lock_type, path) |
| 103 |
|
| 104 |
|
| 105 |
@pytest.mark.requires_hard_links |
| 106 |
@NEEDS_FORK # pragma: needs fork |
| 107 |
@_FORK_WARNING |
| 108 |
def test_soft_read_write_resets_older_same_path_instance(tmp_path: Path) -> None: # pragma: needs hard-link |
| 109 |
path = str(tmp_path / "parent.lock") |
| 110 |
older = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5) |
| 111 |
newer = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5) |
| 112 |
del newer |
| 113 |
gc.collect() |
| 114 |
older.acquire_write() |
| 115 |
|
| 116 |
def inherited_child() -> NoReturn: |
| 117 |
with pytest.raises(RuntimeError, match="invalidated by fork"): |
| 118 |
older.acquire_read(timeout=0) |
| 119 |
older.release() |
| 120 |
exit_child(0) |
| 121 |
|
| 122 |
child_pid = fork_process(inherited_child) |
| 123 |
_, status = os.waitpid(child_pid, 0) |
| 124 |
|
| 125 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 126 |
contender = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5) |
| 127 |
with pytest.raises(Timeout): |
| 128 |
contender.acquire_write(timeout=0) |
| 129 |
contender.close() |
| 130 |
older.release() |
| 131 |
older.close() |
| 132 |
|
| 133 |
|
| 134 |
@NEEDS_FORK # pragma: needs fork |
| 135 |
@_FORK_WARNING |
| 136 |
def test_child_closes_descriptor_held_by_vanished_thread(tmp_path: Path) -> None: |
| 137 |
path = str(tmp_path / "parent.lock") |
| 138 |
descriptor: Queue[int] = Queue() |
| 139 |
acquired, release = threading.Event(), threading.Event() |
| 140 |
|
| 141 |
def hold_lock() -> None: |
| 142 |
lock = FileLock(path, thread_local=True, is_singleton=False, on_acquired=descriptor.put) |
| 143 |
with lock: |
| 144 |
acquired.set() |
| 145 |
release.wait() |
| 146 |
|
| 147 |
worker = threading.Thread(target=hold_lock) |
| 148 |
worker.start() |
| 149 |
assert acquired.wait(timeout=5) |
| 150 |
fd = descriptor.get(timeout=5) |
| 151 |
|
| 152 |
def descriptor_child() -> NoReturn: |
| 153 |
_assert_descriptor_closed(fd) |
| 154 |
|
| 155 |
child_pid = fork_process(descriptor_child) |
| 156 |
_, status = os.waitpid(child_pid, 0) |
| 157 |
release.set() |
| 158 |
worker.join(timeout=5) |
| 159 |
|
| 160 |
assert (os.waitstatus_to_exitcode(status), worker.is_alive()) == (0, False) |
| 161 |
|
| 162 |
|
| 163 |
@NEEDS_FORK # pragma: needs fork |
| 164 |
@_FORK_WARNING |
| 165 |
def test_fork_waits_for_descriptor_registration(tmp_path: Path, mocker: MockerFixture) -> None: |
| 166 |
path = str(tmp_path / "parent.lock") |
| 167 |
lock = FileLock(path, thread_local=False, is_singleton=False) |
| 168 |
entered, proceed, acquired = threading.Event(), threading.Event(), threading.Event() |
| 169 |
descriptors: list[int] = [] |
| 170 |
real_fstat = os.fstat |
| 171 |
|
| 172 |
def delayed_fstat(fd: int) -> os.stat_result: |
| 173 |
if threading.current_thread() is worker and not entered.is_set(): |
| 174 |
descriptors.append(fd) |
| 175 |
entered.set() |
| 176 |
proceed.wait() |
| 177 |
return real_fstat(fd) |
| 178 |
|
| 179 |
mocker.patch("os.fstat", side_effect=delayed_fstat) |
| 180 |
|
| 181 |
def acquire_lock() -> None: |
| 182 |
lock.acquire() |
| 183 |
acquired.set() |
| 184 |
|
| 185 |
worker = threading.Thread(target=acquire_lock) |
| 186 |
worker.start() |
| 187 |
assert entered.wait(timeout=5) |
| 188 |
timer = threading.Timer(0.05, proceed.set) |
| 189 |
timer.start() |
| 190 |
|
| 191 |
def descriptor_child() -> NoReturn: |
| 192 |
_assert_descriptor_closed(descriptors[0]) |
| 193 |
|
| 194 |
child_pid = fork_process(descriptor_child) |
| 195 |
_, status = os.waitpid(child_pid, 0) |
| 196 |
timer.join(timeout=5) |
| 197 |
worker.join(timeout=5) |
| 198 |
|
| 199 |
assert (os.waitstatus_to_exitcode(status), acquired.is_set(), worker.is_alive()) == (0, True, False) |
| 200 |
lock.release() |
| 201 |
|
| 202 |
|
| 203 |
@NEEDS_REGISTER_AT_FORK |
| 204 |
def test_unrelated_acquisitions_reach_filesystem_boundary_concurrently( # pragma: needs fork |
| 205 |
tmp_path: Path, mocker: MockerFixture |
| 206 |
) -> None: |
| 207 |
boundary = threading.Barrier(3, timeout=5) |
| 208 |
real_fstat = os.fstat |
| 209 |
|
| 210 |
def wait_at_boundary(fd: int) -> os.stat_result: |
| 211 |
# Only the two named workers stat while the patch is installed, so the guard never takes its false arc. |
| 212 |
if threading.current_thread().name.startswith("concurrent-acquire-"): # pragma: no branch |
| 213 |
boundary.wait() |
| 214 |
return real_fstat(fd) |
| 215 |
|
| 216 |
mocker.patch("os.fstat", side_effect=wait_at_boundary) |
| 217 |
|
| 218 |
def acquire_lock(path: str) -> None: |
| 219 |
with FileLock(path, is_singleton=False): |
| 220 |
pass |
| 221 |
|
| 222 |
workers = [ |
| 223 |
threading.Thread( |
| 224 |
target=acquire_lock, |
| 225 |
args=(str(tmp_path / f"{index}.lock"),), |
| 226 |
name=f"concurrent-acquire-{index}", |
| 227 |
) |
| 228 |
for index in range(2) |
| 229 |
] |
| 230 |
for worker in workers: |
| 231 |
worker.start() |
| 232 |
try: |
| 233 |
boundary.wait() |
| 234 |
finally: |
| 235 |
for worker in workers: |
| 236 |
worker.join(timeout=5) |
| 237 |
|
| 238 |
assert [worker.is_alive() for worker in workers] == [False, False] |
| 239 |
|
| 240 |
|
| 241 |
@NEEDS_FORK # pragma: needs fork |
| 242 |
@_FORK_WARNING |
| 243 |
@pytest.mark.parametrize("lock_type", [pytest.param(FileLock, id="native"), pytest.param(SoftFileLock, id="soft")]) |
| 244 |
def test_child_singleton_registry_drops_parent_instance(tmp_path: Path, lock_type: type[BaseFileLock]) -> None: |
| 245 |
path = str(tmp_path / "parent.lock") |
| 246 |
parent_lock = lock_type(path, is_singleton=True) |
| 247 |
|
| 248 |
def singleton_child() -> NoReturn: |
| 249 |
child_lock = lock_type(path, is_singleton=True) |
| 250 |
exit_child(0 if child_lock is not parent_lock else 1) |
| 251 |
|
| 252 |
child_pid = fork_process(singleton_child) |
| 253 |
_, status = os.waitpid(child_pid, 0) |
| 254 |
|
| 255 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 256 |
|
| 257 |
|
| 258 |
@NEEDS_FORK # pragma: needs fork |
| 259 |
@_FORK_WARNING |
| 260 |
@pytest.mark.parametrize("lock_type", [pytest.param(FileLock, id="native"), pytest.param(SoftFileLock, id="soft")]) |
| 261 |
def test_inherited_idle_lock_rejects_acquire(tmp_path: Path, lock_type: type[BaseFileLock]) -> None: |
| 262 |
lock = lock_type(str(tmp_path / "parent.lock"), is_singleton=False) |
| 263 |
|
| 264 |
def inherited_child() -> NoReturn: |
| 265 |
try: |
| 266 |
lock.acquire(timeout=0) |
| 267 |
except RuntimeError as exception: |
| 268 |
exit_child(0 if "inherited across fork" in str(exception) else 1) |
| 269 |
exit_child(1) |
| 270 |
|
| 271 |
child_pid = fork_process(inherited_child) |
| 272 |
_, status = os.waitpid(child_pid, 0) |
| 273 |
|
| 274 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 275 |
|
| 276 |
|
| 277 |
@NEEDS_FORK # pragma: needs fork |
| 278 |
@_FORK_WARNING |
| 279 |
@pytest.mark.parametrize( |
| 280 |
"lock_type", [pytest.param(AsyncFileLock, id="native"), pytest.param(AsyncSoftFileLock, id="soft")] |
| 281 |
) |
| 282 |
def test_inherited_idle_async_lock_rejects_acquire(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None: |
| 283 |
lock = lock_type(str(tmp_path / "parent.lock"), is_singleton=False) |
| 284 |
|
| 285 |
def inherited_child() -> NoReturn: |
| 286 |
try: |
| 287 |
asyncio.run(lock.acquire(timeout=0)) |
| 288 |
except RuntimeError as exception: |
| 289 |
exit_child(0 if "inherited across fork" in str(exception) else 1) |
| 290 |
exit_child(1) |
| 291 |
|
| 292 |
child_pid = fork_process(inherited_child) |
| 293 |
_, status = os.waitpid(child_pid, 0) |
| 294 |
|
| 295 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 296 |
|
| 297 |
|
| 298 |
@NEEDS_FORK # pragma: needs fork |
| 299 |
@_FORK_WARNING |
| 300 |
def test_fork_from_on_acquired_invalidates_child_acquire(tmp_path: Path) -> None: |
| 301 |
path = str(tmp_path / "parent.lock") |
| 302 |
fork_result = -1 |
| 303 |
lock: FileLock |
| 304 |
|
| 305 |
def inherited_child() -> NoReturn: |
| 306 |
try: |
| 307 |
lock.acquire(timeout=0) |
| 308 |
except RuntimeError as exception: |
| 309 |
exit_child(0 if "inherited across fork" in str(exception) else 1) |
| 310 |
exit_child(1) |
| 311 |
|
| 312 |
def fork_from_hook(_fd: int) -> None: |
| 313 |
nonlocal fork_result |
| 314 |
fork_result = fork_process(inherited_child) |
| 315 |
|
| 316 |
lock = FileLock(path, thread_local=False, is_singleton=False, on_acquired=fork_from_hook) |
| 317 |
lock.acquire() |
| 318 |
_, status = os.waitpid(fork_result, 0) |
| 319 |
assert (os.waitstatus_to_exitcode(status), _probe_lock(FileLock, path)) == (0, False) |
| 320 |
lock.release() |
| 321 |
|
| 322 |
|
| 323 |
@NEEDS_FORK # pragma: needs fork |
| 324 |
@_FORK_WARNING |
| 325 |
def test_child_callback_registered_before_filelock_can_acquire(tmp_path: Path) -> None: |
| 326 |
script = """ |
| 327 |
import os |
| 328 |
import sys |
| 329 |
|
| 330 |
parent_path, child_path = sys.argv[1:] |
| 331 |
callback_succeeded = False |
| 332 |
|
| 333 |
def acquire_in_early_child_callback() -> None: |
| 334 |
global callback_succeeded |
| 335 |
with FileLock(child_path, is_singleton=False): |
| 336 |
pass |
| 337 |
callback_succeeded = True |
| 338 |
|
| 339 |
os.register_at_fork(after_in_child=acquire_in_early_child_callback) |
| 340 |
|
| 341 |
from filelock import FileLock, Timeout |
| 342 |
|
| 343 |
parent = FileLock(parent_path, is_singleton=False) |
| 344 |
parent.acquire() |
| 345 |
child_pid = os.fork() |
| 346 |
if child_pid == 0: |
| 347 |
os._exit(0 if callback_succeeded else 3) |
| 348 |
_, status = os.waitpid(child_pid, 0) |
| 349 |
if os.waitstatus_to_exitcode(status) != 0: |
| 350 |
sys.exit(1) |
| 351 |
|
| 352 |
contender = FileLock(parent_path, is_singleton=False) |
| 353 |
try: |
| 354 |
contender.acquire(timeout=0) |
| 355 |
except Timeout: |
| 356 |
pass |
| 357 |
else: |
| 358 |
sys.exit(2) |
| 359 |
parent.release() |
| 360 |
""" |
| 361 |
result = subprocess.run( |
| 362 |
[sys.executable, "-c", script, str(tmp_path / "parent.lock"), str(tmp_path / "child.lock")], |
| 363 |
check=False, |
| 364 |
capture_output=True, |
| 365 |
text=True, |
| 366 |
timeout=10, |
| 367 |
) |
| 368 |
|
| 369 |
assert (result.returncode, result.stderr) == (0, "") |
| 370 |
|
| 371 |
|
| 372 |
@NEEDS_FORK # pragma: needs fork |
| 373 |
@_FORK_WARNING |
| 374 |
@pytest.mark.parametrize( |
| 375 |
"kind", |
| 376 |
[ |
| 377 |
pytest.param("native", id="native"), |
| 378 |
pytest.param("soft", id="soft"), |
| 379 |
pytest.param("soft-rw", id="soft-read-write"), |
| 380 |
], |
| 381 |
) |
| 382 |
@pytest.mark.requires_hard_links |
| 383 |
def test_child_interpreter_exit_preserves_parent_lock( |
| 384 |
tmp_path: Path, kind: Literal["native", "soft", "soft-rw"] |
| 385 |
) -> None: # pragma: needs hard-link |
| 386 |
script = """ |
| 387 |
from __future__ import annotations |
| 388 |
|
| 389 |
import os |
| 390 |
import sys |
| 391 |
|
| 392 |
from filelock import BaseFileLock, FileLock, SoftFileLock, SoftReadWriteLock, Timeout |
| 393 |
|
| 394 |
def acquire(lock: BaseFileLock | SoftReadWriteLock, timeout: float = -1) -> None: |
| 395 |
if isinstance(lock, SoftReadWriteLock): |
| 396 |
lock.acquire_write(timeout=timeout) |
| 397 |
else: |
| 398 |
lock.acquire(timeout=timeout) |
| 399 |
|
| 400 |
def release(lock: BaseFileLock | SoftReadWriteLock) -> None: |
| 401 |
if isinstance(lock, SoftReadWriteLock): |
| 402 |
lock.release() |
| 403 |
lock.close() |
| 404 |
else: |
| 405 |
lock.release() |
| 406 |
|
| 407 |
kind, path = sys.argv[1:] |
| 408 |
lock: BaseFileLock | SoftReadWriteLock |
| 409 |
if kind == "soft-rw": |
| 410 |
lock = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=30) |
| 411 |
elif kind == "soft": |
| 412 |
lock = SoftFileLock(path, is_singleton=False) |
| 413 |
else: |
| 414 |
lock = FileLock(path, is_singleton=False) |
| 415 |
acquire(lock) |
| 416 |
|
| 417 |
child_pid = os.fork() |
| 418 |
if child_pid == 0: |
| 419 |
sys.exit(0) |
| 420 |
_, status = os.waitpid(child_pid, 0) |
| 421 |
if os.waitstatus_to_exitcode(status) != 0: |
| 422 |
sys.exit(1) |
| 423 |
|
| 424 |
contender_pid = os.fork() |
| 425 |
if contender_pid == 0: |
| 426 |
contender: BaseFileLock | SoftReadWriteLock |
| 427 |
if kind == "soft-rw": |
| 428 |
contender = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=30) |
| 429 |
elif kind == "soft": |
| 430 |
contender = SoftFileLock(path, is_singleton=False) |
| 431 |
else: |
| 432 |
contender = FileLock(path, is_singleton=False) |
| 433 |
try: |
| 434 |
acquire(contender, timeout=0) |
| 435 |
except Timeout: |
| 436 |
os._exit(0) |
| 437 |
release(contender) |
| 438 |
os._exit(2) |
| 439 |
_, status = os.waitpid(contender_pid, 0) |
| 440 |
release(lock) |
| 441 |
sys.exit(os.waitstatus_to_exitcode(status)) |
| 442 |
""" |
| 443 |
result = subprocess.run( |
| 444 |
[sys.executable, "-c", script, kind, str(tmp_path / "parent.lock")], |
| 445 |
check=False, |
| 446 |
capture_output=True, |
| 447 |
text=True, |
| 448 |
timeout=15, |
| 449 |
) |
| 450 |
|
| 451 |
assert result.returncode == 0, result.stderr |
| 452 |
|
| 453 |
|
| 454 |
def _run_child_cleanup( |
| 455 |
lock: BaseFileLock, |
| 456 |
proxy: AcquireReturnProxy, |
| 457 |
action: Literal["release", "context", "collect"], |
| 458 |
) -> NoReturn: |
| 459 |
assert (lock.is_locked, lock.lock_counter) == (False, 0) |
| 460 |
if action == "release": |
| 461 |
lock.release(force=True) |
| 462 |
elif action == "context": |
| 463 |
proxy.__exit__(None, None, None) |
| 464 |
else: |
| 465 |
del proxy |
| 466 |
del lock |
| 467 |
gc.collect() |
| 468 |
exit_child(0) |
| 469 |
|
| 470 |
|
| 471 |
def _probe_lock(lock_type: type[BaseFileLock], path: str) -> bool: # pragma: needs fork |
| 472 |
read_fd, write_fd = os.pipe() |
| 473 |
|
| 474 |
def probe_child() -> NoReturn: |
| 475 |
os.close(read_fd) |
| 476 |
candidate = lock_type(path, is_singleton=False) |
| 477 |
try: |
| 478 |
candidate.acquire(timeout=0) |
| 479 |
except Timeout: |
| 480 |
acquired = False |
| 481 |
else: |
| 482 |
acquired = True |
| 483 |
candidate.release() |
| 484 |
os.write(write_fd, b"1" if acquired else b"0") |
| 485 |
os.close(write_fd) |
| 486 |
exit_child(0) |
| 487 |
|
| 488 |
child_pid = fork_process(probe_child) |
| 489 |
os.close(write_fd) |
| 490 |
result = os.read(read_fd, 1) |
| 491 |
os.close(read_fd) |
| 492 |
_, status = os.waitpid(child_pid, 0) |
| 493 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 494 |
return result == b"1" |
| 495 |
|
| 496 |
|
| 497 |
def _assert_descriptor_closed(fd: int) -> NoReturn: |
| 498 |
try: |
| 499 |
os.fstat(fd) |
| 500 |
except OSError as exception: |
| 501 |
exit_child(0 if exception.errno == EBADF else 1) |
| 502 |
exit_child(1) |