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