Debian Codegraph @

src/filelock/_soft_rw/_protocol.py

raw
1 """
2 The generation-log protocol behind :class:`~filelock.SoftReadWriteLock`.
3
4 The lock's whole state is a sequence of immutable snapshots, ``gen/<N>``, each naming the writer and the readers that
5 hold the lock at generation ``N``. Every transition is one atomic publication of the next snapshot: a participant reads
6 the latest generation, derives the successor it wants, and links a fully written temporary file to ``gen/<N+1>``. The
7 link fails if a peer got there first, so the participant re-reads and tries again. No step is ever half done: a crash
8 leaves at most an unlinked temporary file, never a state that another participant must repair before it can proceed.
9
10 Liveness rests on a nonce, not a clock. Each participant keeps ``holders/<token>`` and rewrites its nonce every
11 heartbeat. A contender records the bytes it read there and the moment it read them on its own monotonic clock; a
12 member whose bytes have not changed for ``stale_threshold`` is evicted by committing a snapshot without it. Two hosts
13 never compare clocks, so a skewed file server or a suspended virtual machine cannot make a live holder look dead.
14
15 The generation number is monotonic and unique to one transition, so the generation at which a hold was granted fences
16 it: a resource that rejects anything carrying a lower generation than the highest it has accepted refuses a holder
17 that paused past its expiry and resumed.
18 """
19
20 from __future__ import annotations
21
22 import os
23 import secrets
24 from contextlib import suppress
25 from dataclasses import dataclass
26 from pathlib import Path
27 from typing import TYPE_CHECKING, Final, Literal, Protocol
28
29 from filelock._error import SoftFileLockProtocolError
30 from filelock._identity import host_name
31
32 if TYPE_CHECKING:
33 from collections.abc import Callable
34
35 Mode = Literal["read", "write"]
36 HeartbeatOutcome = Literal["ok", "lost", "transient"]
37
38 _PROTOCOL: Final[str] = "filelock-rw/1"
39 _GENERATION_DIGITS: Final[int] = 20
40 _TOKEN_HEX_LENGTH: Final[int] = 32
41 #: A snapshot line is ``reader=`` plus a token, so this bounds a hostile record without capping real reader counts.
42 _MAX_RECORD_SIZE: Final[int] = 1 << 20
43 #: Snapshots older than this many generations behind the latest are removed by whoever commits. The window is also how
44 #: far ``latest`` probes past a gap before it trusts that nothing newer exists, so it bounds how stale a directory
45 #: listing may be before a participant could mistake an old generation for the head.
46 _RETAINED_GENERATIONS: Final[int] = 64
47 _GENERATIONS_DIRECTORY: Final[str] = "gen"
48 _HOLDERS_DIRECTORY: Final[str] = "holders"
49 _TEMPORARY_PREFIX: Final[str] = ".commit-"
50
51
52 class Files(Protocol):
53 """The filesystem operations the protocol runs on; :mod:`._storage` implements them over :mod:`os`."""
54
55 def read(self, path: str) -> bytes | None:
56 """The file's bytes, ``None`` when it does not exist, or ``b""`` when it is not a regular file."""
57
58 def create(self, path: str, data: bytes) -> None:
59 """Create the file exclusively with the whole record written; raise ``FileExistsError`` when it exists."""
60
61 def link(self, source: str, target: str) -> bool:
62 """Hard-link *source* to *target* without replacing; ``True`` when *target* names *source*'s file afterwards."""
63
64 def overwrite(self, path: str, data: bytes) -> bool:
65 """Rewrite the file in place from offset zero; ``False`` when it no longer exists."""
66
67 def unlink(self, path: str) -> None:
68 """Remove the file, tolerating one that is already gone."""
69
70 def listdir(self, path: str) -> list[str]:
71 """The names in the directory, or an empty list when it does not exist."""
72
73 def prepare(self, root: str) -> None:
74 """Create the protocol directories under *root*, refusing anything at those paths that is not a directory."""
75
76
77 @dataclass(frozen=True)
78 class Snapshot:
79 """The lock's state at one generation: which token writes, which tokens read."""
80
81 generation: int
82 writer: str | None
83 readers: frozenset[str]
84
85 @property
86 def members(self) -> frozenset[str]:
87 """Every token this generation names."""
88 return self.readers if self.writer is None else self.readers | {self.writer}
89
90 def encode(self) -> bytes:
91 lines = [_PROTOCOL, f"generation={self.generation}"]
92 if self.writer is not None:
93 lines.append(f"writer={self.writer}")
94 lines.extend(f"reader={token}" for token in sorted(self.readers))
95 return "".join(f"{line}\n" for line in lines).encode("ascii")
96
97
98 def parse_snapshot(data: bytes) -> Snapshot | None:
99 """The snapshot a ``gen/<N>`` record encodes, or ``None`` when the record is malformed."""
100 if not data or len(data) > _MAX_RECORD_SIZE:
101 return None
102 try:
103 lines = data.decode("ascii").split("\n")
104 except UnicodeDecodeError:
105 return None
106 if lines[0] != _PROTOCOL or lines[-1]:
107 return None
108 generation: int | None = None
109 writer: str | None = None
110 readers: set[str] = set()
111 for line in lines[1:-1]:
112 key, _, value = line.partition("=")
113 if (
114 key == "generation"
115 and generation is None
116 and len(value) <= _GENERATION_DIGITS
117 and value.isdigit()
118 and str(int(value)) == value
119 ):
120 generation = int(value)
121 elif key == "writer" and writer is None and is_token(value):
122 writer = value
123 elif key == "reader" and is_token(value) and value not in readers:
124 readers.add(value)
125 else:
126 return None
127 return None if generation is None else Snapshot(generation=generation, writer=writer, readers=frozenset(readers))
128
129
130 def is_token(value: str) -> bool:
131 """Whether *value* is a claim token: exactly 32 lowercase hex digits."""
132 return len(value) == _TOKEN_HEX_LENGTH and all(character in "0123456789abcdef" for character in value)
133
134
135 def new_token() -> str:
136 """A fresh claim token."""
137 return secrets.token_hex(_TOKEN_HEX_LENGTH // 2)
138
139
140 def encode_holder(token: str, nonce: str) -> bytes:
141 """The ``holders/<token>`` record; only the nonce changes between heartbeats, so the length stays constant."""
142 return f"{_PROTOCOL}\ntoken={token}\npid={os.getpid()}\nhost={host_name()}\nnonce={nonce}\n".encode("ascii")
143
144
145 class Ledger:
146 """
147 How long each observed value has stayed the same, measured on this observer's monotonic clock.
148
149 A value that has not changed for ``stale_threshold`` belongs to a participant that stopped refreshing it. The clock
150 is the observer's own and only ever measures the gap between two of its own observations, which is what lets two
151 hosts agree on liveness without agreeing on the time.
152 """
153
154 def __init__(self, clock: Callable[[], float]) -> None:
155 self._clock = clock
156 self._seen: dict[str, tuple[bytes | None, float]] = {}
157
158 def observe(self, key: str, value: bytes | None) -> float:
159 """Record *value* for *key* and return how long it has been unchanged."""
160 now = self._clock()
161 if (seen := self._seen.get(key)) is None or seen[0] != value:
162 self._seen[key] = (value, now)
163 return 0.0
164 return now - seen[1]
165
166 def forget(self, key: str) -> None:
167 self._seen.pop(key, None)
168
169
170 class GenerationLog:
171 """The ordered snapshots under ``gen/``, found by listing and probing, advanced by linking the next one."""
172
173 def __init__(self, files: Files, lock_file: str, root: str) -> None:
174 self._files = files
175 self._lock_file = lock_file
176 self._directory = Path(root, _GENERATIONS_DIRECTORY)
177 self._latest: Snapshot | None = None
178
179 def latest(self) -> Snapshot:
180 """
181 The newest snapshot.
182
183 Lists the directory on every call, since opening it is what makes an NFS client revalidate what it has cached
184 about the names inside, then starts from the newest readable generation the listing or memory names and probes
185 forward by name across the retained window. A listing served stale, a generation compacted between the listing
186 and the read, and a hole left by a committer that died before it compacted are all covered by the probe; only a
187 listing that names generations of which none can be read is refused, because that is a client so far behind
188 the log that nothing it reads can be trusted.
189 """
190 listed = self._list()
191 if (start := self._start(listed)) is None:
192 # Everything the listing named is gone: peers compacted past it while this client looked. One more listing
193 # settles whether the directory is genuinely empty or this client cannot see the head at all.
194 listed = self._list()
195 if (start := self._start(listed)) is None:
196 if listed:
197 raise SoftFileLockProtocolError(self._lock_file, None, "generation log names no readable snapshot")
198 start = Snapshot(generation=0, writer=None, readers=frozenset())
199 latest = start
200 generation = start.generation
201 gap = 0
202 while gap < _RETAINED_GENERATIONS:
203 generation += 1
204 if (snapshot := self._read(generation)) is None:
205 gap += 1
206 continue
207 latest = snapshot
208 gap = 0
209 self._latest = latest
210 return latest
211
212 def _list(self) -> list[int]:
213 listed = sorted(
214 int(name)
215 for name in self._files.listdir(str(self._directory))
216 if name.isdigit() and len(name) == _GENERATION_DIGITS
217 )
218 for generation in listed[:-_RETAINED_GENERATIONS]:
219 self._files.unlink(self._path(generation))
220 return listed[-_RETAINED_GENERATIONS:]
221
222 def _start(self, listed: list[int]) -> Snapshot | None:
223 remembered = self._latest
224 for generation in reversed(listed):
225 if remembered is not None and remembered.generation >= generation:
226 return remembered
227 if (snapshot := self._read(generation)) is not None:
228 return snapshot
229 return remembered
230
231 def _read(self, generation: int) -> Snapshot | None:
232 if (data := self._files.read(self._path(generation))) is None:
233 return None
234 if (snapshot := parse_snapshot(data)) is None or snapshot.generation != generation:
235 name = self._name(generation)
236 raise SoftFileLockProtocolError(self._lock_file, name, "malformed generation record")
237 return snapshot
238
239 def commit(self, successor: Snapshot) -> bool:
240 """
241 Publish *successor* as the next generation; ``False`` when a peer published that generation first.
242
243 The record is complete before it gets its public name, and a no-replace hard link is the compare-and-swap: only
244 one link to ``gen/<N+1>`` can ever succeed. The link's return code is not trusted, because an NFS retry can
245 report a link that did land as failed; the file's identity after the call is what decides.
246 """
247 temporary = str(self._directory / f"{_TEMPORARY_PREFIX}{new_token()}")
248 self._files.create(temporary, successor.encode())
249 try:
250 linked = self._files.link(temporary, self._path(successor.generation))
251 finally:
252 self._files.unlink(temporary)
253 if not linked:
254 return False
255 self._latest = successor
256 self._files.unlink(self._path(successor.generation - _RETAINED_GENERATIONS - 1))
257 return True
258
259 def _path(self, generation: int) -> str:
260 return str(self._directory / self._name(generation))
261
262 @staticmethod
263 def _name(generation: int) -> str:
264 return f"{generation:0{_GENERATION_DIGITS}d}"
265
266
267 class Participant:
268 """
269 One acquisition, from publishing a claim through holding the lock to leaving.
270
271 ``advance`` is polled until it reports the lock granted, ``heartbeat`` runs on the holder's schedule, and ``leave``
272 commits the participant out. None of them sleep: the caller owns the deadline and the poll interval. The ledger and
273 the log outlive one acquisition: how long a peer's record has stayed unchanged is knowledge every attempt against
274 the same lock shares, or a caller whose attempts are each shorter than the stale threshold could never evict.
275 """
276
277 def __init__( # ruff:ignore[too-many-arguments] # one value per protocol input; the lock builds this once per acquisition
278 self,
279 files: Files,
280 root: str,
281 mode: Mode,
282 *,
283 stale_threshold: float,
284 clock: Callable[[], float],
285 ledger: Ledger,
286 log: GenerationLog,
287 ) -> None:
288 self.token: Final[str] = new_token()
289 self.mode: Final[Mode] = mode
290 self.generation: int | None = None
291 self._files = files
292 self._root = root
293 self._stale_threshold = stale_threshold
294 self._clock = clock
295 self._ledger = ledger
296 self._log = log
297 self._holder = self._holder_path(self.token)
298 self._entered = False
299 self._next_sweep = clock()
300
301 def publish(self) -> None:
302 """Create the holder record peers watch for liveness; it exists before the token appears in any snapshot."""
303 self._files.prepare(self._root)
304 self._files.create(self._holder, encode_holder(self.token, new_token()))
305
306 def advance(self) -> bool:
307 """
308 Take the next step toward holding the lock; ``True`` once the lock is granted.
309
310 A reader enters as soon as no live writer is named. A writer enters as soon as no live writer is named, which
311 blocks every new reader, then waits for the named readers to leave. Stale members are evicted in the same commit
312 that admits this participant, and a writer's final admission is itself a commit, so no admission can rest on a
313 snapshot a peer is about to supersede.
314 """
315 # A lost race is not a reason to wait: re-read and try again before handing the poll interval back to the
316 # caller.
317 for _ in range(4):
318 latest = self._log.latest()
319 self._keep_claim_fresh(latest)
320 self._sweep(latest)
321 stale = frozenset(token for token in latest.members - {self.token} if self._is_stale(token))
322 writer = None if latest.writer in stale else latest.writer
323 readers = latest.readers - stale
324 if not self._entered:
325 if writer is not None:
326 # A live writer blocks entry in both modes; only an eviction is worth committing.
327 if stale:
328 self._commit(latest, writer, readers, stale)
329 return False
330 writer, readers = (self.token, readers) if self.mode == "write" else (None, readers | {self.token})
331 granted = self.mode == "read" or not readers
332 if self._entered and not stale and not granted:
333 return False
334 if (generation := self._commit(latest, writer, readers, stale)) is None:
335 continue
336 self._entered = True
337 if granted:
338 self.generation = generation
339 return granted
340 return False
341
342 def _keep_claim_fresh(self, latest: Snapshot) -> None:
343 # The snapshot is the truth about membership: a commit the filesystem reported lost may have landed, and a peer
344 # may have evicted this participant while it waited to drain, so both directions are taken from it. A wait can
345 # outlast the stale threshold, so the nonce changes on every poll; a peer then never reads a patient contender
346 # as a corpse. A record that has gone missing was taken by an evictor or a sweeper that did.
347 self._entered = self.token in latest.members
348 if not self._refresh_nonce():
349 with suppress(FileExistsError):
350 self._files.create(self._holder, encode_holder(self.token, new_token()))
351
352 def _sweep(self, latest: Snapshot) -> None:
353 # A participant that crashed before its first commit leaves a record no snapshot names, and a commit that
354 # crashed between creating and unlinking its temporary file leaves that too. Neither blocks anyone, so they are
355 # collected on the same unchanged-for-a-threshold rule as a member, and only every half threshold at most.
356 if (now := self._clock()) < self._next_sweep:
357 return
358 self._next_sweep = now + self._stale_threshold / 2
359 holders = Path(self._root, _HOLDERS_DIRECTORY)
360 for name in self._files.listdir(str(holders)):
361 if name != self.token and name not in latest.members and is_token(name):
362 self._collect(f"holder:{name}", str(holders / name))
363 generations = Path(self._root, _GENERATIONS_DIRECTORY)
364 for name in self._files.listdir(str(generations)):
365 if name.startswith(_TEMPORARY_PREFIX):
366 self._collect(f"temporary:{name}", str(generations / name))
367
368 def _collect(self, key: str, path: str) -> None:
369 if self._ledger.observe(key, self._files.read(path)) >= self._stale_threshold:
370 self._files.unlink(path)
371 self._ledger.forget(key)
372
373 def _commit(
374 self, latest: Snapshot, writer: str | None, readers: frozenset[str], stale: frozenset[str]
375 ) -> int | None:
376 successor = Snapshot(generation=latest.generation + 1, writer=writer, readers=readers)
377 if not self._log.commit(successor):
378 return None
379 for token in stale:
380 self._files.unlink(self._holder_path(token))
381 self._ledger.forget(token)
382 return successor.generation
383
384 def _is_stale(self, token: str) -> bool:
385 return self._ledger.observe(token, self._files.read(self._holder_path(token))) >= self._stale_threshold
386
387 def _holder_path(self, token: str) -> str:
388 return str(Path(self._root, _HOLDERS_DIRECTORY, token))
389
390 def _refresh_nonce(self) -> bool:
391 return self._files.overwrite(self._holder, encode_holder(self.token, new_token()))
392
393 def heartbeat(self) -> tuple[HeartbeatOutcome, OSError | None]:
394 """
395 Refresh the nonce and confirm the latest snapshot still names this participant.
396
397 ``lost`` means a peer evicted this participant or removed its holder record: the lock is no longer held, and the
398 holder must stop using what it protects. ``transient`` is a filesystem error refreshing the nonce, worth
399 retrying on the next tick. A failure to read the log or to sweep decides nothing about this holder's liveness,
400 so it is not counted against it.
401 """
402 try:
403 if not self._refresh_nonce():
404 return "lost", None
405 except OSError as error:
406 return "transient", error
407 try:
408 latest = self._log.latest()
409 self._sweep(latest)
410 except OSError:
411 return "ok", None
412 return ("ok" if self.token in latest.members else "lost"), None
413
414 def leave(self) -> None:
415 """Commit this participant out of the latest snapshot, then remove its holder record."""
416 while self.token in (latest := self._log.latest()).members:
417 successor = Snapshot(
418 generation=latest.generation + 1,
419 writer=None if latest.writer == self.token else latest.writer,
420 readers=latest.readers - {self.token},
421 )
422 if self._log.commit(successor):
423 break
424 self._entered = False
425 self.generation = None
426 self._files.unlink(self._holder)
427
428
429 __all__ = [
430 "Files",
431 "GenerationLog",
432 "HeartbeatOutcome",
433 "Ledger",
434 "Mode",
435 "Participant",
436 "Snapshot",
437 "encode_holder",
438 "is_token",
439 "new_token",
440 "parse_snapshot",
441 ]