| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import threading |
| 5 |
import time |
| 6 |
from errno import EIO |
| 7 |
from pathlib import Path |
| 8 |
from typing import TYPE_CHECKING, Literal |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from filelock import StrictSoftFileLock, Timeout |
| 13 |
from filelock._strict import _CLAIM_MAGIC |
| 14 |
|
| 15 |
if TYPE_CHECKING: |
| 16 |
from pytest_mock import MockerFixture |
| 17 |
|
| 18 |
|
| 19 |
pytestmark = pytest.mark.requires_hard_links |
| 20 |
|
| 21 |
|
| 22 |
def test_strict_soft_lower_intent_delayed_until_higher_selects(tmp_path: Path, mocker: MockerFixture) -> None: |
| 23 |
lock_path = tmp_path / "resource.lock" |
| 24 |
_initialize_protocol(lock_path) |
| 25 |
lower_intent_waiting = threading.Event() |
| 26 |
higher_held_attempted = threading.Event() |
| 27 |
lower_held_linked = threading.Event() |
| 28 |
higher_held_linked = threading.Event() |
| 29 |
real_link = os.link |
| 30 |
|
| 31 |
def ordered_link( |
| 32 |
source: str, |
| 33 |
destination: str, |
| 34 |
*, |
| 35 |
src_dir_fd: int | None = None, |
| 36 |
dst_dir_fd: int | None = None, |
| 37 |
follow_symlinks: bool = True, |
| 38 |
) -> None: |
| 39 |
name = Path(destination).name |
| 40 |
if threading.current_thread().name == "lower" and name.startswith("intent-"): |
| 41 |
lower_intent_waiting.set() |
| 42 |
assert higher_held_attempted.wait(timeout=2) |
| 43 |
if threading.current_thread().name == "higher" and name.startswith("held-"): |
| 44 |
higher_held_attempted.set() |
| 45 |
assert lower_held_linked.wait(timeout=2) |
| 46 |
real_link( |
| 47 |
source, |
| 48 |
destination, |
| 49 |
src_dir_fd=src_dir_fd, |
| 50 |
dst_dir_fd=dst_dir_fd, |
| 51 |
follow_symlinks=follow_symlinks, |
| 52 |
) |
| 53 |
if threading.current_thread().name == "lower" and name.startswith("held-"): |
| 54 |
lower_held_linked.set() |
| 55 |
assert higher_held_linked.wait(timeout=2) |
| 56 |
elif threading.current_thread().name == "higher" and name.startswith("held-"): |
| 57 |
higher_held_linked.set() |
| 58 |
|
| 59 |
mocker.patch("filelock._strict.os.link", side_effect=ordered_link) |
| 60 |
mocker.patch( |
| 61 |
"filelock._strict.secrets.token_hex", |
| 62 |
side_effect=lambda _size: "0" * 32 if threading.current_thread().name == "lower" else "f" * 32, |
| 63 |
) |
| 64 |
acquisition_order: list[str] = [] |
| 65 |
inside, state_lock = 0, threading.Lock() |
| 66 |
|
| 67 |
def acquire(label: str) -> None: |
| 68 |
nonlocal inside |
| 69 |
with StrictSoftFileLock(lock_path, timeout=3, poll_interval=0.001): |
| 70 |
with state_lock: |
| 71 |
inside += 1 |
| 72 |
assert inside == 1 |
| 73 |
acquisition_order.append(label) |
| 74 |
time.sleep(0.01) |
| 75 |
with state_lock: |
| 76 |
inside -= 1 |
| 77 |
|
| 78 |
lower = threading.Thread(target=acquire, args=("lower",), name="lower") |
| 79 |
higher = threading.Thread(target=acquire, args=("higher",), name="higher") |
| 80 |
lower.start() |
| 81 |
assert lower_intent_waiting.wait(timeout=2) |
| 82 |
higher.start() |
| 83 |
_join_threads(lower, higher) |
| 84 |
assert (acquisition_order, inside) == (["lower", "higher"], 0) |
| 85 |
|
| 86 |
|
| 87 |
def test_strict_soft_lower_intent_delayed_until_higher_enters(tmp_path: Path, mocker: MockerFixture) -> None: |
| 88 |
lock_path = tmp_path / "resource.lock" |
| 89 |
_initialize_protocol(lock_path) |
| 90 |
lower_intent_waiting = threading.Event() |
| 91 |
higher_entered = threading.Event() |
| 92 |
release_higher = threading.Event() |
| 93 |
real_link = os.link |
| 94 |
|
| 95 |
def delayed_link( |
| 96 |
source: str, |
| 97 |
destination: str, |
| 98 |
*, |
| 99 |
src_dir_fd: int | None = None, |
| 100 |
dst_dir_fd: int | None = None, |
| 101 |
follow_symlinks: bool = True, |
| 102 |
) -> None: |
| 103 |
if threading.current_thread().name == "lower" and Path(destination).name.startswith("intent-"): |
| 104 |
lower_intent_waiting.set() |
| 105 |
assert higher_entered.wait(timeout=2) |
| 106 |
real_link( |
| 107 |
source, |
| 108 |
destination, |
| 109 |
src_dir_fd=src_dir_fd, |
| 110 |
dst_dir_fd=dst_dir_fd, |
| 111 |
follow_symlinks=follow_symlinks, |
| 112 |
) |
| 113 |
|
| 114 |
mocker.patch("filelock._strict.os.link", side_effect=delayed_link) |
| 115 |
mocker.patch( |
| 116 |
"filelock._strict.secrets.token_hex", |
| 117 |
side_effect=lambda _size: "0" * 32 if threading.current_thread().name == "lower" else "f" * 32, |
| 118 |
) |
| 119 |
acquisition_order: list[str] = [] |
| 120 |
|
| 121 |
def acquire(label: str) -> None: |
| 122 |
with StrictSoftFileLock(lock_path, timeout=3, poll_interval=0.001): |
| 123 |
acquisition_order.append(label) |
| 124 |
if label == "higher": |
| 125 |
higher_entered.set() |
| 126 |
assert release_higher.wait(timeout=2) |
| 127 |
|
| 128 |
lower = threading.Thread(target=acquire, args=("lower",), name="lower") |
| 129 |
higher = threading.Thread(target=acquire, args=("higher",), name="higher") |
| 130 |
lower.start() |
| 131 |
assert lower_intent_waiting.wait(timeout=2) |
| 132 |
higher.start() |
| 133 |
assert higher_entered.wait(timeout=2) |
| 134 |
assert acquisition_order == ["higher"] |
| 135 |
release_higher.set() |
| 136 |
_join_threads(lower, higher) |
| 137 |
assert acquisition_order == ["higher", "lower"] |
| 138 |
|
| 139 |
|
| 140 |
def test_strict_soft_private_partial_record_is_not_a_claim(tmp_path: Path, mocker: MockerFixture) -> None: |
| 141 |
lock_path = tmp_path / "resource.lock" |
| 142 |
_initialize_protocol(lock_path) |
| 143 |
partial_written = threading.Event() |
| 144 |
resume_write = threading.Event() |
| 145 |
real_write = os.write |
| 146 |
paused = False |
| 147 |
|
| 148 |
# The patch binds os.write process-wide, so key the pause to the claim record itself: a finalizer the collector |
| 149 |
# runs on the "partial" thread may write to the resource tracker's pipe meanwhile, and truncating that command |
| 150 |
# breaks the tracker rather than this test. |
| 151 |
def paused_write(fd: int, data: bytes | bytearray | memoryview) -> int: |
| 152 |
nonlocal paused |
| 153 |
if threading.current_thread().name != "partial" or paused or not bytes(data).startswith(_CLAIM_MAGIC.encode()): |
| 154 |
return real_write(fd, data) |
| 155 |
paused = True |
| 156 |
written = real_write(fd, data[:1]) |
| 157 |
partial_written.set() |
| 158 |
assert resume_write.wait(timeout=2) |
| 159 |
return written |
| 160 |
|
| 161 |
mocker.patch("filelock._util.os.write", side_effect=paused_write) |
| 162 |
|
| 163 |
def acquire_partial() -> None: |
| 164 |
with StrictSoftFileLock(lock_path, timeout=3, poll_interval=0.001): |
| 165 |
pass |
| 166 |
|
| 167 |
partial = threading.Thread(target=acquire_partial, name="partial") |
| 168 |
partial.start() |
| 169 |
assert partial_written.wait(timeout=2) |
| 170 |
with StrictSoftFileLock(lock_path, timeout=0) as contender: |
| 171 |
assert contender.is_locked |
| 172 |
resume_write.set() |
| 173 |
_join_threads(partial) |
| 174 |
|
| 175 |
|
| 176 |
def test_strict_soft_shared_instance_waits_for_failed_doorway(tmp_path: Path, mocker: MockerFixture) -> None: |
| 177 |
lock_path = tmp_path / "resource.lock" |
| 178 |
_initialize_protocol(lock_path) |
| 179 |
lock = StrictSoftFileLock(lock_path, thread_local=False, timeout=2, poll_interval=0.001) |
| 180 |
first_doorway = threading.Event() |
| 181 |
fail_first = threading.Event() |
| 182 |
second_entered = threading.Event() |
| 183 |
first_errors: list[OSError] = [] |
| 184 |
real_link = os.link |
| 185 |
|
| 186 |
def pause_first_intent( |
| 187 |
source: str, |
| 188 |
destination: str, |
| 189 |
*, |
| 190 |
src_dir_fd: int | None = None, |
| 191 |
dst_dir_fd: int | None = None, |
| 192 |
follow_symlinks: bool = True, |
| 193 |
) -> None: |
| 194 |
if threading.current_thread().name == "first" and Path(destination).name.startswith("intent-"): |
| 195 |
first_doorway.set() |
| 196 |
assert fail_first.wait(timeout=2) |
| 197 |
raise OSError(EIO, "doorway failed") |
| 198 |
real_link( |
| 199 |
source, |
| 200 |
destination, |
| 201 |
src_dir_fd=src_dir_fd, |
| 202 |
dst_dir_fd=dst_dir_fd, |
| 203 |
follow_symlinks=follow_symlinks, |
| 204 |
) |
| 205 |
|
| 206 |
def acquire_first() -> None: |
| 207 |
try: |
| 208 |
lock.acquire() |
| 209 |
except OSError as error: |
| 210 |
first_errors.append(error) |
| 211 |
|
| 212 |
def acquire_second() -> None: |
| 213 |
with lock: |
| 214 |
second_entered.set() |
| 215 |
|
| 216 |
mocker.patch("filelock._strict.os.link", side_effect=pause_first_intent) |
| 217 |
first = threading.Thread(target=acquire_first, name="first") |
| 218 |
second = threading.Thread(target=acquire_second, name="second") |
| 219 |
first.start() |
| 220 |
assert first_doorway.wait(timeout=2) |
| 221 |
second.start() |
| 222 |
assert not second_entered.wait(timeout=0.05) |
| 223 |
fail_first.set() |
| 224 |
_join_threads(first, second) |
| 225 |
assert ([str(error) for error in first_errors], second_entered.is_set(), lock.is_locked) == ( |
| 226 |
["[Errno 5] doorway failed"], |
| 227 |
True, |
| 228 |
False, |
| 229 |
) |
| 230 |
|
| 231 |
|
| 232 |
@pytest.mark.parametrize( |
| 233 |
"admission", |
| 234 |
[ |
| 235 |
pytest.param("timeout", id="zero-timeout"), |
| 236 |
pytest.param("blocking", id="nonblocking"), |
| 237 |
pytest.param("cancel", id="cancel-check"), |
| 238 |
], |
| 239 |
) |
| 240 |
def test_strict_soft_shared_instance_transition_respects_admission( |
| 241 |
tmp_path: Path, |
| 242 |
mocker: MockerFixture, |
| 243 |
admission: Literal["timeout", "blocking", "cancel"], |
| 244 |
) -> None: |
| 245 |
lock_path = tmp_path / "resource.lock" |
| 246 |
_initialize_protocol(lock_path) |
| 247 |
lock = StrictSoftFileLock(lock_path, thread_local=False, timeout=2, poll_interval=0.001) |
| 248 |
first_doorway = threading.Event() |
| 249 |
continue_first = threading.Event() |
| 250 |
release_first = threading.Event() |
| 251 |
real_link = os.link |
| 252 |
|
| 253 |
def pause_first_intent( |
| 254 |
source: str, |
| 255 |
destination: str, |
| 256 |
*, |
| 257 |
src_dir_fd: int | None = None, |
| 258 |
dst_dir_fd: int | None = None, |
| 259 |
follow_symlinks: bool = True, |
| 260 |
) -> None: |
| 261 |
if threading.current_thread().name == "first" and Path(destination).name.startswith("intent-"): |
| 262 |
first_doorway.set() |
| 263 |
assert continue_first.wait(timeout=2) |
| 264 |
real_link( |
| 265 |
source, |
| 266 |
destination, |
| 267 |
src_dir_fd=src_dir_fd, |
| 268 |
dst_dir_fd=dst_dir_fd, |
| 269 |
follow_symlinks=follow_symlinks, |
| 270 |
) |
| 271 |
|
| 272 |
def acquire_first() -> None: |
| 273 |
with lock: |
| 274 |
assert release_first.wait(timeout=2) |
| 275 |
|
| 276 |
mocker.patch("filelock._strict.os.link", side_effect=pause_first_intent) |
| 277 |
first = threading.Thread(target=acquire_first, name="first") |
| 278 |
first.start() |
| 279 |
assert first_doorway.wait(timeout=2) |
| 280 |
started = time.perf_counter() |
| 281 |
with pytest.raises(Timeout): |
| 282 |
_acquire_during_transition(lock, admission) |
| 283 |
elapsed = time.perf_counter() - started |
| 284 |
continue_first.set() |
| 285 |
release_first.set() |
| 286 |
_join_threads(first) |
| 287 |
assert (elapsed < 0.2, lock.is_locked) == (True, False) |
| 288 |
|
| 289 |
|
| 290 |
def _acquire_during_transition( |
| 291 |
lock: StrictSoftFileLock, |
| 292 |
admission: Literal["timeout", "blocking", "cancel"], |
| 293 |
) -> None: |
| 294 |
if admission == "timeout": |
| 295 |
lock.acquire(timeout=0) |
| 296 |
elif admission == "blocking": |
| 297 |
lock.acquire(blocking=False) |
| 298 |
else: |
| 299 |
lock.acquire(cancel_check=lambda: True) |
| 300 |
|
| 301 |
|
| 302 |
def _initialize_protocol(lock_path: Path) -> None: |
| 303 |
with StrictSoftFileLock(lock_path): |
| 304 |
pass |
| 305 |
|
| 306 |
|
| 307 |
def _join_threads(*threads: threading.Thread) -> None: |
| 308 |
for thread in threads: |
| 309 |
thread.join(timeout=3) |
| 310 |
assert [thread.name for thread in threads if thread.is_alive()] == [] |