Debian Codegraph @

src/filelock/_lease.py

raw
1 from __future__ import annotations
2
3 import os
4 import secrets
5 import time
6 from contextlib import suppress
7 from dataclasses import dataclass
8 from math import isfinite
9 from threading import Event, Thread, current_thread, local
10 from typing import TYPE_CHECKING, Literal
11
12 from ._error import LeaseSettingsMismatch
13 from ._identity import owner_is_stale
14 from ._marker import MarkerSoftFileLock, OwnerMode, OwnerRecord, parse_marker
15 from ._soft import _read_lock_file
16 from ._util import break_lock_file, touch
17
18 if TYPE_CHECKING:
19 import sys
20 from collections.abc import Callable
21
22 from ._api import LockOptions
23
24 if sys.version_info >= (3, 11): # pragma: no cover (py311+)
25 from typing import Unpack
26 else: # pragma: no cover (<py311)
27 from typing_extensions import Unpack
28
29 #: ``evicted`` is a :class:`~filelock.SoftReadWriteLock` loss: a peer waited out the stale threshold and committed a
30 #: generation without this holder.
31 CompromiseReason = Literal["marker-missing", "owner-changed", "refresh-failed", "evicted"]
32
33 _RefreshOutcome = Literal["ok", "lost", "transient"]
34
35
36 @dataclass(frozen=True)
37 class LeaseCompromise:
38 """Why a held lease stopped being this process's to hold."""
39
40 lock_file: str
41 token: str
42 reason: CompromiseReason
43 error: OSError | None = None
44
45
46 @dataclass(frozen=True)
47 class _Heartbeat:
48 """A running heartbeat and the event that stops it, which only ever exist together."""
49
50 thread: Thread
51 stop: Event
52
53
54 @dataclass
55 class _LeaseClaim:
56 """The state of one claim: its token, its heartbeat, and how that claim was lost."""
57
58 token: str | None = None
59 compromise: LeaseCompromise | None = None
60 heartbeat: _Heartbeat | None = None
61
62
63 class _LeaseClaimHolder:
64 """Holds the claim its owning context acquired."""
65
66 # Only the holder is thread-local, mirroring FileLockContext: the claim stays an ordinary object, so the heartbeat
67 # thread records a compromise where the thread that acquired the lease reads it.
68
69 def __init__(self) -> None:
70 self.claim = _LeaseClaim()
71
72
73 class _ThreadLocalLeaseClaimHolder(_LeaseClaimHolder, local):
74 """A thread local version of the ``_LeaseClaimHolder`` class."""
75
76
77 class SoftFileLease(MarkerSoftFileLock):
78 """
79 Existence lock whose claim expires, so a peer may take it while the previous holder still runs.
80
81 A lease trades mutual exclusion for progress. The holder publishes a claim and refreshes it every
82 ``heartbeat_interval`` seconds; a contender takes the marker once it is ``lease_duration`` seconds stale. Nothing
83 stops the expired holder: it keeps running, and it keeps using whatever the lock protects. Treat the lease as a hint
84 about who *should* be working, not as a guarantee that only one worker is.
85
86 To make a protected resource reject a superseded holder, that resource must be linearizable and must fence on a
87 monotonic generation it controls. :attr:`token` names a claim; it does not fence one. Where overlap is unacceptable,
88 use :class:`StrictSoftFileLock <filelock.StrictSoftFileLock>` instead.
89
90 Every contender for a path must agree on ``lease_duration``. A contender that finds a claim published under a
91 different duration raises :class:`LeaseSettingsMismatch <filelock.LeaseSettingsMismatch>` rather than apply its own
92 expiry to a peer that never agreed to it.
93
94 Expiry reclaims less on Windows, which refuses to rename or delete a file another process holds open. A peer there
95 takes an expired claim only once the previous holder's process exits and its handle closes; a holder that lives on
96 but stops refreshing keeps the marker. Unix reclaims the marker either way.
97
98 ``on_compromise`` fires from the heartbeat thread when a refresh fails, or when the marker vanishes or names another
99 owner. The holder should stop touching the protected resource when it runs. Because it runs on that thread, a
100 ``release()`` inside it only takes effect when the lease was built with ``thread_local=False``; the default
101 thread-local context hides the claim from every thread but the one that acquired it, so the release does nothing.
102 Signal the acquiring thread instead when the context stays thread-local.
103
104 .. versionadded:: 3.30.0
105
106 """
107
108 _owner_mode: OwnerMode = "lease"
109
110 #: lease_duration replaces the legacy age-based lifetime, so accepting both would give one lock two expiry clocks.
111 _lifetime_supported: bool = False
112 _lifetime_unsupported_reason: str = "lease_duration sets when a lease expires"
113
114 def __init__(
115 self,
116 lock_file: str | os.PathLike[str],
117 *,
118 lease_duration: float = 30.0,
119 heartbeat_interval: float | None = None,
120 on_compromise: Callable[[LeaseCompromise], None] | None = None,
121 **kwargs: Unpack[LockOptions],
122 ) -> None:
123 """
124 Create a lease.
125
126 :param lease_duration: seconds of marker staleness after which a contender may take the claim. Every contender
127 for the path must pass the same value.
128 :param heartbeat_interval: seconds between refreshes. Defaults to a third of ``lease_duration``, leaving room
129 for two missed refreshes before a peer may take the claim. Must be shorter than ``lease_duration``.
130 :param on_compromise: called from the heartbeat thread with a :class:`LeaseCompromise` when the claim is lost.
131 :param kwargs: every other :class:`BaseFileLock <filelock.BaseFileLock>` option, ``timeout`` and ``mode`` among
132 them. The metaclass passes them all by keyword, and taking them here lets
133 :class:`AsyncSoftFileLease <filelock.AsyncSoftFileLease>` add the async plumbing a fixed signature would
134 hide.
135
136 """
137 if isinstance(lease_duration, bool) or not isinstance(lease_duration, (int, float)):
138 msg = f"lease_duration must be a finite positive number, not {type(lease_duration).__name__}"
139 raise TypeError(msg)
140 if not isfinite(lease_duration) or lease_duration <= 0:
141 msg = f"lease_duration must be positive and finite, got {lease_duration!r}"
142 raise ValueError(msg)
143 if heartbeat_interval is None:
144 heartbeat_interval = lease_duration / 3
145 if not 0 < heartbeat_interval < lease_duration:
146 msg = f"heartbeat_interval must be positive and below lease_duration, got {heartbeat_interval!r}"
147 raise ValueError(msg)
148 super().__init__(lock_file, **kwargs)
149 self._lease_duration = lease_duration
150 self._heartbeat_interval = heartbeat_interval
151 self._on_compromise = on_compromise
152 # Sharing one claim across a thread-local lock lets a second thread's failed acquisition stop the heartbeat of
153 # the thread holding the lease, leaving its marker unrefreshed until a peer reclaims it.
154 self._claims: _LeaseClaimHolder = (
155 _ThreadLocalLeaseClaimHolder if self.is_thread_local() else _LeaseClaimHolder
156 )()
157
158 @property
159 def _claim(self) -> _LeaseClaim:
160 return self._claims.claim
161
162 @property
163 def lease_duration(self) -> float:
164 """The staleness in seconds after which a contender may take this claim."""
165 return self._lease_duration
166
167 @property
168 def token(self) -> str | None:
169 """
170 The token naming the claim this process published.
171
172 :returns: the token while the lease is held, ``None`` otherwise. It identifies a claim; it does not fence one.
173
174 """
175 return self._claim.token
176
177 @property
178 def compromise(self) -> LeaseCompromise | None:
179 """
180 The loss of claim the heartbeat observed.
181
182 :returns: the :class:`LeaseCompromise`, or ``None`` while the claim still holds
183
184 """
185 return self._claim.compromise
186
187 def _acquire(self) -> None:
188 claim = self._claim
189 self._stop_heartbeat() # no earlier claim's heartbeat outlives the acquisition of the next one
190 # The published record reads the token, so it exists before the marker is written and goes back on failure.
191 claim.token = token = secrets.token_hex(16)
192 claim.compromise = None
193 try:
194 super()._acquire()
195 except BaseException:
196 claim.token = None
197 raise
198 # The context is thread-local by default, so the heartbeat thread cannot read the descriptor this one just
199 # published, nor the claim this one owns. Hand it the fd, the inode it verified and the claim instead.
200 if (fd := self._context.lock_file_fd) is not None and (
201 identity := self._context.lock_file_fd_identity
202 ) is not None:
203 self._start_heartbeat(claim, fd, identity, token)
204 else:
205 claim.token = None
206
207 def _release(self) -> None:
208 self._stop_heartbeat()
209 self._claim.token = None
210 super()._release()
211
212 def _published_record(self) -> OwnerRecord:
213 return super()._published_record()._replace(token=self._claim.token, lease_duration=self._lease_duration)
214
215 def _try_break_stale_lock(self) -> None:
216 if (peer := self._read_peer()) is None:
217 # Not a readable protocol 2 lease record: a partial write, a foreign or legacy protocol 1 marker, or the
218 # strict sentinel. The base self-heal evicts a genuinely malformed marker once it ages past the grace
219 # window and leaves a legitimate legacy or strict holder in place, so a corrupt marker no longer wedges
220 # every lease contender until its own timeout.
221 super()._try_break_stale_lock()
222 return
223 owner, mtime, ino = peer
224 # Only a peer that published a lease agreed to be superseded by one, so a record stating any other contract is
225 # never reclaimed by age. Raise the mismatch outside the read so the suppression cannot swallow it.
226 if owner.mode != "lease":
227 return
228 if owner.lease_duration != self._lease_duration:
229 msg = (
230 f"{self.lock_file} holds a lease of {owner.lease_duration!r}s but this contender configured "
231 f"{self._lease_duration!r}s; every contender for a path must agree on lease_duration"
232 )
233 raise LeaseSettingsMismatch(msg)
234 # A break can fail for reasons a contender must ride out rather than raise on: a peer broke the marker first,
235 # or Windows refuses to rename a file whose holder still has it open. Poll again instead.
236 with suppress(OSError):
237 # A dead or recycled owner is reclaimed at once; a live owner past its lease duration is superseded on the
238 # schedule every contender agreed to.
239 if owner_is_stale(owner.pid, owner.hostname, owner.start):
240 break_lock_file(self.lock_file, mtime, ino)
241 return
242 if time.time() - mtime >= self._lease_duration:
243 break_lock_file(self.lock_file, mtime, ino)
244
245 def _read_peer(self) -> tuple[OwnerRecord, float, int] | None:
246 with suppress(OSError, ValueError):
247 content, mtime, ino = _read_lock_file(self.lock_file)
248 if (owner := parse_marker(content)) is not None:
249 return owner, mtime, ino
250 return None
251
252 def _start_heartbeat(self, claim: _LeaseClaim, fd: int, identity: tuple[int, int], token: str) -> None:
253 # The thread watches the event it was handed rather than whatever the claim names later: a heartbeat that
254 # outlives its join timeout would otherwise adopt the next acquisition's event and never stop.
255 stop = Event()
256 thread = Thread(
257 target=self._refresh_until_stopped,
258 args=(claim, fd, identity, token, stop),
259 name=f"filelock-lease-{os.getpid()}",
260 daemon=True,
261 )
262 # Record the heartbeat before starting the thread so a release racing this acquire on a shared,
263 # non-thread-local claim always sees it and sets the stop event; the thread then exits at its first wait
264 # instead of outliving the release. A start that raises leaves the unstarted thread for _stop_heartbeat.
265 claim.heartbeat = _Heartbeat(thread, stop)
266 thread.start()
267
268 def _stop_heartbeat(self) -> None:
269 claim = self._claim
270 if (heartbeat := claim.heartbeat) is None:
271 return
272 heartbeat.stop.set()
273 claim.heartbeat = None
274 # thread.ident is None until start() runs: a heartbeat recorded before its thread started (a start that
275 # raised, or a release racing acquire on a shared claim) has nothing to join, and the stop above makes it
276 # exit at once. on_compromise runs on the heartbeat thread and may release the lease, landing back here.
277 if heartbeat.thread.ident is not None and heartbeat.thread is not current_thread():
278 heartbeat.thread.join(timeout=self._heartbeat_interval)
279
280 def _refresh_until_stopped(
281 self,
282 claim: _LeaseClaim,
283 fd: int,
284 identity: tuple[int, int],
285 token: str,
286 stop: Event,
287 ) -> None:
288 # The loop ends at the first loss of the claim, so the holder hears about it once. A transient filesystem
289 # error (ESTALE / EIO on the NFS-style filesystems a lease targets) is not a loss: retry rather than raise a
290 # false compromise. Report the claim unrefreshable only once failures have run long enough that a contender
291 # could take it before the next success would land, a margin before the marker actually ages out, the way
292 # restic declares a lock unrefreshable ahead of its stale time.
293 last_success = time.monotonic()
294 while not stop.wait(self._heartbeat_interval):
295 outcome, error = self._refresh_claim(claim, fd, identity, token)
296 if outcome == "lost":
297 return
298 if outcome == "ok":
299 last_success = time.monotonic()
300 elif time.monotonic() - last_success >= self._lease_duration - self._heartbeat_interval:
301 self._report_compromise(claim, "refresh-failed", error, token)
302 return
303
304 def _refresh_claim(
305 self,
306 claim: _LeaseClaim,
307 fd: int,
308 identity: tuple[int, int],
309 token: str,
310 ) -> tuple[_RefreshOutcome, OSError | None]:
311 try:
312 st = os.lstat(self.lock_file)
313 except FileNotFoundError as error:
314 self._report_compromise(claim, "marker-missing", error, token)
315 return "lost", None
316 except OSError as error:
317 return "transient", error
318 # A peer that took the expired claim replaced the marker, so the pathname now names its inode, not ours.
319 if (st.st_dev, st.st_ino) != identity:
320 self._report_compromise(claim, "owner-changed", None, token)
321 return "lost", None
322 try:
323 touch(self.lock_file, fd=fd)
324 except OSError as error:
325 return "transient", error
326 return "ok", None
327
328 def _report_compromise(
329 self,
330 claim: _LeaseClaim,
331 reason: CompromiseReason,
332 error: OSError | None,
333 token: str,
334 ) -> None:
335 # Record it on the claim this heartbeat serves, not on self._claim: a thread-local claim read from the
336 # heartbeat thread is a different, empty one, so the holder would never see the loss it is being told about.
337 # The token is the one this thread published, not claim.token, which a release may already have cleared.
338 claim.compromise = LeaseCompromise(lock_file=self.lock_file, token=token, reason=reason, error=error)
339 if self._on_compromise is not None:
340 self._on_compromise(claim.compromise)
341
342
343 __all__ = [
344 "CompromiseReason",
345 "LeaseCompromise",
346 "SoftFileLease",
347 ]