emberpool 0.1.0a1__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.
emberpool/_ledger.py ADDED
@@ -0,0 +1,815 @@
1
+ """Crash-recovery ledger: what a pool created on the host, so that a pool
2
+ that died before teardown can be cleaned up by the next one.
3
+
4
+ One ledger per prefix, in the jail base: `<jail_base>/<prefix>.ledger`, with
5
+ an exclusive `flock` on `<jail_base>/<prefix>.ledger.lock` held for the
6
+ pool's lifetime. A second pool with the same prefix fails to take the lock
7
+ and refuses to start.
8
+
9
+ The ledger is root-owned, mode 0600, JSON lines. Each line records that a
10
+ resource was added or released, and is flushed and fsynced before the call
11
+ that creates the resource goes ahead (or, where emberpool only learns the
12
+ name from the call, right after it):
13
+
14
+ {"v": 1, "op": "add", "kind": "netns", "name": "ep-1a2b3c4d"}
15
+ {"v": 1, "op": "del", "kind": "netns", "name": "ep-1a2b3c4d"}
16
+
17
+ Kinds: `table` (host nftables table, family inet), `netns`, `link` (a
18
+ host-side veth), `jail` (`<jail_base>/<exec>/<vm_id>`), `cgroup`
19
+ (`<cgroup root>/<parent>/<vm_id>`), `vmm` (a Firecracker process: pid and vm
20
+ id) and `workdir` (`<jail_base>/<name>`).
21
+
22
+ Recovery (docs/40-rules.md rule 10): every name is validated again when the
23
+ ledger is read, and anything that fails is rejected and reported, never
24
+ acted on. Each resource is removed by its exact recorded name, only if it
25
+ still exists. A process is killed only if its command line is the jailer or
26
+ Firecracker with `--id <vm_id>` and it belongs to this jail base (its root
27
+ directory is the VM's jail or it sits in the VM's cgroup, or its
28
+ `--chroot-base-dir` is the base); the kill goes
29
+ through a pidfd, so a recycled pid is never signalled. Trees are removed
30
+ without following symlinks. Recovery is idempotent and bounded.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ import contextlib
37
+ import errno
38
+ import fcntl
39
+ import json
40
+ import logging
41
+ import os
42
+ import re
43
+ import select
44
+ import shutil
45
+ import signal
46
+ import stat
47
+ import time
48
+ from collections.abc import Awaitable, Callable, Iterable, Sequence
49
+ from dataclasses import dataclass, field
50
+ from pathlib import Path
51
+ from typing import Any
52
+
53
+ from emberpool._jailer import CGROUP_ROOT, JailLayout, remove_jail
54
+ from emberpool._names import (
55
+ CommandResult,
56
+ run_command,
57
+ validate_interface,
58
+ validate_netns,
59
+ validate_nft_table,
60
+ validate_vm_id,
61
+ )
62
+ from emberpool._types import IsolationError
63
+
64
+ __all__ = [
65
+ "LEDGER_VERSION",
66
+ "Entry",
67
+ "Ledger",
68
+ "LedgerBusy",
69
+ "RecoveryReport",
70
+ "parse_ledger",
71
+ "is_vmm",
72
+ "recover",
73
+ ]
74
+
75
+ log = logging.getLogger(__name__)
76
+
77
+ LEDGER_VERSION = 1
78
+ MAX_LINE = 1024 # bytes per line, newline included
79
+ MAX_FILE = 4 << 20 # a larger ledger is refused, never partly trusted
80
+ MAX_PID = 1 << 22 # PID_MAX_LIMIT on 64-bit Linux
81
+ _COMPACT_MIN = 1024 # lines before the ledger is rewritten with live entries only
82
+ _MAX_CMDLINE = 64 << 10
83
+
84
+ # Kind -> field name -> type. Every line has exactly these keys plus v, op, kind.
85
+ _SCHEMA: dict[str, dict[str, type]] = {
86
+ "table": {"name": str},
87
+ "netns": {"name": str},
88
+ "link": {"name": str},
89
+ "jail": {"vm_id": str, "exec": str},
90
+ "cgroup": {"parent": str, "vm_id": str},
91
+ "vmm": {"pid": int, "vm_id": str},
92
+ "workdir": {"name": str},
93
+ }
94
+ # Removal order: processes first, then what they used.
95
+ _ORDER = ("vmm", "jail", "netns", "link", "table", "cgroup", "workdir")
96
+
97
+ _CGROUP_PARENT_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
98
+
99
+
100
+ class LedgerBusy(IsolationError):
101
+ """Another live pool holds the ledger lock for this prefix."""
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class Entry:
106
+ """One recorded resource. Build with the class methods."""
107
+
108
+ kind: str
109
+ fields: tuple[tuple[str, str | int], ...]
110
+
111
+ @classmethod
112
+ def table(cls, name: str) -> Entry:
113
+ return cls("table", (("name", name),))
114
+
115
+ @classmethod
116
+ def netns(cls, name: str) -> Entry:
117
+ return cls("netns", (("name", name),))
118
+
119
+ @classmethod
120
+ def link(cls, name: str) -> Entry:
121
+ return cls("link", (("name", name),))
122
+
123
+ @classmethod
124
+ def jail(cls, vm_id: str, exec_name: str) -> Entry:
125
+ return cls("jail", (("exec", exec_name), ("vm_id", vm_id)))
126
+
127
+ @classmethod
128
+ def cgroup(cls, parent: str, vm_id: str) -> Entry:
129
+ return cls("cgroup", (("parent", parent), ("vm_id", vm_id)))
130
+
131
+ @classmethod
132
+ def vmm(cls, pid: int, vm_id: str) -> Entry:
133
+ return cls("vmm", (("pid", pid), ("vm_id", vm_id)))
134
+
135
+ @classmethod
136
+ def workdir(cls, name: str) -> Entry:
137
+ return cls("workdir", (("name", name),))
138
+
139
+ def get(self, key: str) -> Any:
140
+ return dict(self.fields)[key]
141
+
142
+ def describe(self) -> str:
143
+ return self.kind + " " + " ".join(f"{k}={v}" for k, v in self.fields)
144
+
145
+ def to_line(self, op: str) -> bytes:
146
+ obj: dict[str, Any] = {"v": LEDGER_VERSION, "op": op, "kind": self.kind}
147
+ obj.update(self.fields)
148
+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=True).encode("ascii") + b"\n"
149
+
150
+
151
+ def check_entry(entry: Entry, base: Path, prefix: str) -> Entry:
152
+ """Validate an entry for a ledger in `base` with `prefix`. Raises ValueError."""
153
+ schema = _SCHEMA.get(entry.kind)
154
+ if schema is None:
155
+ raise ValueError(f"unknown kind: {entry.kind!r}")
156
+ values = dict(entry.fields)
157
+ if set(values) != set(schema) or len(values) != len(entry.fields):
158
+ raise ValueError(f"bad fields for {entry.kind}: {sorted(values)}")
159
+ for key, typ in schema.items():
160
+ if type(values[key]) is not typ:
161
+ raise ValueError(f"{entry.kind}.{key} must be {typ.__name__}")
162
+ if entry.kind == "table":
163
+ validate_nft_table(values["name"])
164
+ elif entry.kind == "netns":
165
+ if not validate_netns(values["name"]).startswith(f"{prefix}-"):
166
+ raise ValueError(f"netns outside prefix {prefix!r}: {values['name']!r}")
167
+ elif entry.kind == "link":
168
+ if not validate_interface(values["name"]).startswith(f"{prefix}-"):
169
+ raise ValueError(f"link outside prefix {prefix!r}: {values['name']!r}")
170
+ elif entry.kind == "jail":
171
+ JailLayout(base, values["exec"], validate_vm_id(values["vm_id"]))
172
+ elif entry.kind == "cgroup":
173
+ if _CGROUP_PARENT_RE.fullmatch(values["parent"]) is None:
174
+ raise ValueError(f"invalid cgroup parent: {values['parent']!r}")
175
+ validate_vm_id(values["vm_id"])
176
+ elif entry.kind == "vmm":
177
+ if not 1 < values["pid"] <= MAX_PID:
178
+ raise ValueError(f"invalid pid: {values['pid']!r}")
179
+ validate_vm_id(values["vm_id"])
180
+ elif entry.kind == "workdir":
181
+ if re.fullmatch(re.escape(prefix) + r"-pool-[0-9a-f]{12}", values["name"]) is None:
182
+ raise ValueError(f"invalid workdir name: {values['name']!r}")
183
+ return entry
184
+
185
+
186
+ def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
187
+ out: dict[str, Any] = {}
188
+ for key, value in pairs:
189
+ if key in out:
190
+ raise ValueError(f"duplicate key {key!r}")
191
+ out[key] = value
192
+ return out
193
+
194
+
195
+ def _reject_constant(name: str) -> Any:
196
+ raise ValueError(f"invalid JSON constant {name}")
197
+
198
+
199
+ def _reject_float(text: str) -> Any:
200
+ raise ValueError("floats are not allowed")
201
+
202
+
203
+ def _parse_line(raw: bytes, base: Path, prefix: str) -> tuple[str, Entry]:
204
+ if len(raw) + 1 > MAX_LINE:
205
+ raise ValueError("line too long")
206
+ obj = json.loads(
207
+ raw.decode("ascii"),
208
+ object_pairs_hook=_no_duplicates,
209
+ parse_constant=_reject_constant,
210
+ parse_float=_reject_float,
211
+ )
212
+ if not isinstance(obj, dict):
213
+ raise ValueError("not an object")
214
+ if type(obj.get("v")) is not int or obj["v"] != LEDGER_VERSION:
215
+ raise ValueError(f"unsupported version: {obj.get('v')!r}")
216
+ op, kind = obj.get("op"), obj.get("kind")
217
+ if op not in ("add", "del"):
218
+ raise ValueError(f"bad op: {op!r}")
219
+ if not isinstance(kind, str) or kind not in _SCHEMA:
220
+ raise ValueError(f"unknown kind: {kind!r}")
221
+ keys = set(obj) - {"v", "op", "kind"}
222
+ if keys != set(_SCHEMA[kind]):
223
+ raise ValueError(f"bad keys for {kind}: {sorted(keys)}")
224
+ entry = Entry(kind, tuple(sorted((k, obj[k]) for k in keys)))
225
+ return op, check_entry(entry, base, prefix)
226
+
227
+
228
+ def parse_ledger(data: bytes, base: Path, prefix: str) -> tuple[list[Entry], list[str]]:
229
+ """Live entries (added and not released, in order) and rejected lines,
230
+ each as a short reason. An unterminated last line is a torn write and is
231
+ rejected."""
232
+ live: dict[Entry, None] = {}
233
+ rejected: list[str] = []
234
+ lines = data.split(b"\n")
235
+ tail = lines.pop() # b"" when the data ends in a newline
236
+ for number, raw in enumerate(lines, 1):
237
+ try:
238
+ op, entry = _parse_line(raw, base, prefix)
239
+ except (ValueError, UnicodeDecodeError, RecursionError) as e:
240
+ rejected.append(f"line {number}: {type(e).__name__}: {str(e)[:200]}")
241
+ continue
242
+ if op == "add":
243
+ live[entry] = None
244
+ else:
245
+ live.pop(entry, None)
246
+ if tail:
247
+ rejected.append(f"line {len(lines) + 1}: incomplete (torn write)")
248
+ return list(live), rejected
249
+
250
+
251
+ def _check_own_file(fd: int, path: Path) -> os.stat_result:
252
+ st = os.fstat(fd)
253
+ if not stat.S_ISREG(st.st_mode):
254
+ raise IsolationError(f"ledger file is not a regular file: {path}")
255
+ if st.st_uid != os.geteuid():
256
+ raise IsolationError(f"ledger file is not owned by this user: {path}")
257
+ if st.st_mode & 0o077:
258
+ raise IsolationError(f"ledger file is accessible to others (mode {st.st_mode & 0o777:o}): {path}")
259
+ return st
260
+
261
+
262
+ def _fsync_dir(path: Path) -> None:
263
+ fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
264
+ try:
265
+ os.fsync(fd)
266
+ finally:
267
+ os.close(fd)
268
+
269
+
270
+ def _write_all(fd: int, data: bytes) -> None:
271
+ view = memoryview(data)
272
+ while view:
273
+ n = os.write(fd, view)
274
+ view = view[n:]
275
+
276
+
277
+ _FLAGS = os.O_CLOEXEC | os.O_NOFOLLOW
278
+
279
+
280
+ class Ledger:
281
+ """The ledger of one pool. Use `Ledger.acquire()`; synchronous and fast
282
+ (each write is one small append and an fsync)."""
283
+
284
+ def __init__(self, base: Path, prefix: str, lock_fd: int) -> None:
285
+ self.base = base
286
+ self.prefix = prefix
287
+ self.path = base / f"{prefix}.ledger"
288
+ self.lock_path = base / f"{prefix}.ledger.lock"
289
+ self._tmp_path = base / f"{prefix}.ledger.tmp"
290
+ self._lock_fd: int | None = lock_fd
291
+ self._fd: int | None = None
292
+ self._live: dict[Entry, None] = {}
293
+ self._lines = 0
294
+ # Left by a pool that died: entries and rejected lines.
295
+ self.stale: list[Entry] = []
296
+ self.rejected: list[str] = []
297
+
298
+ # -- open and close ----------------------------------------------------
299
+
300
+ @classmethod
301
+ def acquire(cls, base: Path, prefix: str) -> Ledger:
302
+ """Take the lock for `prefix` in `base` and read any ledger left behind.
303
+ Raises LedgerBusy if another live pool holds it, IsolationError if a
304
+ ledger file is not this user's own private file or is too large."""
305
+ if not isinstance(prefix, str):
306
+ raise ValueError(f"prefix must be a str: {prefix!r}")
307
+ validate_netns(f"{prefix}-0")
308
+ base = Path(base)
309
+ if not base.is_absolute():
310
+ raise ValueError(f"ledger base must be absolute: {base}")
311
+ lock_path = base / f"{prefix}.ledger.lock"
312
+ for _ in range(8):
313
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | _FLAGS, 0o600)
314
+ try:
315
+ st = _check_own_file(fd, lock_path)
316
+ try:
317
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
318
+ except BlockingIOError:
319
+ raise LedgerBusy(
320
+ f"another emberpool pool with prefix {prefix!r} is running on this host "
321
+ f"(it holds {lock_path})"
322
+ ) from None
323
+ # The previous holder may have unlinked the file before we
324
+ # locked it; then the lock guards nothing. Retry.
325
+ try:
326
+ now = os.stat(lock_path, follow_symlinks=False)
327
+ except FileNotFoundError:
328
+ now = None
329
+ if now is not None and (now.st_dev, now.st_ino) == (st.st_dev, st.st_ino):
330
+ break
331
+ except BaseException:
332
+ os.close(fd)
333
+ raise
334
+ os.close(fd)
335
+ else:
336
+ raise IsolationError(f"could not lock {lock_path}: it keeps being replaced")
337
+ ledger = cls(base, prefix, fd)
338
+ try:
339
+ ledger._read_stale()
340
+ except BaseException:
341
+ ledger._release_lock(unlink=False)
342
+ raise
343
+ return ledger
344
+
345
+ def _read_stale(self) -> None:
346
+ try:
347
+ fd = os.open(self.path, os.O_RDONLY | _FLAGS)
348
+ except FileNotFoundError:
349
+ return
350
+ except OSError as e:
351
+ if e.errno == errno.ELOOP:
352
+ raise IsolationError(f"ledger file is a symlink: {self.path}") from None
353
+ raise
354
+ try:
355
+ st = _check_own_file(fd, self.path)
356
+ if st.st_size > MAX_FILE:
357
+ raise IsolationError(f"ledger file too large ({st.st_size} bytes): {self.path}")
358
+ data = os.read(fd, MAX_FILE + 1)
359
+ if len(data) > MAX_FILE:
360
+ raise IsolationError(f"ledger file too large: {self.path}")
361
+ finally:
362
+ os.close(fd)
363
+ self.stale, self.rejected = parse_ledger(data, self.base, self.prefix)
364
+ # Recovery acts on these; until it says otherwise, they are live.
365
+ self._live = dict.fromkeys(self.stale)
366
+
367
+ def close(self) -> bool:
368
+ """Release the lock. If nothing is live any more, remove the ledger
369
+ first (a clean shutdown) and return True; otherwise keep it for the
370
+ next start to recover, and return False. Idempotent."""
371
+ if self._lock_fd is None:
372
+ return not self._live
373
+ clean = not self._live
374
+ try:
375
+ if self._fd is not None:
376
+ os.close(self._fd)
377
+ self._fd = None
378
+ if clean:
379
+ for path in (self.path, self._tmp_path):
380
+ with contextlib.suppress(FileNotFoundError):
381
+ os.unlink(path)
382
+ _fsync_dir(self.base)
383
+ finally:
384
+ self._release_lock(unlink=clean)
385
+ return clean
386
+
387
+ def _release_lock(self, *, unlink: bool) -> None:
388
+ if self._lock_fd is None:
389
+ return
390
+ try:
391
+ if unlink: # still holding the lock, so nobody else owns this path
392
+ with contextlib.suppress(FileNotFoundError):
393
+ os.unlink(self.lock_path)
394
+ finally:
395
+ os.close(self._lock_fd)
396
+ self._lock_fd = None
397
+
398
+ # -- records -------------------------------------------------------------
399
+
400
+ @property
401
+ def closed(self) -> bool:
402
+ return self._lock_fd is None
403
+
404
+ @property
405
+ def live(self) -> list[Entry]:
406
+ return list(self._live)
407
+
408
+ def add(self, entry: Entry) -> bool:
409
+ """Record a resource before it is created. Returns False if it was
410
+ already live. Raises if it cannot be written durably: the caller must
411
+ then not create the resource."""
412
+ check_entry(entry, self.base, self.prefix)
413
+ if entry in self._live:
414
+ return False
415
+ self._append(entry.to_line("add"))
416
+ self._live[entry] = None
417
+ return True
418
+
419
+ def release(self, entry: Entry) -> None:
420
+ """Record that a resource is gone. No-op if it was not live."""
421
+ if entry not in self._live:
422
+ return
423
+ self._append(entry.to_line("del"))
424
+ del self._live[entry]
425
+ if self._lines > _COMPACT_MIN and self._lines > 4 * len(self._live):
426
+ self.reset(list(self._live))
427
+
428
+ def reset(self, entries: Sequence[Entry]) -> None:
429
+ """Replace the ledger with `entries` as the only live records (after
430
+ recovery, or to compact it). Atomic: a crash leaves the old or the new
431
+ file, never a mix."""
432
+ for entry in entries:
433
+ check_entry(entry, self.base, self.prefix)
434
+ self._require_open()
435
+ if self._fd is not None:
436
+ os.close(self._fd)
437
+ self._fd = None
438
+ with contextlib.suppress(FileNotFoundError):
439
+ os.unlink(self._tmp_path)
440
+ fd = os.open(self._tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _FLAGS, 0o600)
441
+ try:
442
+ _write_all(fd, b"".join(e.to_line("add") for e in entries))
443
+ os.fsync(fd)
444
+ finally:
445
+ os.close(fd)
446
+ os.replace(self._tmp_path, self.path)
447
+ _fsync_dir(self.base)
448
+ self._live = dict.fromkeys(entries)
449
+ self._lines = len(entries)
450
+
451
+ def _require_open(self) -> None:
452
+ if self._lock_fd is None:
453
+ raise IsolationError("ledger is closed")
454
+
455
+ def _append(self, line: bytes) -> None:
456
+ self._require_open()
457
+ if self._fd is None:
458
+ created = not os.path.lexists(self.path)
459
+ self._fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | _FLAGS, 0o600)
460
+ try:
461
+ _check_own_file(self._fd, self.path)
462
+ if created:
463
+ _fsync_dir(self.base)
464
+ except BaseException:
465
+ os.close(self._fd)
466
+ self._fd = None
467
+ raise
468
+ _write_all(self._fd, line)
469
+ os.fsync(self._fd)
470
+ self._lines += 1
471
+
472
+
473
+ # --------------------------------------------------------------------------
474
+ # Recovery
475
+ # --------------------------------------------------------------------------
476
+
477
+ Runner = Callable[..., Awaitable[CommandResult]]
478
+
479
+
480
+ @dataclass(slots=True)
481
+ class RecoveryReport:
482
+ removed: list[str] = field(default_factory=list) # existed and were removed
483
+ absent: list[str] = field(default_factory=list) # already gone
484
+ failed: list[tuple[Entry, str]] = field(default_factory=list) # still there
485
+ rejected: list[str] = field(default_factory=list) # ledger lines never acted on
486
+
487
+ @property
488
+ def failed_entries(self) -> list[Entry]:
489
+ return [e for e, _ in self.failed]
490
+
491
+ def summary(self) -> str:
492
+ parts = [f"{len(self.removed)} removed", f"{len(self.absent)} already gone"]
493
+ if self.failed:
494
+ parts.append("failed: " + "; ".join(f"{e.describe()}: {why}" for e, why in self.failed))
495
+ if self.rejected:
496
+ parts.append("rejected: " + "; ".join(self.rejected))
497
+ return ", ".join(parts)
498
+
499
+
500
+ def _cmdline(proc_root: Path, pid: int) -> list[bytes] | None:
501
+ try:
502
+ with open(proc_root / str(pid) / "cmdline", "rb") as f:
503
+ data = f.read(_MAX_CMDLINE)
504
+ except OSError:
505
+ return None
506
+ if not data:
507
+ return None
508
+ return data.rstrip(b"\0").split(b"\0")
509
+
510
+
511
+ def _arg(argv: list[bytes], flag: bytes) -> bytes | None:
512
+ for i, arg in enumerate(argv[:-1]):
513
+ if arg == flag:
514
+ return argv[i + 1]
515
+ return None
516
+
517
+
518
+ def _same_dir(a: Path, b: Path) -> bool:
519
+ try:
520
+ sa, sb = os.stat(a), os.stat(b)
521
+ except OSError:
522
+ return False
523
+ return (sa.st_dev, sa.st_ino) == (sb.st_dev, sb.st_ino)
524
+
525
+
526
+ def _in_cgroup(proc_root: Path, pid: int, parent: str, vm_id: str) -> bool:
527
+ try:
528
+ with open(proc_root / str(pid) / "cgroup", "rb") as f:
529
+ data = f.read(4096)
530
+ except OSError:
531
+ return False
532
+ return f"0::/{parent}/{vm_id}".encode() in data.splitlines()
533
+
534
+
535
+ def is_vmm(
536
+ pid: int,
537
+ vm_id: str,
538
+ base: Path,
539
+ *,
540
+ cgroup_parent: str | None = None,
541
+ proc_root: Path = Path("/proc"),
542
+ ) -> bool:
543
+ """True if `pid` is the jailer or the jailed Firecracker of `vm_id` under
544
+ the jail base `base`. Reads only host facts: the command line must carry
545
+ `--id <vm_id>`, and
546
+
547
+ - Firecracker (after the jailer's exec) must have the VM's jail as its
548
+ root directory (same device and inode; the jailer pivots into it in its
549
+ own mount namespace, so the link text is useless), or sit in the VM's
550
+ cgroup `<cgroup_parent>/<vm_id>` when one is given;
551
+ - the jailer (before its exec) must name this base and a Firecracker
552
+ binary.
553
+ """
554
+ argv = _cmdline(proc_root, pid)
555
+ if not argv or _arg(argv, b"--id") != validate_vm_id(vm_id).encode():
556
+ return False
557
+ prog = os.path.basename(argv[0]).decode("ascii", "replace")
558
+ try:
559
+ layout = JailLayout(base, prog, vm_id) # prog is a firecracker exec name
560
+ except ValueError:
561
+ layout = None
562
+ if layout is not None:
563
+ if _same_dir(proc_root / str(pid) / "root", layout.root):
564
+ return True
565
+ return cgroup_parent is not None and _in_cgroup(proc_root, pid, cgroup_parent, vm_id)
566
+ if "jailer" in prog:
567
+ exec_file = _arg(argv, b"--exec-file")
568
+ chroot_base = _arg(argv, b"--chroot-base-dir")
569
+ if exec_file is None or chroot_base != os.fsencode(base):
570
+ return False
571
+ try:
572
+ JailLayout(base, os.path.basename(exec_file).decode("ascii"), vm_id)
573
+ except (ValueError, UnicodeDecodeError):
574
+ return False
575
+ return True
576
+ return False
577
+
578
+
579
+ def _scan(proc_root: Path, vm_ids: set[str]) -> dict[int, str]:
580
+ """pid -> vm id for every process whose command line names one of
581
+ `vm_ids` with `--id`. Candidates only; is_vmm decides."""
582
+ found: dict[int, str] = {}
583
+ try:
584
+ names = os.listdir(proc_root)
585
+ except OSError:
586
+ return found
587
+ for name in names:
588
+ if not name.isdigit():
589
+ continue
590
+ argv = _cmdline(proc_root, int(name))
591
+ if not argv:
592
+ continue
593
+ value = _arg(argv, b"--id")
594
+ if value is not None:
595
+ text = value.decode("ascii", "replace")
596
+ if text in vm_ids:
597
+ found[int(name)] = text
598
+ return found
599
+
600
+
601
+ def _wait_pidfd(fd: int, timeout: float) -> bool:
602
+ poller = select.poll()
603
+ poller.register(fd, select.POLLIN)
604
+ return bool(poller.poll(int(timeout * 1000)))
605
+
606
+
607
+ async def _kill_vmm(
608
+ pid: int, vm_id: str, base: Path, cgroup_parent: str | None, proc_root: Path, wait: float
609
+ ) -> bool:
610
+ """Kill one verified VMM. True if it was ours and is now dead, False if it
611
+ was not running or not ours. Raises if it survives."""
612
+ try:
613
+ fd = os.pidfd_open(pid)
614
+ except ProcessLookupError:
615
+ return False
616
+ try:
617
+ # The pidfd pins the process: if the pid was recycled before it was
618
+ # opened, the check below reads the new process and rejects it.
619
+ if not is_vmm(pid, vm_id, base, cgroup_parent=cgroup_parent, proc_root=proc_root):
620
+ return False
621
+ with contextlib.suppress(ProcessLookupError):
622
+ signal.pidfd_send_signal(fd, signal.SIGKILL)
623
+ if not await asyncio.to_thread(_wait_pidfd, fd, wait):
624
+ raise IsolationError(f"VMM {pid} ({vm_id}) did not exit within {wait}s of SIGKILL")
625
+ return True
626
+ finally:
627
+ os.close(fd)
628
+
629
+
630
+ def _lstat(path: Path) -> os.stat_result | None:
631
+ try:
632
+ return os.lstat(path)
633
+ except FileNotFoundError:
634
+ return None
635
+
636
+
637
+ def _plain_dir(path: Path, what: str) -> bool:
638
+ """True if `path` is a real directory, False if absent. Raises otherwise."""
639
+ st = _lstat(path)
640
+ if st is None:
641
+ return False
642
+ if not stat.S_ISDIR(st.st_mode):
643
+ raise IsolationError(f"{what} is not a plain directory: {path}")
644
+ return True
645
+
646
+
647
+ def _rmdir_retry(path: Path, deadline: float) -> None:
648
+ while True:
649
+ try:
650
+ os.rmdir(path)
651
+ return
652
+ except FileNotFoundError:
653
+ return
654
+ except OSError as e:
655
+ # A killed VMM can take a moment to leave its cgroup.
656
+ if e.errno != errno.EBUSY or time.monotonic() >= deadline:
657
+ raise
658
+ time.sleep(0.05)
659
+
660
+
661
+ async def recover(
662
+ entries: Iterable[Entry],
663
+ *,
664
+ base: Path,
665
+ runner: Runner = run_command,
666
+ proc_root: Path = Path("/proc"),
667
+ cgroup_root: Path = CGROUP_ROOT,
668
+ command_timeout: float = 10.0,
669
+ kill_wait: float = 10.0,
670
+ total_timeout: float = 300.0,
671
+ ) -> RecoveryReport:
672
+ """Remove every recorded resource that still exists, by its exact name.
673
+ Entries must already be validated (Ledger does that). Never raises for a
674
+ single resource: failures are collected in the report. Bounded by
675
+ `total_timeout`; whatever was not reached by then is reported failed."""
676
+ report = RecoveryReport()
677
+ by_kind: dict[str, list[Entry]] = {k: [] for k in _ORDER}
678
+ for entry in dict.fromkeys(entries):
679
+ by_kind[entry.kind].append(entry)
680
+ pending: dict[Entry, None] = {e: None for k in _ORDER for e in by_kind[k]}
681
+
682
+ def done(entry: Entry, removed: bool) -> None:
683
+ (report.removed if removed else report.absent).append(entry.describe())
684
+ pending.pop(entry, None)
685
+
686
+ def fail(entry: Entry, error: BaseException | str) -> None:
687
+ why = error if isinstance(error, str) else f"{type(error).__name__}: {error}"
688
+ report.failed.append((entry, why[:300]))
689
+ pending.pop(entry, None)
690
+
691
+ async def run(argv: list[str], check: bool = True) -> CommandResult:
692
+ return await runner(argv, timeout=command_timeout, check=check, max_output=65536)
693
+
694
+ async def body() -> None:
695
+ # 1. Processes: recorded pids, and any VMM still running for a recorded
696
+ # vm id (closes the window before its pid was recorded).
697
+ vm_ids = {e.get("vm_id") for e in by_kind["vmm"] + by_kind["jail"]}
698
+ scanned = await asyncio.to_thread(_scan, proc_root, vm_ids) if vm_ids else {}
699
+ cgroups = {e.get("vm_id"): e.get("parent") for e in by_kind["cgroup"]}
700
+ alive: set[str] = set() # vm ids with a VMM that survived
701
+ for entry in by_kind["vmm"]:
702
+ pid, vm_id = entry.get("pid"), entry.get("vm_id")
703
+ scanned.pop(pid, None)
704
+ try:
705
+ done(entry, await _kill_vmm(pid, vm_id, base, cgroups.get(vm_id), proc_root, kill_wait))
706
+ except Exception as e:
707
+ alive.add(vm_id)
708
+ fail(entry, e)
709
+ for pid, vm_id in scanned.items():
710
+ try:
711
+ if await _kill_vmm(pid, vm_id, base, cgroups.get(vm_id), proc_root, kill_wait):
712
+ report.removed.append(f"vmm pid={pid} vm_id={vm_id} (found running)")
713
+ except Exception as e:
714
+ alive.add(vm_id)
715
+ report.failed.append((Entry.vmm(pid, vm_id), f"{type(e).__name__}: {e}"[:300]))
716
+
717
+ # 2. Jails: no symlinks followed (fd-based rmtree).
718
+ for entry in by_kind["jail"]:
719
+ if entry.get("vm_id") in alive:
720
+ fail(entry, "its VMM is still running")
721
+ continue
722
+ try:
723
+ layout = JailLayout(base, entry.get("exec"), entry.get("vm_id"))
724
+ if not _plain_dir(layout.id_dir.parent, "jail parent") or not _plain_dir(layout.id_dir, "jail"):
725
+ done(entry, False)
726
+ continue
727
+ await asyncio.to_thread(remove_jail, layout)
728
+ done(entry, True)
729
+ except Exception as e:
730
+ fail(entry, e)
731
+
732
+ # 3. Namespaces, by exact name, if listed.
733
+ if by_kind["netns"]:
734
+ try:
735
+ out = (await run(["ip", "-j", "netns", "list"])).stdout
736
+ present = {e.get("name") for e in json.loads(out or b"[]") if isinstance(e, dict)}
737
+ except Exception as e:
738
+ for entry in by_kind["netns"]:
739
+ fail(entry, e)
740
+ else:
741
+ for entry in by_kind["netns"]:
742
+ name = validate_netns(entry.get("name"))
743
+ if name not in present:
744
+ done(entry, False)
745
+ continue
746
+ try:
747
+ await run(["ip", "netns", "del", name])
748
+ done(entry, True)
749
+ except Exception as e:
750
+ fail(entry, e)
751
+
752
+ # 4. Host-side veths. Deleting a namespace removes its veth
753
+ # asynchronously, so one that vanishes meanwhile is not an error.
754
+ for entry in by_kind["link"]:
755
+ name = validate_interface(entry.get("name"))
756
+ try:
757
+ if (await run(["ip", "link", "show", "dev", name], check=False)).returncode != 0:
758
+ done(entry, False)
759
+ continue
760
+ r = await run(["ip", "link", "del", "dev", name], check=False)
761
+ if r.returncode != 0:
762
+ if (await run(["ip", "link", "show", "dev", name], check=False)).returncode == 0:
763
+ raise IsolationError(r.stderr[-300:].decode("utf-8", "replace").strip())
764
+ done(entry, True)
765
+ except Exception as e:
766
+ fail(entry, e)
767
+
768
+ # 5. The host nftables table.
769
+ for entry in by_kind["table"]:
770
+ name = validate_nft_table(entry.get("name"))
771
+ try:
772
+ if (await run(["nft", "list", "table", "inet", name], check=False)).returncode != 0:
773
+ done(entry, False)
774
+ continue
775
+ await run(["nft", "delete", "table", "inet", name])
776
+ done(entry, True)
777
+ except Exception as e:
778
+ fail(entry, e)
779
+
780
+ # 6. Cgroups (empty once their VMM is gone).
781
+ deadline = time.monotonic() + kill_wait
782
+ for entry in by_kind["cgroup"]:
783
+ if entry.get("vm_id") in alive:
784
+ fail(entry, "its VMM is still running")
785
+ continue
786
+ parent = cgroup_root / entry.get("parent")
787
+ path = parent / validate_vm_id(entry.get("vm_id"))
788
+ try:
789
+ if not _plain_dir(parent, "cgroup parent") or not _plain_dir(path, "cgroup"):
790
+ done(entry, False)
791
+ continue
792
+ await asyncio.to_thread(_rmdir_retry, path, deadline)
793
+ done(entry, True)
794
+ except Exception as e:
795
+ fail(entry, e)
796
+
797
+ # 7. The template workdir.
798
+ for entry in by_kind["workdir"]:
799
+ path = base / entry.get("name")
800
+ try:
801
+ if not _plain_dir(path, "workdir"):
802
+ done(entry, False)
803
+ continue
804
+ await asyncio.to_thread(shutil.rmtree, path)
805
+ done(entry, True)
806
+ except Exception as e:
807
+ fail(entry, e)
808
+
809
+ try:
810
+ async with asyncio.timeout(total_timeout):
811
+ await body()
812
+ except TimeoutError:
813
+ for entry in list(pending):
814
+ fail(entry, f"recovery timed out after {total_timeout}s")
815
+ return report