cli-svckit 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli_svckit/__init__.py +75 -0
- cli_svckit/contract/__init__.py +47 -0
- cli_svckit/contract/argparse_cli.py +37 -0
- cli_svckit/contract/client.py +290 -0
- cli_svckit/contract/discovery.py +76 -0
- cli_svckit/contract/envelope.py +338 -0
- cli_svckit/contract/schemas/complete.json +126 -0
- cli_svckit/contract/schemas/describe.json +137 -0
- cli_svckit/contract/schemas/doctor.json +87 -0
- cli_svckit/contract/schemas/envelope.json +133 -0
- cli_svckit/contract/schemas/health.json +75 -0
- cli_svckit/contract/schemas/install.json +102 -0
- cli_svckit/contract/schemas/lease.json +114 -0
- cli_svckit/contract/schemas/prepare.json +89 -0
- cli_svckit/contract/server.py +165 -0
- cli_svckit/contract/typer_cli.py +36 -0
- cli_svckit/coord/__init__.py +1 -0
- cli_svckit/coord/controller.py +353 -0
- cli_svckit/coord/lease.py +439 -0
- cli_svckit/coord/participant.py +227 -0
- cli_svckit/coord/watch.py +387 -0
- cli_svckit/doctor.py +125 -0
- cli_svckit/health.py +149 -0
- cli_svckit/procs.py +139 -0
- cli_svckit/py.typed +0 -0
- cli_svckit/rcfile.py +336 -0
- cli_svckit/receipts.py +59 -0
- cli_svckit/testing.py +448 -0
- cli_svckit-0.1.2.dist-info/METADATA +151 -0
- cli_svckit-0.1.2.dist-info/RECORD +32 -0
- cli_svckit-0.1.2.dist-info/WHEEL +4 -0
- cli_svckit-0.1.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Durable lease directory: one JSON file per active operation, tombstones in ``done/``.
|
|
2
|
+
|
|
3
|
+
A controller writes ``<dir>/<op_id>.json`` before it restarts or updates anything; participant daemons watch the
|
|
4
|
+
directory and quiesce while a matching lease is active. When the operation ends the file is rewritten with phase
|
|
5
|
+
``complete`` and moved to ``<dir>/done/<op_id>.json`` (a tombstone, kept 24 h). Leases past ``op.expires_at`` are
|
|
6
|
+
stale and count as inactive (fail open for a dead controller).
|
|
7
|
+
|
|
8
|
+
Trust: a lease counts only when the file is owned (``st_uid``) by our own uid or root, and its JSON ``owner_uid``
|
|
9
|
+
agrees with the file owner. Anything else, and any file that does not parse or has a newer format version, is
|
|
10
|
+
ignored (with one warning on stderr) but never deleted by a reader.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import dataclasses
|
|
17
|
+
import fcntl
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
import tempfile
|
|
23
|
+
import time
|
|
24
|
+
from collections.abc import Callable, Iterator
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from cli_svckit.contract.envelope import Op, SvcError
|
|
29
|
+
|
|
30
|
+
PHASES = ("prepare", "running", "complete")
|
|
31
|
+
LEASE_VERSION = 1
|
|
32
|
+
DONE_DIR = "done"
|
|
33
|
+
LOCK_FILE = ".lock"
|
|
34
|
+
TOMBSTONE_MAX_AGE_S = 86400.0
|
|
35
|
+
|
|
36
|
+
_OP_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _warn(msg: str) -> None:
|
|
40
|
+
"""Write one warning line to stderr (looked up at call time so tests can capture it)."""
|
|
41
|
+
print(f"cli_svckit: {msg}", file=sys.stderr, flush=True)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _check_op_id(op_id: str) -> str:
|
|
45
|
+
"""Return ``op_id`` when it is safe as a file name; raise ``SvcError("invalid")`` otherwise."""
|
|
46
|
+
if not isinstance(op_id, str) or not _OP_ID.match(op_id):
|
|
47
|
+
raise SvcError("invalid", f"bad op id for a lease file: {op_id!r}")
|
|
48
|
+
return op_id
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Lease:
|
|
53
|
+
"""One lease file as read from (or written to) the lease directory.
|
|
54
|
+
|
|
55
|
+
``op`` is the announced operation, ``phase`` one of ``PHASES`` and ``phase_at`` when it was entered.
|
|
56
|
+
``outcome`` and ``facts`` are set when the op completes. ``owner_uid`` is the uid that wrote the file and
|
|
57
|
+
``path`` where the file was found (the active file or its ``done/`` tombstone).
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
op: Op
|
|
61
|
+
phase: str
|
|
62
|
+
phase_at: float
|
|
63
|
+
outcome: str | None
|
|
64
|
+
facts: dict[str, Any] | None
|
|
65
|
+
owner_uid: int
|
|
66
|
+
path: str
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict[str, Any]:
|
|
69
|
+
"""Return the lease file JSON form (``path`` is not stored)."""
|
|
70
|
+
return {
|
|
71
|
+
"v": LEASE_VERSION,
|
|
72
|
+
"op": self.op.to_dict(),
|
|
73
|
+
"phase": self.phase,
|
|
74
|
+
"phase_at": self.phase_at,
|
|
75
|
+
"outcome": self.outcome,
|
|
76
|
+
"facts": None if self.facts is None else dict(self.facts),
|
|
77
|
+
"owner_uid": self.owner_uid,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def from_dict(cls, d: dict[str, Any], path: str = "") -> Lease:
|
|
82
|
+
"""Build a lease from its file JSON. Raises ``SvcError("invalid")`` or ``("incompatible")`` (``v`` > 1)."""
|
|
83
|
+
if not isinstance(d, dict):
|
|
84
|
+
raise SvcError("invalid", "lease must be a JSON object")
|
|
85
|
+
v = d.get("v")
|
|
86
|
+
if not isinstance(v, int) or isinstance(v, bool) or v < 1:
|
|
87
|
+
raise SvcError("invalid", f"lease has a bad format version: {v!r}")
|
|
88
|
+
if v > LEASE_VERSION:
|
|
89
|
+
raise SvcError("incompatible", f"lease format version {v} is newer than {LEASE_VERSION}")
|
|
90
|
+
phase = d.get("phase")
|
|
91
|
+
if phase not in PHASES:
|
|
92
|
+
raise SvcError("invalid", f"lease has an unknown phase: {phase!r}")
|
|
93
|
+
owner = d.get("owner_uid")
|
|
94
|
+
if not isinstance(owner, int) or isinstance(owner, bool) or owner < 0:
|
|
95
|
+
raise SvcError("invalid", "lease.owner_uid must be a non-negative integer")
|
|
96
|
+
outcome = d.get("outcome")
|
|
97
|
+
if outcome is not None and not isinstance(outcome, str):
|
|
98
|
+
raise SvcError("invalid", "lease.outcome must be a string or null")
|
|
99
|
+
facts = d.get("facts")
|
|
100
|
+
if facts is not None and not isinstance(facts, dict):
|
|
101
|
+
raise SvcError("invalid", "lease.facts must be an object or null")
|
|
102
|
+
try:
|
|
103
|
+
phase_at = float(d.get("phase_at") or 0.0)
|
|
104
|
+
except (TypeError, ValueError) as exc:
|
|
105
|
+
raise SvcError("invalid", f"lease.phase_at is malformed: {exc}") from exc
|
|
106
|
+
return cls(
|
|
107
|
+
op=Op.from_dict(d.get("op")), # type: ignore[arg-type]
|
|
108
|
+
phase=phase,
|
|
109
|
+
phase_at=phase_at,
|
|
110
|
+
outcome=outcome,
|
|
111
|
+
facts=facts,
|
|
112
|
+
owner_uid=owner,
|
|
113
|
+
path=path,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def is_active(self, now: float) -> bool:
|
|
117
|
+
"""Return True while the op is not complete and its lease has not expired at ``now``."""
|
|
118
|
+
return self.phase != "complete" and self.op.expires_at > now
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class LeaseDir:
|
|
122
|
+
"""A lease directory at ``path`` (mode 0700, files 0600, tombstones in ``done/``).
|
|
123
|
+
|
|
124
|
+
``uid`` is the uid whose leases we trust besides root (default: our effective uid). ``clock`` supplies
|
|
125
|
+
every timestamp, so tests can use a fake clock. Writes are atomic (temp file in the same directory, fsync,
|
|
126
|
+
``os.replace``); ``create`` and the other writers hold an ``flock`` on ``<path>/.lock``.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(self, path: str | os.PathLike[str], *, uid: int | None = None, clock: Callable[[], float] = time.time):
|
|
130
|
+
self.path = os.fspath(path)
|
|
131
|
+
self.uid = os.geteuid() if uid is None else uid
|
|
132
|
+
self.clock = clock
|
|
133
|
+
self._warned: set[tuple[str, str]] = set()
|
|
134
|
+
|
|
135
|
+
# -- paths -------------------------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def done_path(self) -> str:
|
|
139
|
+
"""The tombstone directory ``<path>/done``."""
|
|
140
|
+
return os.path.join(self.path, DONE_DIR)
|
|
141
|
+
|
|
142
|
+
def _active_file(self, op_id: str) -> str:
|
|
143
|
+
return os.path.join(self.path, f"{_check_op_id(op_id)}.json")
|
|
144
|
+
|
|
145
|
+
def _done_file(self, op_id: str) -> str:
|
|
146
|
+
return os.path.join(self.done_path, f"{_check_op_id(op_id)}.json")
|
|
147
|
+
|
|
148
|
+
def _trusted_uids(self) -> set[int]:
|
|
149
|
+
return {self.uid, 0}
|
|
150
|
+
|
|
151
|
+
# -- low-level io ------------------------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
def ensure(self) -> None:
|
|
154
|
+
"""Create the directory and ``done/`` if missing and make sure both are mode 0700."""
|
|
155
|
+
for d in (self.path, self.done_path):
|
|
156
|
+
old = os.umask(0o077)
|
|
157
|
+
try:
|
|
158
|
+
os.makedirs(d, mode=0o700, exist_ok=True)
|
|
159
|
+
finally:
|
|
160
|
+
os.umask(old)
|
|
161
|
+
os.chmod(d, 0o700)
|
|
162
|
+
|
|
163
|
+
@contextlib.contextmanager
|
|
164
|
+
def _locked(self) -> Iterator[None]:
|
|
165
|
+
"""Hold an exclusive ``flock`` on ``<path>/.lock`` for the duration of the block."""
|
|
166
|
+
self.ensure()
|
|
167
|
+
old = os.umask(0o077)
|
|
168
|
+
try:
|
|
169
|
+
fd = os.open(os.path.join(self.path, LOCK_FILE), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
170
|
+
finally:
|
|
171
|
+
os.umask(old)
|
|
172
|
+
try:
|
|
173
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
174
|
+
yield
|
|
175
|
+
finally:
|
|
176
|
+
with contextlib.suppress(OSError):
|
|
177
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
178
|
+
os.close(fd)
|
|
179
|
+
|
|
180
|
+
def _write(self, target: str, lease: Lease) -> None:
|
|
181
|
+
"""Atomically write ``lease`` to ``target``: temp file in the same dir, fsync, chmod 0600, os.replace."""
|
|
182
|
+
data = json.dumps(lease.to_dict(), sort_keys=True).encode("utf-8") + b"\n"
|
|
183
|
+
directory = os.path.dirname(target)
|
|
184
|
+
old = os.umask(0o077)
|
|
185
|
+
try:
|
|
186
|
+
fd, tmp = tempfile.mkstemp(prefix=".tmp-", suffix=".json", dir=directory)
|
|
187
|
+
finally:
|
|
188
|
+
os.umask(old)
|
|
189
|
+
try:
|
|
190
|
+
with os.fdopen(fd, "wb") as f:
|
|
191
|
+
f.write(data)
|
|
192
|
+
f.flush()
|
|
193
|
+
os.fsync(f.fileno())
|
|
194
|
+
os.chmod(tmp, 0o600)
|
|
195
|
+
os.replace(tmp, target)
|
|
196
|
+
except BaseException:
|
|
197
|
+
with contextlib.suppress(OSError):
|
|
198
|
+
os.unlink(tmp)
|
|
199
|
+
raise
|
|
200
|
+
_fsync_dir(directory)
|
|
201
|
+
|
|
202
|
+
def _warn_once(self, path: str, reason: str) -> None:
|
|
203
|
+
key = (path, reason)
|
|
204
|
+
if key not in self._warned:
|
|
205
|
+
self._warned.add(key)
|
|
206
|
+
_warn(f"ignoring lease file {path}: {reason}")
|
|
207
|
+
|
|
208
|
+
def _read(self, path: str) -> Lease | None:
|
|
209
|
+
"""Read and trust-check one lease file; return None (warning once) when it must be ignored."""
|
|
210
|
+
try:
|
|
211
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
212
|
+
except FileNotFoundError:
|
|
213
|
+
return None
|
|
214
|
+
except OSError as exc:
|
|
215
|
+
self._warn_once(path, f"cannot open ({exc.strerror})")
|
|
216
|
+
return None
|
|
217
|
+
try:
|
|
218
|
+
st = os.fstat(fd)
|
|
219
|
+
with os.fdopen(fd, "rb") as f:
|
|
220
|
+
fd = -1
|
|
221
|
+
raw = f.read()
|
|
222
|
+
finally:
|
|
223
|
+
if fd >= 0:
|
|
224
|
+
os.close(fd)
|
|
225
|
+
if st.st_uid not in self._trusted_uids():
|
|
226
|
+
self._warn_once(path, f"owned by uid {st.st_uid}, not {self.uid} or root")
|
|
227
|
+
return None
|
|
228
|
+
try:
|
|
229
|
+
lease = Lease.from_dict(json.loads(raw.decode("utf-8")), path)
|
|
230
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
231
|
+
self._warn_once(path, f"not valid JSON ({exc.__class__.__name__})")
|
|
232
|
+
return None
|
|
233
|
+
except SvcError as exc:
|
|
234
|
+
self._warn_once(path, exc.message)
|
|
235
|
+
return None
|
|
236
|
+
if lease.owner_uid != st.st_uid:
|
|
237
|
+
self._warn_once(path, f"owner_uid {lease.owner_uid} does not match file owner {st.st_uid}")
|
|
238
|
+
return None
|
|
239
|
+
return lease
|
|
240
|
+
|
|
241
|
+
def _scan(self, directory: str) -> list[Lease]:
|
|
242
|
+
"""Return the trusted, parseable leases in ``directory`` (temp and hidden files skipped)."""
|
|
243
|
+
try:
|
|
244
|
+
names = sorted(os.listdir(directory))
|
|
245
|
+
except FileNotFoundError:
|
|
246
|
+
return []
|
|
247
|
+
out: list[Lease] = []
|
|
248
|
+
for name in names:
|
|
249
|
+
if name.startswith(".") or not name.endswith(".json"):
|
|
250
|
+
continue
|
|
251
|
+
lease = self._read(os.path.join(directory, name))
|
|
252
|
+
if lease is not None and lease.op.id == name[: -len(".json")]:
|
|
253
|
+
out.append(lease)
|
|
254
|
+
elif lease is not None:
|
|
255
|
+
self._warn_once(lease.path, f"op id {lease.op.id!r} does not match the file name")
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
def _tombstone(self, lease: Lease, outcome: str | None, facts: dict[str, Any] | None) -> Lease:
|
|
259
|
+
"""Rewrite ``lease`` as complete in place, then move it to ``done/``. Caller holds the lock."""
|
|
260
|
+
done = dataclasses.replace(
|
|
261
|
+
lease,
|
|
262
|
+
phase="complete",
|
|
263
|
+
phase_at=self.clock(),
|
|
264
|
+
outcome=outcome,
|
|
265
|
+
facts=None if facts is None else dict(facts),
|
|
266
|
+
owner_uid=os.geteuid(),
|
|
267
|
+
)
|
|
268
|
+
self._write(lease.path, done)
|
|
269
|
+
target = self._done_file(lease.op.id)
|
|
270
|
+
os.replace(lease.path, target)
|
|
271
|
+
_fsync_dir(self.done_path)
|
|
272
|
+
_fsync_dir(self.path)
|
|
273
|
+
return dataclasses.replace(done, path=target)
|
|
274
|
+
|
|
275
|
+
# -- public api --------------------------------------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
def create(self, op: Op, phase: str = "prepare") -> Lease:
|
|
278
|
+
"""Write a new lease for ``op`` and return it.
|
|
279
|
+
|
|
280
|
+
Idempotent: when an active lease for the same op id already exists it is returned unchanged. Refuses
|
|
281
|
+
(``SvcError("invalid")``) an op whose ``expires_at`` is not in the future, a phase other than prepare or
|
|
282
|
+
running, an op id that already has a tombstone, and an existing file it cannot read or trust.
|
|
283
|
+
"""
|
|
284
|
+
_check_op_id(op.id)
|
|
285
|
+
if phase not in PHASES or phase == "complete":
|
|
286
|
+
raise SvcError("invalid", f"a new lease must start in phase prepare or running, not {phase!r}")
|
|
287
|
+
with self._locked():
|
|
288
|
+
now = self.clock()
|
|
289
|
+
path = self._active_file(op.id)
|
|
290
|
+
if os.path.lexists(path):
|
|
291
|
+
existing = self._read(path)
|
|
292
|
+
if existing is None:
|
|
293
|
+
raise SvcError("invalid", f"a lease file for {op.id} exists but cannot be trusted or read")
|
|
294
|
+
if existing.is_active(now):
|
|
295
|
+
return existing
|
|
296
|
+
if os.path.lexists(self._done_file(op.id)):
|
|
297
|
+
raise SvcError("invalid", f"op {op.id} has already completed")
|
|
298
|
+
if op.expires_at <= now:
|
|
299
|
+
raise SvcError("invalid", f"op {op.id} expires_at {op.expires_at} is not after now ({now})")
|
|
300
|
+
lease = Lease(
|
|
301
|
+
op=dataclasses.replace(op, lease=path),
|
|
302
|
+
phase=phase,
|
|
303
|
+
phase_at=now,
|
|
304
|
+
outcome=None,
|
|
305
|
+
facts=None,
|
|
306
|
+
owner_uid=os.geteuid(),
|
|
307
|
+
path=path,
|
|
308
|
+
)
|
|
309
|
+
self._write(path, lease)
|
|
310
|
+
return lease
|
|
311
|
+
|
|
312
|
+
def get(self, op_id: str) -> Lease | None:
|
|
313
|
+
"""Return the lease for ``op_id``: the active file if present, else its tombstone, else None.
|
|
314
|
+
|
|
315
|
+
Untrusted or unreadable files count as absent. Expired leases are returned too (check ``is_active``).
|
|
316
|
+
"""
|
|
317
|
+
lease = self._read(self._active_file(op_id))
|
|
318
|
+
if lease is None:
|
|
319
|
+
lease = self._read(self._done_file(op_id))
|
|
320
|
+
return lease
|
|
321
|
+
|
|
322
|
+
def set_phase(
|
|
323
|
+
self,
|
|
324
|
+
op_id: str,
|
|
325
|
+
phase: str,
|
|
326
|
+
*,
|
|
327
|
+
outcome: str | None = None,
|
|
328
|
+
facts: dict[str, Any] | None = None,
|
|
329
|
+
) -> Lease:
|
|
330
|
+
"""Move the active lease ``op_id`` to ``phase`` (``complete`` behaves like :meth:`complete`).
|
|
331
|
+
|
|
332
|
+
``outcome``/``facts`` replace the stored ones when given. Raises ``SvcError("invalid")`` when there is no
|
|
333
|
+
active lease file for the op or the phase is unknown.
|
|
334
|
+
"""
|
|
335
|
+
if phase not in PHASES:
|
|
336
|
+
raise SvcError("invalid", f"unknown lease phase {phase!r}")
|
|
337
|
+
with self._locked():
|
|
338
|
+
lease = self._read(self._active_file(op_id))
|
|
339
|
+
if lease is None or lease.phase == "complete":
|
|
340
|
+
raise SvcError("invalid", f"no active lease for {op_id}")
|
|
341
|
+
new_outcome = lease.outcome if outcome is None else outcome
|
|
342
|
+
new_facts = lease.facts if facts is None else facts
|
|
343
|
+
if phase == "complete":
|
|
344
|
+
return self._tombstone(lease, new_outcome, new_facts)
|
|
345
|
+
updated = dataclasses.replace(
|
|
346
|
+
lease,
|
|
347
|
+
phase=phase,
|
|
348
|
+
phase_at=self.clock(),
|
|
349
|
+
outcome=new_outcome,
|
|
350
|
+
facts=None if new_facts is None else dict(new_facts),
|
|
351
|
+
)
|
|
352
|
+
self._write(lease.path, updated)
|
|
353
|
+
return updated
|
|
354
|
+
|
|
355
|
+
def complete(self, op_id: str, outcome: str, facts: dict[str, Any] | None) -> Lease:
|
|
356
|
+
"""End ``op_id``: write phase complete with ``outcome``/``facts``, then move it to ``done/<op_id>.json``.
|
|
357
|
+
|
|
358
|
+
Calling it again after the op is tombstoned returns the tombstone unchanged. Raises
|
|
359
|
+
``SvcError("invalid")`` when the op has neither an active lease nor a tombstone.
|
|
360
|
+
"""
|
|
361
|
+
with self._locked():
|
|
362
|
+
lease = self._read(self._active_file(op_id))
|
|
363
|
+
if lease is None:
|
|
364
|
+
done = self._read(self._done_file(op_id))
|
|
365
|
+
if done is not None:
|
|
366
|
+
return done
|
|
367
|
+
raise SvcError("invalid", f"no lease for {op_id}")
|
|
368
|
+
return self._tombstone(lease, outcome, facts)
|
|
369
|
+
|
|
370
|
+
def clear(self, op_id: str, reason: str = "") -> Lease | None:
|
|
371
|
+
"""Human end of a stuck lease: tombstone it with outcome ``aborted`` and ``cleared_by_human`` facts.
|
|
372
|
+
|
|
373
|
+
Works on expired leases too. Returns the tombstone, the existing tombstone when the op had already ended,
|
|
374
|
+
or None when there is no such lease.
|
|
375
|
+
"""
|
|
376
|
+
with self._locked():
|
|
377
|
+
lease = self._read(self._active_file(op_id))
|
|
378
|
+
if lease is None:
|
|
379
|
+
return self._read(self._done_file(op_id))
|
|
380
|
+
return self._tombstone(lease, "aborted", {"cleared_by_human": True, "reason": reason})
|
|
381
|
+
|
|
382
|
+
def list_active(self, now: float | None = None) -> list[Lease]:
|
|
383
|
+
"""Return the trusted leases that are active at ``now`` (default: the clock), oldest first."""
|
|
384
|
+
t = self.clock() if now is None else now
|
|
385
|
+
active = [lease for lease in self._scan(self.path) if lease.is_active(t)]
|
|
386
|
+
return sorted(active, key=lambda le: (le.op.started_at, le.phase_at, le.op.id))
|
|
387
|
+
|
|
388
|
+
def tombstones(self, since: float = 0.0) -> list[Lease]:
|
|
389
|
+
"""Return the trusted tombstones in ``done/`` whose ``phase_at`` >= ``since``, oldest first."""
|
|
390
|
+
done = [lease for lease in self._scan(self.done_path) if lease.phase_at >= since]
|
|
391
|
+
return sorted(done, key=lambda le: (le.phase_at, le.op.id))
|
|
392
|
+
|
|
393
|
+
def expire_stale(self) -> list[str]:
|
|
394
|
+
"""Move leases whose ``expires_at`` has passed to ``done/`` with outcome ``expired``; return their ids.
|
|
395
|
+
|
|
396
|
+
Leases already in phase complete but left in the active directory (a writer died between the rewrite
|
|
397
|
+
and the move) are moved too, keeping their outcome.
|
|
398
|
+
"""
|
|
399
|
+
moved: list[str] = []
|
|
400
|
+
with self._locked():
|
|
401
|
+
now = self.clock()
|
|
402
|
+
for lease in self._scan(self.path):
|
|
403
|
+
if lease.phase == "complete":
|
|
404
|
+
target = self._done_file(lease.op.id)
|
|
405
|
+
os.replace(lease.path, target)
|
|
406
|
+
moved.append(lease.op.id)
|
|
407
|
+
elif lease.op.expires_at <= now:
|
|
408
|
+
self._tombstone(lease, "expired", lease.facts)
|
|
409
|
+
moved.append(lease.op.id)
|
|
410
|
+
if moved:
|
|
411
|
+
_fsync_dir(self.done_path)
|
|
412
|
+
_fsync_dir(self.path)
|
|
413
|
+
return moved
|
|
414
|
+
|
|
415
|
+
def prune_tombstones(self, max_age_s: float = TOMBSTONE_MAX_AGE_S) -> list[str]:
|
|
416
|
+
"""Delete trusted tombstones whose ``phase_at`` is more than ``max_age_s`` ago; return their op ids."""
|
|
417
|
+
pruned: list[str] = []
|
|
418
|
+
with self._locked():
|
|
419
|
+
cutoff = self.clock() - max_age_s
|
|
420
|
+
for lease in self._scan(self.done_path):
|
|
421
|
+
if lease.phase_at < cutoff:
|
|
422
|
+
with contextlib.suppress(FileNotFoundError):
|
|
423
|
+
os.unlink(lease.path)
|
|
424
|
+
pruned.append(lease.op.id)
|
|
425
|
+
return pruned
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _fsync_dir(directory: str) -> None:
|
|
429
|
+
"""Flush a directory entry change to disk (best effort: some filesystems refuse to fsync directories)."""
|
|
430
|
+
try:
|
|
431
|
+
fd = os.open(directory, os.O_RDONLY)
|
|
432
|
+
except OSError:
|
|
433
|
+
return
|
|
434
|
+
try:
|
|
435
|
+
os.fsync(fd)
|
|
436
|
+
except OSError:
|
|
437
|
+
pass
|
|
438
|
+
finally:
|
|
439
|
+
os.close(fd)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Participant side of lease coordination: which ops concern us, and firing quiesce/resume callbacks once.
|
|
2
|
+
|
|
3
|
+
A participant daemon builds a :class:`Quiescer` over the shared :class:`~cli_svckit.coord.lease.LeaseDir`, calls
|
|
4
|
+
:meth:`Quiescer.catch_up` on start and :meth:`Quiescer.refresh` on every watcher event. ``on_prepare(lease)`` runs
|
|
5
|
+
once per matching op that becomes active, ``on_complete(lease)`` once per such op when it ends (tombstone appears,
|
|
6
|
+
or its lease expires: fail open for a dead controller).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import dataclasses
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import traceback
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from cli_svckit.contract.envelope import Op, matches
|
|
25
|
+
from cli_svckit.coord.lease import Lease, LeaseDir
|
|
26
|
+
|
|
27
|
+
STATE_VERSION = 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Interest:
|
|
32
|
+
"""The ops a participant cares about: ``kinds`` and ``services`` are shell-style globs.
|
|
33
|
+
|
|
34
|
+
An op matches when its kind matches one of ``kinds`` and at least one of its targets matches one of
|
|
35
|
+
``services``.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
kinds: list[str] = field(default_factory=list)
|
|
39
|
+
services: list[str] = field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
def matches(self, op: Op) -> bool:
|
|
42
|
+
"""Return True when ``op`` concerns this participant."""
|
|
43
|
+
return matches(op.kind, self.kinds) and any(matches(t, self.services) for t in op.targets)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def active_ops(lease_dir: LeaseDir, interest: Interest, now: float | None = None) -> list[Lease]:
|
|
47
|
+
"""Return the active leases in ``lease_dir`` (at ``now``, default the dir's clock) that match ``interest``."""
|
|
48
|
+
return [lease for lease in lease_dir.list_active(now) if interest.matches(lease.op)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Quiescer:
|
|
52
|
+
"""Turns lease-directory changes into one ``on_prepare`` and one ``on_complete`` call per matching op.
|
|
53
|
+
|
|
54
|
+
The op ids already fired are kept in memory and, when ``state_file`` is given, persisted there (JSON,
|
|
55
|
+
written atomically) so a restarted daemon does not fire again. Tombstones are only considered when they are
|
|
56
|
+
newer than the marker: the stored marker from ``state_file``, else the moment this Quiescer was built, so old
|
|
57
|
+
history never fires. Thread-safe; callback exceptions are reported on stderr and do not stop other callbacks.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
lease_dir: LeaseDir,
|
|
63
|
+
interest: Interest,
|
|
64
|
+
on_prepare: Callable[[Lease], Any],
|
|
65
|
+
on_complete: Callable[[Lease], Any],
|
|
66
|
+
*,
|
|
67
|
+
state_file: str | os.PathLike[str] | None = None,
|
|
68
|
+
clock: Callable[[], float] = time.time,
|
|
69
|
+
):
|
|
70
|
+
self.lease_dir = lease_dir
|
|
71
|
+
self.interest = interest
|
|
72
|
+
self.on_prepare = on_prepare
|
|
73
|
+
self.on_complete = on_complete
|
|
74
|
+
self.state_file = None if state_file is None else os.fspath(state_file)
|
|
75
|
+
self.clock = clock
|
|
76
|
+
self._lock = threading.RLock()
|
|
77
|
+
self._prepared: set[str] = set()
|
|
78
|
+
self._completed: set[str] = set()
|
|
79
|
+
self._seen: dict[str, Lease] = {}
|
|
80
|
+
stored = self._load()
|
|
81
|
+
self._marker: float = self.clock() if stored is None else stored
|
|
82
|
+
self._baseline = self._marker
|
|
83
|
+
|
|
84
|
+
# -- state -------------------------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def prepared(self) -> frozenset[str]:
|
|
88
|
+
"""Op ids that got ``on_prepare`` and are not finished yet."""
|
|
89
|
+
with self._lock:
|
|
90
|
+
return frozenset(self._prepared)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def completed(self) -> frozenset[str]:
|
|
94
|
+
"""Op ids that got ``on_complete`` (kept until their tombstone is pruned)."""
|
|
95
|
+
with self._lock:
|
|
96
|
+
return frozenset(self._completed)
|
|
97
|
+
|
|
98
|
+
def _load(self) -> float | None:
|
|
99
|
+
"""Read ``state_file``; return its marker, or None when there is no usable state."""
|
|
100
|
+
if self.state_file is None:
|
|
101
|
+
return None
|
|
102
|
+
try:
|
|
103
|
+
with open(self.state_file, encoding="utf-8") as f:
|
|
104
|
+
data = json.load(f)
|
|
105
|
+
except FileNotFoundError:
|
|
106
|
+
return None
|
|
107
|
+
except (OSError, ValueError) as exc:
|
|
108
|
+
print(f"cli_svckit: ignoring quiescer state {self.state_file}: {exc}", file=sys.stderr, flush=True)
|
|
109
|
+
return None
|
|
110
|
+
if not isinstance(data, dict) or data.get("v") != STATE_VERSION:
|
|
111
|
+
print(f"cli_svckit: ignoring quiescer state {self.state_file}: unknown format", file=sys.stderr)
|
|
112
|
+
return None
|
|
113
|
+
self._prepared = {str(x) for x in data.get("prepared") or [] if isinstance(x, str)}
|
|
114
|
+
self._completed = {str(x) for x in data.get("completed") or [] if isinstance(x, str)}
|
|
115
|
+
marker = data.get("marker")
|
|
116
|
+
if isinstance(marker, (int, float)) and not isinstance(marker, bool):
|
|
117
|
+
return float(marker)
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
def _save(self) -> None:
|
|
121
|
+
"""Write the state atomically to ``state_file`` (no-op without one; failures are reported, not raised)."""
|
|
122
|
+
if self.state_file is None:
|
|
123
|
+
return
|
|
124
|
+
data = {
|
|
125
|
+
"v": STATE_VERSION,
|
|
126
|
+
"marker": self._marker,
|
|
127
|
+
"prepared": sorted(self._prepared),
|
|
128
|
+
"completed": sorted(self._completed),
|
|
129
|
+
}
|
|
130
|
+
directory = os.path.dirname(os.path.abspath(self.state_file))
|
|
131
|
+
tmp = None
|
|
132
|
+
try:
|
|
133
|
+
os.makedirs(directory, mode=0o700, exist_ok=True)
|
|
134
|
+
fd, tmp = tempfile.mkstemp(prefix=".tmp-", suffix=".json", dir=directory)
|
|
135
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
136
|
+
json.dump(data, f, sort_keys=True)
|
|
137
|
+
f.write("\n")
|
|
138
|
+
f.flush()
|
|
139
|
+
os.fsync(f.fileno())
|
|
140
|
+
os.chmod(tmp, 0o600)
|
|
141
|
+
os.replace(tmp, self.state_file)
|
|
142
|
+
tmp = None
|
|
143
|
+
except OSError as exc:
|
|
144
|
+
print(f"cli_svckit: cannot save quiescer state {self.state_file}: {exc}", file=sys.stderr, flush=True)
|
|
145
|
+
finally:
|
|
146
|
+
if tmp is not None:
|
|
147
|
+
with contextlib.suppress(OSError):
|
|
148
|
+
os.unlink(tmp)
|
|
149
|
+
|
|
150
|
+
# -- firing ------------------------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
def _fire(self, callback: Callable[[Lease], Any], lease: Lease, what: str) -> None:
|
|
153
|
+
try:
|
|
154
|
+
callback(lease)
|
|
155
|
+
except Exception:
|
|
156
|
+
print(f"cli_svckit: {what} callback failed for {lease.op.id}:", file=sys.stderr)
|
|
157
|
+
traceback.print_exc(file=sys.stderr)
|
|
158
|
+
|
|
159
|
+
def _prepare(self, lease: Lease) -> None:
|
|
160
|
+
self._prepared.add(lease.op.id)
|
|
161
|
+
self._seen[lease.op.id] = lease
|
|
162
|
+
self._fire(self.on_prepare, lease, "on_prepare")
|
|
163
|
+
|
|
164
|
+
def _complete(self, lease: Lease) -> None:
|
|
165
|
+
self._prepared.discard(lease.op.id)
|
|
166
|
+
self._completed.add(lease.op.id)
|
|
167
|
+
self._seen.pop(lease.op.id, None)
|
|
168
|
+
self._fire(self.on_complete, lease, "on_complete")
|
|
169
|
+
|
|
170
|
+
def refresh(self) -> None:
|
|
171
|
+
"""Re-read the lease directory and fire the callbacks that are due. Call it on every watcher event.
|
|
172
|
+
|
|
173
|
+
Newly active matching ops get ``on_prepare``. Matching tombstones get ``on_complete`` when we prepared
|
|
174
|
+
for them, or ``on_prepare`` then ``on_complete`` when the op came and went between two refreshes (only
|
|
175
|
+
for tombstones newer than the marker). A prepared op whose lease expired without a tombstone gets
|
|
176
|
+
``on_complete`` with outcome ``expired``.
|
|
177
|
+
"""
|
|
178
|
+
with self._lock:
|
|
179
|
+
before = (frozenset(self._prepared), frozenset(self._completed), self._marker)
|
|
180
|
+
now = self.clock()
|
|
181
|
+
active = active_ops(self.lease_dir, self.interest, now)
|
|
182
|
+
for lease in active:
|
|
183
|
+
oid = lease.op.id
|
|
184
|
+
if oid not in self._prepared and oid not in self._completed:
|
|
185
|
+
self._prepare(lease)
|
|
186
|
+
else:
|
|
187
|
+
self._seen[oid] = lease
|
|
188
|
+
tombs = [t for t in self.lease_dir.tombstones() if self.interest.matches(t.op)]
|
|
189
|
+
tomb_ids = {t.op.id for t in tombs}
|
|
190
|
+
for tomb in tombs:
|
|
191
|
+
oid = tomb.op.id
|
|
192
|
+
if oid in self._completed:
|
|
193
|
+
continue
|
|
194
|
+
if oid in self._prepared:
|
|
195
|
+
self._complete(tomb)
|
|
196
|
+
elif tomb.phase_at > self._baseline:
|
|
197
|
+
self._prepare(tomb)
|
|
198
|
+
self._complete(tomb)
|
|
199
|
+
else:
|
|
200
|
+
continue
|
|
201
|
+
self._marker = max(self._marker, tomb.phase_at)
|
|
202
|
+
active_ids = {lease.op.id for lease in active}
|
|
203
|
+
for oid in sorted(self._prepared - active_ids - tomb_ids):
|
|
204
|
+
current = self.lease_dir.get(oid)
|
|
205
|
+
if current is not None and current.phase != "complete":
|
|
206
|
+
# Still there but no longer active: expired (fail open).
|
|
207
|
+
self._complete(dataclasses.replace(current, outcome="expired"))
|
|
208
|
+
elif current is None:
|
|
209
|
+
last = self._seen.get(oid)
|
|
210
|
+
if last is not None:
|
|
211
|
+
# The lease file vanished (removed by hand): resume rather than stay quiesced.
|
|
212
|
+
self._complete(dataclasses.replace(last, outcome="missing"))
|
|
213
|
+
else:
|
|
214
|
+
self._prepared.discard(oid)
|
|
215
|
+
# Forget completed ids whose files are gone for good (tombstone pruned), so the state stays small.
|
|
216
|
+
for oid in sorted(self._completed - tomb_ids):
|
|
217
|
+
if self.lease_dir.get(oid) is None:
|
|
218
|
+
self._completed.discard(oid)
|
|
219
|
+
if (frozenset(self._prepared), frozenset(self._completed), self._marker) != before:
|
|
220
|
+
self._save()
|
|
221
|
+
|
|
222
|
+
def catch_up(self) -> None:
|
|
223
|
+
"""Run once on daemon start: fire for ops already active and for tombstones newer than the stored marker.
|
|
224
|
+
|
|
225
|
+
Ids recorded in ``state_file`` as already fired are not fired again.
|
|
226
|
+
"""
|
|
227
|
+
self.refresh()
|