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,387 @@
|
|
|
1
|
+
"""Directory watcher used by participant daemons to notice lease changes quickly.
|
|
2
|
+
|
|
3
|
+
``LeaseWatcher`` watches a *directory* (never a single file, because atomic replace swaps inodes) and calls a
|
|
4
|
+
callback whenever something in it changes. It uses kqueue on macOS/BSD, inotify (via ctypes) on Linux and falls
|
|
5
|
+
back to periodic snapshots everywhere else.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import ctypes
|
|
12
|
+
import os
|
|
13
|
+
import select
|
|
14
|
+
import stat
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
|
|
20
|
+
__all__ = ["LeaseWatcher"]
|
|
21
|
+
|
|
22
|
+
# inotify constants (linux/inotify.h)
|
|
23
|
+
_IN_ATTRIB = 0x00000004
|
|
24
|
+
_IN_CLOSE_WRITE = 0x00000008
|
|
25
|
+
_IN_MOVED_FROM = 0x00000040
|
|
26
|
+
_IN_MOVED_TO = 0x00000080
|
|
27
|
+
_IN_CREATE = 0x00000100
|
|
28
|
+
_IN_DELETE = 0x00000200
|
|
29
|
+
_IN_DELETE_SELF = 0x00000400
|
|
30
|
+
_IN_MOVE_SELF = 0x00000800
|
|
31
|
+
_IN_IGNORED = 0x00008000
|
|
32
|
+
_IN_NONBLOCK = os.O_NONBLOCK
|
|
33
|
+
_IN_CLOEXEC = getattr(os, "O_CLOEXEC", 0x80000)
|
|
34
|
+
_IN_MASK = (
|
|
35
|
+
_IN_CREATE | _IN_DELETE | _IN_MOVED_TO | _IN_MOVED_FROM | _IN_CLOSE_WRITE | _IN_ATTRIB | _IN_DELETE_SELF
|
|
36
|
+
| _IN_MOVE_SELF
|
|
37
|
+
) # fmt: skip
|
|
38
|
+
_IN_GONE = _IN_DELETE_SELF | _IN_MOVE_SELF | _IN_IGNORED
|
|
39
|
+
|
|
40
|
+
# Wait results shared by all backends.
|
|
41
|
+
_EVENT = "event"
|
|
42
|
+
_GONE = "gone"
|
|
43
|
+
_STOP = "stop"
|
|
44
|
+
_TIMEOUT = "timeout"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _Backend:
|
|
48
|
+
"""One way of waiting for directory changes. ``wait`` returns _EVENT, _GONE, _STOP or _TIMEOUT."""
|
|
49
|
+
|
|
50
|
+
name = ""
|
|
51
|
+
|
|
52
|
+
def __init__(self, path: str, stop_fd: int, poll_interval: float) -> None:
|
|
53
|
+
self.path = path
|
|
54
|
+
self.stop_fd = stop_fd
|
|
55
|
+
self.poll_interval = poll_interval
|
|
56
|
+
|
|
57
|
+
def arm(self) -> bool:
|
|
58
|
+
"""Start watching the directory; False when it does not exist (yet)."""
|
|
59
|
+
raise NotImplementedError
|
|
60
|
+
|
|
61
|
+
def wait(self, timeout: float | None) -> str:
|
|
62
|
+
"""Block until something happens or ``timeout`` seconds pass."""
|
|
63
|
+
raise NotImplementedError
|
|
64
|
+
|
|
65
|
+
def disarm(self) -> None:
|
|
66
|
+
"""Release the per-directory resources (the watcher may arm again later)."""
|
|
67
|
+
|
|
68
|
+
def close(self) -> None:
|
|
69
|
+
"""Release everything."""
|
|
70
|
+
self.disarm()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _KqueueBackend(_Backend):
|
|
74
|
+
name = "kqueue"
|
|
75
|
+
|
|
76
|
+
def __init__(self, path: str, stop_fd: int, poll_interval: float) -> None:
|
|
77
|
+
super().__init__(path, stop_fd, poll_interval)
|
|
78
|
+
self._kq = select.kqueue()
|
|
79
|
+
self._dir_fd: int | None = None
|
|
80
|
+
stop_ev = select.kevent(
|
|
81
|
+
stop_fd, select.KQ_FILTER_READ, select.KQ_EV_ADD | select.KQ_EV_ENABLE | select.KQ_EV_CLEAR
|
|
82
|
+
)
|
|
83
|
+
self._kq.control([stop_ev], 0, 0)
|
|
84
|
+
|
|
85
|
+
def arm(self) -> bool:
|
|
86
|
+
flags = getattr(os, "O_EVTONLY", None) or getattr(os, "O_RDONLY") # noqa: B009
|
|
87
|
+
try:
|
|
88
|
+
fd = os.open(self.path, flags | getattr(os, "O_CLOEXEC", 0))
|
|
89
|
+
except OSError:
|
|
90
|
+
return False
|
|
91
|
+
try:
|
|
92
|
+
if not stat.S_ISDIR(os.fstat(fd).st_mode):
|
|
93
|
+
os.close(fd)
|
|
94
|
+
return False
|
|
95
|
+
fflags = (
|
|
96
|
+
select.KQ_NOTE_WRITE | select.KQ_NOTE_DELETE | select.KQ_NOTE_RENAME | select.KQ_NOTE_EXTEND
|
|
97
|
+
| select.KQ_NOTE_ATTRIB | select.KQ_NOTE_REVOKE
|
|
98
|
+
) # fmt: skip
|
|
99
|
+
ev = select.kevent(
|
|
100
|
+
fd, select.KQ_FILTER_VNODE, select.KQ_EV_ADD | select.KQ_EV_ENABLE | select.KQ_EV_CLEAR, fflags
|
|
101
|
+
)
|
|
102
|
+
self._kq.control([ev], 0, 0)
|
|
103
|
+
except OSError:
|
|
104
|
+
with contextlib.suppress(OSError):
|
|
105
|
+
os.close(fd)
|
|
106
|
+
return False
|
|
107
|
+
self._dir_fd = fd
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
def wait(self, timeout: float | None) -> str:
|
|
111
|
+
events = self._kq.control(None, 8, timeout)
|
|
112
|
+
if not events:
|
|
113
|
+
return _TIMEOUT
|
|
114
|
+
result = _EVENT
|
|
115
|
+
for ev in events:
|
|
116
|
+
if ev.ident == self.stop_fd:
|
|
117
|
+
return _STOP
|
|
118
|
+
if ev.fflags & (select.KQ_NOTE_DELETE | select.KQ_NOTE_RENAME | select.KQ_NOTE_REVOKE):
|
|
119
|
+
result = _GONE
|
|
120
|
+
return result
|
|
121
|
+
|
|
122
|
+
def disarm(self) -> None:
|
|
123
|
+
if self._dir_fd is not None:
|
|
124
|
+
with contextlib.suppress(OSError):
|
|
125
|
+
os.close(self._dir_fd) # closing removes the kevent
|
|
126
|
+
self._dir_fd = None
|
|
127
|
+
|
|
128
|
+
def close(self) -> None:
|
|
129
|
+
self.disarm()
|
|
130
|
+
with contextlib.suppress(OSError):
|
|
131
|
+
self._kq.close()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class _InotifyBackend(_Backend):
|
|
135
|
+
name = "inotify"
|
|
136
|
+
|
|
137
|
+
def __init__(self, path: str, stop_fd: int, poll_interval: float) -> None:
|
|
138
|
+
super().__init__(path, stop_fd, poll_interval)
|
|
139
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
140
|
+
self._add_watch = libc.inotify_add_watch
|
|
141
|
+
self._add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
|
|
142
|
+
self._add_watch.restype = ctypes.c_int
|
|
143
|
+
init = libc.inotify_init1
|
|
144
|
+
init.argtypes = [ctypes.c_int]
|
|
145
|
+
init.restype = ctypes.c_int
|
|
146
|
+
fd = init(_IN_NONBLOCK | _IN_CLOEXEC)
|
|
147
|
+
if fd < 0:
|
|
148
|
+
raise OSError(ctypes.get_errno(), "inotify_init1 failed")
|
|
149
|
+
self._fd = fd
|
|
150
|
+
self._armed = False
|
|
151
|
+
|
|
152
|
+
def arm(self) -> bool:
|
|
153
|
+
# Drain stale events from a previous (now gone) watch.
|
|
154
|
+
self._drain()
|
|
155
|
+
wd = self._add_watch(self._fd, os.fsencode(self.path), _IN_MASK)
|
|
156
|
+
self._armed = wd >= 0
|
|
157
|
+
return self._armed
|
|
158
|
+
|
|
159
|
+
def _drain(self) -> int:
|
|
160
|
+
"""Read all pending inotify events and return the OR of their masks."""
|
|
161
|
+
mask_or = 0
|
|
162
|
+
while True:
|
|
163
|
+
try:
|
|
164
|
+
data = os.read(self._fd, 65536)
|
|
165
|
+
except BlockingIOError:
|
|
166
|
+
break
|
|
167
|
+
except OSError:
|
|
168
|
+
break
|
|
169
|
+
if not data:
|
|
170
|
+
break
|
|
171
|
+
pos = 0
|
|
172
|
+
while pos + 16 <= len(data):
|
|
173
|
+
_wd = int.from_bytes(data[pos : pos + 4], sys.byteorder, signed=True)
|
|
174
|
+
mask = int.from_bytes(data[pos + 4 : pos + 8], sys.byteorder)
|
|
175
|
+
length = int.from_bytes(data[pos + 12 : pos + 16], sys.byteorder)
|
|
176
|
+
mask_or |= mask
|
|
177
|
+
pos += 16 + length
|
|
178
|
+
return mask_or
|
|
179
|
+
|
|
180
|
+
def wait(self, timeout: float | None) -> str:
|
|
181
|
+
ready, _, _ = select.select([self._fd, self.stop_fd], [], [], timeout)
|
|
182
|
+
if self.stop_fd in ready:
|
|
183
|
+
return _STOP
|
|
184
|
+
if self._fd in ready:
|
|
185
|
+
mask = self._drain()
|
|
186
|
+
if mask & _IN_GONE:
|
|
187
|
+
return _GONE
|
|
188
|
+
return _EVENT
|
|
189
|
+
return _TIMEOUT
|
|
190
|
+
|
|
191
|
+
def disarm(self) -> None:
|
|
192
|
+
self._armed = False
|
|
193
|
+
|
|
194
|
+
def close(self) -> None:
|
|
195
|
+
with contextlib.suppress(OSError):
|
|
196
|
+
os.close(self._fd)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class _PollBackend(_Backend):
|
|
200
|
+
name = "poll"
|
|
201
|
+
|
|
202
|
+
def __init__(self, path: str, stop_fd: int, poll_interval: float) -> None:
|
|
203
|
+
super().__init__(path, stop_fd, poll_interval)
|
|
204
|
+
self._snap: dict[str, tuple[int, int, int]] = {}
|
|
205
|
+
|
|
206
|
+
def _snapshot(self) -> dict[str, tuple[int, int, int]]:
|
|
207
|
+
snap: dict[str, tuple[int, int, int]] = {}
|
|
208
|
+
try:
|
|
209
|
+
with os.scandir(self.path) as it:
|
|
210
|
+
for entry in it:
|
|
211
|
+
try:
|
|
212
|
+
st = entry.stat(follow_symlinks=False)
|
|
213
|
+
except OSError:
|
|
214
|
+
continue
|
|
215
|
+
snap[entry.name] = (st.st_mtime_ns, st.st_size, st.st_ino)
|
|
216
|
+
st = os.stat(self.path)
|
|
217
|
+
snap["."] = (st.st_mtime_ns, 0, st.st_ino)
|
|
218
|
+
except OSError:
|
|
219
|
+
return {}
|
|
220
|
+
return snap
|
|
221
|
+
|
|
222
|
+
def arm(self) -> bool:
|
|
223
|
+
self._snap = self._snapshot()
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
def wait(self, timeout: float | None) -> str:
|
|
227
|
+
interval = self.poll_interval if timeout is None else min(timeout, self.poll_interval)
|
|
228
|
+
ready, _, _ = select.select([self.stop_fd], [], [], interval)
|
|
229
|
+
if ready:
|
|
230
|
+
return _STOP
|
|
231
|
+
snap = self._snapshot()
|
|
232
|
+
if snap != self._snap:
|
|
233
|
+
self._snap = snap
|
|
234
|
+
return _EVENT
|
|
235
|
+
return _TIMEOUT
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
_BACKENDS: dict[str, type[_Backend]] = {"kqueue": _KqueueBackend, "inotify": _InotifyBackend, "poll": _PollBackend}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _auto_candidates() -> list[str]:
|
|
242
|
+
"""Backend names to try for ``backend="auto"``, best first."""
|
|
243
|
+
names = []
|
|
244
|
+
if hasattr(select, "kqueue"):
|
|
245
|
+
names.append("kqueue")
|
|
246
|
+
elif sys.platform.startswith("linux"):
|
|
247
|
+
names.append("inotify")
|
|
248
|
+
names.append("poll")
|
|
249
|
+
return names
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class LeaseWatcher:
|
|
253
|
+
"""Call ``callback()`` once at start and after every (debounced) change in the directory ``path``.
|
|
254
|
+
|
|
255
|
+
``backend`` is ``"auto"``, ``"kqueue"``, ``"inotify"`` or ``"poll"``; after ``start()`` the ``backend``
|
|
256
|
+
attribute names the one in use. The callback runs on a daemon thread; exceptions are logged to stderr and
|
|
257
|
+
do not stop the watcher. If the directory is deleted or renamed away the watcher waits for it to reappear
|
|
258
|
+
(checking every ``poll_interval`` seconds), re-arms and fires the callback.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def __init__(
|
|
262
|
+
self,
|
|
263
|
+
path: str | os.PathLike[str],
|
|
264
|
+
callback: Callable[[], None],
|
|
265
|
+
*,
|
|
266
|
+
backend: str = "auto",
|
|
267
|
+
poll_interval: float = 1.0,
|
|
268
|
+
debounce: float = 0.05,
|
|
269
|
+
) -> None:
|
|
270
|
+
if backend != "auto" and backend not in _BACKENDS:
|
|
271
|
+
raise ValueError(f"unknown watch backend {backend!r}")
|
|
272
|
+
self.path = os.fspath(path)
|
|
273
|
+
self._callback = callback
|
|
274
|
+
self._requested = backend
|
|
275
|
+
self._poll_interval = poll_interval
|
|
276
|
+
self._debounce = debounce
|
|
277
|
+
self.backend: str = backend
|
|
278
|
+
self._lock = threading.Lock()
|
|
279
|
+
self._thread: threading.Thread | None = None
|
|
280
|
+
self._stop_r = -1
|
|
281
|
+
self._stop_w = -1
|
|
282
|
+
self._impl: _Backend | None = None
|
|
283
|
+
self._abandoned = False
|
|
284
|
+
|
|
285
|
+
def start(self) -> None:
|
|
286
|
+
"""Create the directory if needed, start watching and fire the callback once. Idempotent."""
|
|
287
|
+
with self._lock:
|
|
288
|
+
if self._thread is not None and self._thread.is_alive():
|
|
289
|
+
return
|
|
290
|
+
self._abandoned = False
|
|
291
|
+
os.makedirs(self.path, mode=0o700, exist_ok=True)
|
|
292
|
+
self._stop_r, self._stop_w = os.pipe()
|
|
293
|
+
for fd in (self._stop_r, self._stop_w):
|
|
294
|
+
os.set_blocking(fd, False)
|
|
295
|
+
impl = self._make_backend()
|
|
296
|
+
self._impl = impl
|
|
297
|
+
self.backend = impl.name
|
|
298
|
+
impl.arm()
|
|
299
|
+
thread = threading.Thread(target=self._run, args=(impl,), name="cli-svckit-lease-watcher", daemon=True)
|
|
300
|
+
self._thread = thread
|
|
301
|
+
thread.start()
|
|
302
|
+
|
|
303
|
+
def stop(self) -> None:
|
|
304
|
+
"""Stop the thread (within about a second) and close all descriptors. Idempotent."""
|
|
305
|
+
with self._lock:
|
|
306
|
+
thread = self._thread
|
|
307
|
+
if thread is None:
|
|
308
|
+
return
|
|
309
|
+
with contextlib.suppress(OSError):
|
|
310
|
+
os.write(self._stop_w, b"x")
|
|
311
|
+
if thread is not threading.current_thread():
|
|
312
|
+
thread.join(1.0)
|
|
313
|
+
if thread.is_alive():
|
|
314
|
+
self._abandoned = True # callback still running; the thread cleans up when it exits
|
|
315
|
+
return
|
|
316
|
+
self._cleanup(self._impl)
|
|
317
|
+
|
|
318
|
+
def _cleanup(self, impl: _Backend | None) -> None:
|
|
319
|
+
if impl is not None:
|
|
320
|
+
impl.close()
|
|
321
|
+
for fd in (self._stop_r, self._stop_w):
|
|
322
|
+
if fd >= 0:
|
|
323
|
+
with contextlib.suppress(OSError):
|
|
324
|
+
os.close(fd)
|
|
325
|
+
self._stop_r = self._stop_w = -1
|
|
326
|
+
self._impl = None
|
|
327
|
+
self._thread = None
|
|
328
|
+
|
|
329
|
+
def _make_backend(self) -> _Backend:
|
|
330
|
+
if self._requested != "auto":
|
|
331
|
+
return _BACKENDS[self._requested](self.path, self._stop_r, self._poll_interval)
|
|
332
|
+
last: Exception | None = None
|
|
333
|
+
for name in _auto_candidates():
|
|
334
|
+
try:
|
|
335
|
+
return _BACKENDS[name](self.path, self._stop_r, self._poll_interval)
|
|
336
|
+
except (OSError, AttributeError, ValueError) as exc:
|
|
337
|
+
last = exc
|
|
338
|
+
raise OSError(f"no watch backend available: {last}")
|
|
339
|
+
|
|
340
|
+
def _fire(self) -> None:
|
|
341
|
+
try:
|
|
342
|
+
self._callback()
|
|
343
|
+
except Exception as exc: # noqa: BLE001 - the watcher must survive callback bugs
|
|
344
|
+
print(f"cli-svckit: lease watcher callback failed: {exc!r}", file=sys.stderr)
|
|
345
|
+
|
|
346
|
+
def _wait_for_dir(self, impl: _Backend) -> bool:
|
|
347
|
+
"""Wait until the directory exists and is armed again; False if stop was requested."""
|
|
348
|
+
impl.disarm()
|
|
349
|
+
while True:
|
|
350
|
+
if impl.arm():
|
|
351
|
+
return True
|
|
352
|
+
ready, _, _ = select.select([self._stop_r], [], [], self._poll_interval)
|
|
353
|
+
if ready:
|
|
354
|
+
return False
|
|
355
|
+
|
|
356
|
+
def _run(self, impl: _Backend) -> None:
|
|
357
|
+
try:
|
|
358
|
+
self._loop(impl)
|
|
359
|
+
finally:
|
|
360
|
+
if self._abandoned: # stop() gave up waiting for a slow callback
|
|
361
|
+
self._cleanup(impl)
|
|
362
|
+
|
|
363
|
+
def _loop(self, impl: _Backend) -> None:
|
|
364
|
+
self._fire()
|
|
365
|
+
while True:
|
|
366
|
+
res = impl.wait(None if impl.name != "poll" else self._poll_interval)
|
|
367
|
+
if res == _STOP:
|
|
368
|
+
return
|
|
369
|
+
if res == _TIMEOUT:
|
|
370
|
+
continue
|
|
371
|
+
# Coalesce a burst of events into one callback.
|
|
372
|
+
deadline = time.monotonic() + max(self._debounce * 10, 0.5)
|
|
373
|
+
while res != _STOP:
|
|
374
|
+
if res == _GONE:
|
|
375
|
+
if not self._wait_for_dir(impl):
|
|
376
|
+
return
|
|
377
|
+
res = _EVENT
|
|
378
|
+
break
|
|
379
|
+
remaining = min(self._debounce, deadline - time.monotonic())
|
|
380
|
+
if remaining <= 0:
|
|
381
|
+
break
|
|
382
|
+
res = impl.wait(remaining)
|
|
383
|
+
if res == _TIMEOUT:
|
|
384
|
+
break
|
|
385
|
+
if res == _STOP:
|
|
386
|
+
return
|
|
387
|
+
self._fire()
|
cli_svckit/doctor.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Doctor: run independent diagnostic checks concurrently, each with its own deadline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from cli_svckit.contract.envelope import EXIT_FAIL, EXIT_OK, EXIT_WARN
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class DoctorItem:
|
|
16
|
+
"""What one check found: ``ok``, ``warn``, ``fail`` or ``skip``, a detail line and an optional fix."""
|
|
17
|
+
|
|
18
|
+
status: str
|
|
19
|
+
detail: str
|
|
20
|
+
fix: dict[str, Any] | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Check:
|
|
25
|
+
"""A named diagnostic: ``fn`` returns a :class:`DoctorItem` and must finish within ``deadline_s``."""
|
|
26
|
+
|
|
27
|
+
id: str
|
|
28
|
+
title: str
|
|
29
|
+
fn: Callable[[], DoctorItem]
|
|
30
|
+
area: str = "general"
|
|
31
|
+
deadline_s: float = 10.0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class CheckOutcome:
|
|
36
|
+
"""A check together with its result."""
|
|
37
|
+
|
|
38
|
+
check: Check
|
|
39
|
+
item: DoctorItem
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, Any]:
|
|
42
|
+
"""Return the wire form matching ``doctor.json``."""
|
|
43
|
+
d: dict[str, Any] = {
|
|
44
|
+
"id": self.check.id,
|
|
45
|
+
"title": self.check.title,
|
|
46
|
+
"area": self.check.area,
|
|
47
|
+
"status": self.item.status,
|
|
48
|
+
"detail": self.item.detail,
|
|
49
|
+
}
|
|
50
|
+
if self.item.fix is not None:
|
|
51
|
+
d["fix"] = self.item.fix
|
|
52
|
+
return d
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class DoctorReport:
|
|
57
|
+
"""All check outcomes in the order the checks were given."""
|
|
58
|
+
|
|
59
|
+
outcomes: list[CheckOutcome] = field(default_factory=list)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def status(self) -> str:
|
|
63
|
+
"""``fail`` if any check failed, else ``warn`` if any warned, else ``ok`` (skips do not count)."""
|
|
64
|
+
statuses = {o.item.status for o in self.outcomes}
|
|
65
|
+
if statuses - {"ok", "warn", "skip"}: # "fail" and anything unknown: fail closed
|
|
66
|
+
return "fail"
|
|
67
|
+
return "warn" if "warn" in statuses else "ok"
|
|
68
|
+
|
|
69
|
+
def to_dict(self) -> dict[str, Any]:
|
|
70
|
+
"""Return the wire form matching ``doctor.json``."""
|
|
71
|
+
return {"status": self.status, "checks": [o.to_dict() for o in self.outcomes]}
|
|
72
|
+
|
|
73
|
+
def exit_code(self) -> int:
|
|
74
|
+
"""Exit code for the aggregate status (ok 0, warn 4, fail 1)."""
|
|
75
|
+
return {"ok": EXIT_OK, "warn": EXIT_WARN}.get(self.status, EXIT_FAIL)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _run_one(check: Check, box: list[DoctorItem], done: threading.Event) -> None:
|
|
79
|
+
try:
|
|
80
|
+
item = check.fn()
|
|
81
|
+
if not isinstance(item, DoctorItem):
|
|
82
|
+
item = DoctorItem("fail", f"check returned {type(item).__name__}, expected DoctorItem")
|
|
83
|
+
if item.status not in ("ok", "warn", "fail", "skip"):
|
|
84
|
+
item = DoctorItem("fail", f"invalid status {item.status!r}")
|
|
85
|
+
box.append(item)
|
|
86
|
+
except BaseException as exc:
|
|
87
|
+
box.append(DoctorItem("fail", f"{type(exc).__name__}: {exc}"))
|
|
88
|
+
finally:
|
|
89
|
+
done.set()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run_checks(
|
|
93
|
+
checks: list[Check],
|
|
94
|
+
*,
|
|
95
|
+
max_workers: int = 8,
|
|
96
|
+
clock: Callable[[], float] = time.monotonic,
|
|
97
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
98
|
+
) -> DoctorReport:
|
|
99
|
+
"""Run ``checks`` with at most ``max_workers`` in flight; a check that overruns its deadline fails.
|
|
100
|
+
|
|
101
|
+
Each check runs in a daemon thread. An overrunning thread is abandoned (it cannot be killed) and its slot is
|
|
102
|
+
freed. Exceptions become ``fail`` items with the exception type and message, never a traceback.
|
|
103
|
+
"""
|
|
104
|
+
checks = list(checks)
|
|
105
|
+
results: list[DoctorItem | None] = [None] * len(checks)
|
|
106
|
+
pending = list(range(len(checks)))
|
|
107
|
+
running: dict[int, tuple[float, threading.Event, list[DoctorItem]]] = {}
|
|
108
|
+
while pending or running:
|
|
109
|
+
while pending and len(running) < max(1, max_workers):
|
|
110
|
+
i = pending.pop(0)
|
|
111
|
+
done = threading.Event()
|
|
112
|
+
box: list[DoctorItem] = []
|
|
113
|
+
threading.Thread(target=_run_one, args=(checks[i], box, done), daemon=True).start()
|
|
114
|
+
running[i] = (clock() + checks[i].deadline_s, done, box)
|
|
115
|
+
sleep(0.005)
|
|
116
|
+
now = clock()
|
|
117
|
+
for i, (deadline, done, box) in list(running.items()):
|
|
118
|
+
if done.is_set():
|
|
119
|
+
results[i] = box[0]
|
|
120
|
+
elif now >= deadline:
|
|
121
|
+
results[i] = DoctorItem("fail", f"timed out after {checks[i].deadline_s:g}s")
|
|
122
|
+
else:
|
|
123
|
+
continue
|
|
124
|
+
del running[i]
|
|
125
|
+
return DoctorReport([CheckOutcome(c, r) for c, r in zip(checks, results, strict=True) if r is not None])
|
cli_svckit/health.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Health results (IETF health-check draft style) and probes that never raise."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import socket
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from cli_svckit.contract.envelope import EXIT_FAIL, EXIT_OK, EXIT_WARN
|
|
15
|
+
from cli_svckit.procs import pid_alive
|
|
16
|
+
|
|
17
|
+
STATUSES = ("pass", "warn", "fail")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class CheckResult:
|
|
22
|
+
"""The outcome of one probe: a status plus optional measured value and note."""
|
|
23
|
+
|
|
24
|
+
status: str
|
|
25
|
+
observed_value: Any = None
|
|
26
|
+
observed_unit: str | None = None
|
|
27
|
+
output: str | None = None
|
|
28
|
+
|
|
29
|
+
def to_dict(self) -> dict[str, Any]:
|
|
30
|
+
"""Return the wire form (camelCase keys, unset fields omitted)."""
|
|
31
|
+
d: dict[str, Any] = {"status": self.status}
|
|
32
|
+
if self.observed_value is not None:
|
|
33
|
+
d["observedValue"] = self.observed_value
|
|
34
|
+
if self.observed_unit is not None:
|
|
35
|
+
d["observedUnit"] = self.observed_unit
|
|
36
|
+
if self.output is not None:
|
|
37
|
+
d["output"] = self.output
|
|
38
|
+
return d
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_dict(cls, d: dict[str, Any]) -> CheckResult:
|
|
42
|
+
"""Build from the wire form; unknown keys are ignored."""
|
|
43
|
+
return cls(d.get("status", "fail"), d.get("observedValue"), d.get("observedUnit"), d.get("output"))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class HealthResult:
|
|
48
|
+
"""Overall health: status, liveness, readiness and named groups of check results."""
|
|
49
|
+
|
|
50
|
+
status: str
|
|
51
|
+
live: bool
|
|
52
|
+
ready: bool
|
|
53
|
+
version: str | None = None
|
|
54
|
+
output: str | None = None
|
|
55
|
+
checks: dict[str, list[CheckResult]] = field(default_factory=dict)
|
|
56
|
+
|
|
57
|
+
def to_dict(self) -> dict[str, Any]:
|
|
58
|
+
"""Return the wire form matching ``health.json``."""
|
|
59
|
+
d: dict[str, Any] = {"status": self.status, "live": self.live, "ready": self.ready}
|
|
60
|
+
if self.version is not None:
|
|
61
|
+
d["version"] = self.version
|
|
62
|
+
if self.output is not None:
|
|
63
|
+
d["output"] = self.output
|
|
64
|
+
d["checks"] = {name: [c.to_dict() for c in items] for name, items in self.checks.items()}
|
|
65
|
+
return d
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_dict(cls, d: dict[str, Any]) -> HealthResult:
|
|
69
|
+
"""Build from the wire form; unknown keys are ignored."""
|
|
70
|
+
checks_in = d.get("checks")
|
|
71
|
+
if not isinstance(checks_in, dict):
|
|
72
|
+
checks_in = {}
|
|
73
|
+
checks = {
|
|
74
|
+
name: [CheckResult.from_dict(c) for c in items if isinstance(c, dict)]
|
|
75
|
+
for name, items in checks_in.items()
|
|
76
|
+
if isinstance(items, list)
|
|
77
|
+
}
|
|
78
|
+
return cls(
|
|
79
|
+
status=d.get("status", "fail"),
|
|
80
|
+
live=bool(d.get("live", False)),
|
|
81
|
+
ready=bool(d.get("ready", False)),
|
|
82
|
+
version=d.get("version"),
|
|
83
|
+
output=d.get("output"),
|
|
84
|
+
checks=checks,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def worst(statuses: Iterable[str]) -> str:
|
|
89
|
+
"""Return the worst status (fail > warn > pass); unknown values count as warn; ``pass`` when empty."""
|
|
90
|
+
result = "pass"
|
|
91
|
+
for s in statuses:
|
|
92
|
+
if s == "fail":
|
|
93
|
+
return "fail"
|
|
94
|
+
if s != "pass":
|
|
95
|
+
result = "warn"
|
|
96
|
+
return result
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def exit_code(status: str) -> int:
|
|
100
|
+
"""Map a health status to a process exit code (pass 0, warn 4, anything else 1)."""
|
|
101
|
+
return {"pass": EXIT_OK, "warn": EXIT_WARN}.get(status, EXIT_FAIL)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _SameHostRedirect(urllib.request.HTTPRedirectHandler):
|
|
105
|
+
def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> Any:
|
|
106
|
+
if urllib.parse.urlsplit(newurl).netloc not in ("", urllib.parse.urlsplit(req.full_url).netloc):
|
|
107
|
+
return None
|
|
108
|
+
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def http_probe(url: str, timeout: float = 5.0, expect_status: int = 200) -> CheckResult:
|
|
112
|
+
"""GET ``url`` and pass when the status equals ``expect_status``; records latency in ms. Never raises.
|
|
113
|
+
|
|
114
|
+
Redirects to another host are not followed, and response bodies are never read or reported.
|
|
115
|
+
"""
|
|
116
|
+
start = time.monotonic()
|
|
117
|
+
try:
|
|
118
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _SameHostRedirect)
|
|
119
|
+
with opener.open(urllib.request.Request(url, method="GET"), timeout=timeout) as resp:
|
|
120
|
+
code = resp.status
|
|
121
|
+
except urllib.error.HTTPError as exc:
|
|
122
|
+
code = exc.code
|
|
123
|
+
except Exception as exc:
|
|
124
|
+
# Only the exception type: messages such as "unknown url type" echo the whole URL (maybe a token).
|
|
125
|
+
return CheckResult("fail", output=type(exc).__name__)
|
|
126
|
+
ms = round((time.monotonic() - start) * 1000, 1)
|
|
127
|
+
if code == expect_status:
|
|
128
|
+
return CheckResult("pass", ms, "ms", f"HTTP {code}")
|
|
129
|
+
return CheckResult("fail", ms, "ms", f"HTTP {code}, expected {expect_status}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def port_probe(host: str, port: int, timeout: float = 2.0) -> CheckResult:
|
|
133
|
+
"""Pass when a TCP connection to ``host:port`` succeeds. Never raises."""
|
|
134
|
+
start = time.monotonic()
|
|
135
|
+
try:
|
|
136
|
+
with socket.create_connection((host, port), timeout=timeout):
|
|
137
|
+
pass
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
return CheckResult("fail", output=f"{type(exc).__name__}: {exc}"[:200])
|
|
140
|
+
return CheckResult("pass", round((time.monotonic() - start) * 1000, 1), "ms", "connected")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def pid_probe(pid: int) -> CheckResult:
|
|
144
|
+
"""Pass when process ``pid`` is alive. Never raises."""
|
|
145
|
+
try:
|
|
146
|
+
alive = pid_alive(pid)
|
|
147
|
+
except Exception as exc:
|
|
148
|
+
return CheckResult("fail", output=f"{type(exc).__name__}: {exc}"[:200])
|
|
149
|
+
return CheckResult("pass", output="running") if alive else CheckResult("fail", output="not running")
|