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.
@@ -0,0 +1,948 @@
1
+ """FirecrackerEngine: the Engine protocol on Firecracker v1.18 under the jailer.
2
+
3
+ The only module (with _jailer.py) that knows about Firecracker
4
+ (docs/40-rules.md rule 18).
5
+
6
+ Template build: cold boot under the jailer in the given namespace, wait for
7
+ the guest agent to accept a vsock connection on VSOCK_PORT, pause, write a
8
+ Full snapshot, then move the snapshot and the template's scratch drive into
9
+ `workdir`.
10
+
11
+ Restore: a new jail per VM with the snapshot state, memory file and shared
12
+ rootfs hard-linked in read-only, and a private copy of the template's scratch
13
+ drive, all at the paths the snapshot recorded. The jailer joins the VM's
14
+ namespace (no network_overrides); the namespace provides `tap0` with TAP_MAC.
15
+
16
+ Teardown: kill() stops the process and removes its sockets; list_changes()
17
+ reads the scratch drive with debugfs as the jail uid, never mounting it
18
+ (rule 6); cleanup() removes the jail directory, including the scratch drive.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import collections
25
+ import contextlib
26
+ import json
27
+ import logging
28
+ import os
29
+ import re
30
+ import shutil
31
+ import signal
32
+ import stat
33
+ from collections.abc import Iterable, Mapping, Sequence
34
+ from dataclasses import dataclass, field
35
+ from pathlib import Path
36
+ from typing import Any
37
+
38
+ from emberpool._jailer import (
39
+ IN_JAIL_KERNEL,
40
+ IN_JAIL_MEM,
41
+ IN_JAIL_ROOTFS,
42
+ IN_JAIL_SCRATCH,
43
+ IN_JAIL_STATE,
44
+ IN_JAIL_VSOCK,
45
+ JailerConfig,
46
+ JailLayout,
47
+ check_cgroup,
48
+ create_jail,
49
+ jailer_argv,
50
+ netns_path,
51
+ remove_cgroup,
52
+ remove_jail,
53
+ )
54
+ from emberpool._names import (
55
+ CommandError,
56
+ new_vm_id,
57
+ run_command,
58
+ validate_netns,
59
+ validate_vm_id,
60
+ )
61
+ from emberpool._types import (
62
+ TAP_NAME,
63
+ VSOCK_PORT,
64
+ EmberpoolError,
65
+ IsolationError,
66
+ Template,
67
+ VMHandle,
68
+ )
69
+ from emberpool.engine import ExecClient
70
+
71
+ __all__ = [
72
+ "FirecrackerConfig",
73
+ "FirecrackerEngine",
74
+ "DEFAULT_BOOT_ARGS",
75
+ "GUEST_MAC",
76
+ "GUEST_CID",
77
+ "SCRATCH_BASE_NAME",
78
+ "LsEntry",
79
+ "parse_ls_sections",
80
+ "diff_listings",
81
+ ]
82
+
83
+ log = logging.getLogger("emberpool.firecracker")
84
+
85
+ GUEST_MAC = "06:00:ac:10:00:02"
86
+ GUEST_CID = 3
87
+ # Template scratch drive as of the snapshot, kept next to the snapshot state.
88
+ # Every clone starts from a copy of it: the guest kernel's view of that
89
+ # filesystem is part of the snapshot, so an empty drive would corrupt it.
90
+ SCRATCH_BASE_NAME = "scratch.ext4"
91
+ _ROOTFS_NAME = "rootfs.ext4"
92
+ _STATE_NAME = "snapshot.state"
93
+ _MEM_NAME = "snapshot.mem"
94
+
95
+ # No console: guest serial output is not needed and is guest-controlled.
96
+ # The guest image configures eth0 (GUEST_IP, default route via TAP_HOST_IP).
97
+ DEFAULT_BOOT_ARGS = "reboot=k panic=1 pci=off"
98
+
99
+ # Host-tool environment and output caps.
100
+ _ENV: Mapping[str, str] = {
101
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
102
+ "LC_ALL": "C",
103
+ }
104
+ _OUTPUT_TAIL_BYTES = 16 * 1024
105
+ _HTTP_MAX_HEADER = 16 * 1024
106
+ _HTTP_MAX_BODY = 64 * 1024
107
+ _FAULT_MAX_CHARS = 300
108
+ _READY_LINE_MAX = 64
109
+ _DEBUGFS_MAX_OUTPUT = 16 * 1024 * 1024
110
+ _DEBUGFS_BATCH = 256
111
+ _MAX_NAME_CHARS = 1024
112
+ _BOOT_ARGS_RE = re.compile(r"[\x20-\x7e]{1,2048}")
113
+ _UPPER_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
114
+ _READY_RE = re.compile(rb"OK [0-9]{1,10}\n")
115
+
116
+
117
+ def _positive(name: str, value: object) -> float:
118
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 < value < 1e6:
119
+ raise ValueError(f"{name} must be a positive number: {value!r}")
120
+ return float(value)
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class FirecrackerConfig:
125
+ """Paths, VM shape and limits for FirecrackerEngine.
126
+
127
+ `kernel_path` and `rootfs_path` are copied into the template workdir;
128
+ the rootfs must be a clean ext4 image (no pending journal recovery),
129
+ because every VM opens it read-only. The template workdir and
130
+ `jailer.chroot_base` must be on the same filesystem: clones get the
131
+ snapshot files as hard links.
132
+
133
+ `scratch_upper_dir` is the directory on the scratch drive that the guest
134
+ uses as its overlayfs upper layer. list_changes reports paths below it.
135
+ If the drive has no such directory, it reports everything except
136
+ `lost+found`.
137
+ """
138
+
139
+ jailer: JailerConfig
140
+ kernel_path: Path
141
+ rootfs_path: Path
142
+ vcpu_count: int = 1
143
+ mem_size_mib: int = 512
144
+ scratch_size_mib: int = 1024
145
+ boot_args: str = DEFAULT_BOOT_ARGS
146
+ scratch_upper_dir: str = "upper"
147
+ boot_timeout: float = 120.0
148
+ api_timeout: float = 10.0
149
+ snapshot_timeout: float = 300.0
150
+ restore_timeout: float = 60.0
151
+ kill_timeout: float = 10.0
152
+ copy_timeout: float = 300.0
153
+ vmgenid_timeout: float = 30.0
154
+ changes_timeout: float = 30.0
155
+ max_changes: int = 10_000
156
+ max_scan_entries: int = 100_000
157
+ max_depth: int = 32
158
+
159
+ def __post_init__(self) -> None:
160
+ if not isinstance(self.jailer, JailerConfig):
161
+ raise TypeError("jailer must be a JailerConfig")
162
+ for name in ("kernel_path", "rootfs_path"):
163
+ value = getattr(self, name)
164
+ if not isinstance(value, Path):
165
+ object.__setattr__(self, name, Path(value))
166
+ for name, lo, hi in (
167
+ ("vcpu_count", 1, 32),
168
+ ("mem_size_mib", 128, 1 << 20),
169
+ ("scratch_size_mib", 16, 1 << 20),
170
+ ("max_changes", 1, 10_000_000),
171
+ ("max_scan_entries", 1, 10_000_000),
172
+ ("max_depth", 1, 4096),
173
+ ):
174
+ value = getattr(self, name)
175
+ if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
176
+ raise ValueError(f"{name} must be an int in {lo}..{hi}: {value!r}")
177
+ if not isinstance(self.boot_args, str) or _BOOT_ARGS_RE.fullmatch(self.boot_args) is None:
178
+ raise ValueError("boot_args must be printable ASCII")
179
+ if (
180
+ not isinstance(self.scratch_upper_dir, str)
181
+ or _UPPER_RE.fullmatch(self.scratch_upper_dir) is None
182
+ or self.scratch_upper_dir in (".", "..")
183
+ ):
184
+ raise ValueError(f"invalid scratch_upper_dir: {self.scratch_upper_dir!r}")
185
+ for name in (
186
+ "boot_timeout",
187
+ "api_timeout",
188
+ "snapshot_timeout",
189
+ "restore_timeout",
190
+ "kill_timeout",
191
+ "copy_timeout",
192
+ "vmgenid_timeout",
193
+ "changes_timeout",
194
+ ):
195
+ object.__setattr__(self, name, _positive(name, getattr(self, name)))
196
+
197
+
198
+ # --------------------------------------------------------------------------
199
+ # Process output: drained continuously, last bytes kept for error messages
200
+ # --------------------------------------------------------------------------
201
+
202
+
203
+ class _Tail:
204
+ def __init__(self, cap: int = _OUTPUT_TAIL_BYTES) -> None:
205
+ self._buf: collections.deque[bytes] = collections.deque()
206
+ self._size = 0
207
+ self._cap = cap
208
+
209
+ def add(self, chunk: bytes) -> None:
210
+ self._buf.append(chunk)
211
+ self._size += len(chunk)
212
+ while self._size > self._cap and self._buf:
213
+ self._size -= len(self._buf.popleft())
214
+
215
+ def text(self, limit: int = 2000) -> str:
216
+ """Escaped, printable tail. VMM output can contain guest serial
217
+ output, so it is shown escaped and only in error messages."""
218
+ data = b"".join(self._buf)[-limit:]
219
+ return data.decode("ascii", "backslashreplace").encode("unicode_escape").decode("ascii")
220
+
221
+
222
+ async def _drain(stream: asyncio.StreamReader, tail: _Tail) -> None:
223
+ with contextlib.suppress(Exception):
224
+ while chunk := await stream.read(4096):
225
+ tail.add(chunk)
226
+
227
+
228
+ # --------------------------------------------------------------------------
229
+ # Firecracker API over its Unix socket
230
+ # --------------------------------------------------------------------------
231
+
232
+
233
+ class _ApiError(IsolationError):
234
+ """The Firecracker API returned an error or a malformed response. A VM
235
+ whose VMM cannot be driven as asked is not started (fail closed)."""
236
+
237
+
238
+ def _fault_message(body: bytes) -> str:
239
+ try:
240
+ data = json.loads(body.decode("utf-8"))
241
+ msg = data.get("fault_message") if isinstance(data, dict) else None
242
+ except (UnicodeDecodeError, ValueError):
243
+ msg = None
244
+ if not isinstance(msg, str):
245
+ msg = body[:_FAULT_MAX_CHARS].decode("ascii", "backslashreplace")
246
+ return repr(msg[:_FAULT_MAX_CHARS])
247
+
248
+
249
+ def parse_http_head(head: bytes) -> tuple[int, dict[str, str]]:
250
+ """Parse an HTTP/1.1 status line and headers (terminated by CRLFCRLF)."""
251
+ try:
252
+ text = head.decode("ascii")
253
+ except UnicodeDecodeError:
254
+ raise _ApiError("non-ASCII HTTP response header") from None
255
+ lines = text.split("\r\n")
256
+ m = re.fullmatch(r"HTTP/1\.[01] ([1-5][0-9]{2})(?: .*)?", lines[0])
257
+ if m is None:
258
+ raise _ApiError(f"bad HTTP status line: {lines[0][:80]!r}")
259
+ headers: dict[str, str] = {}
260
+ for line in lines[1:]:
261
+ if not line:
262
+ continue
263
+ name, sep, value = line.partition(":")
264
+ if not sep:
265
+ raise _ApiError("bad HTTP header line")
266
+ headers[name.strip().lower()] = value.strip()
267
+ return int(m.group(1)), headers
268
+
269
+
270
+ async def _api_call(
271
+ sock: Path, method: str, path: str, body: dict[str, Any] | None, timeout: float
272
+ ) -> bytes:
273
+ """One request on a fresh connection. Returns the body of a 2xx reply,
274
+ raises _ApiError otherwise. Sizes are capped: a compromised VMM is not
275
+ trusted either."""
276
+ payload = b"" if body is None else json.dumps(body, separators=(",", ":")).encode("utf-8")
277
+ head = f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nAccept: application/json\r\n"
278
+ if body is not None:
279
+ head += "Content-Type: application/json\r\n"
280
+ head += f"Content-Length: {len(payload)}\r\n\r\n"
281
+ async with asyncio.timeout(timeout):
282
+ reader, writer = await asyncio.open_unix_connection(str(sock), limit=_HTTP_MAX_HEADER)
283
+ try:
284
+ writer.write(head.encode("ascii") + payload)
285
+ await writer.drain()
286
+ try:
287
+ raw = await reader.readuntil(b"\r\n\r\n")
288
+ except asyncio.LimitOverrunError:
289
+ raise _ApiError("HTTP response header too large") from None
290
+ except asyncio.IncompleteReadError:
291
+ raise _ApiError("connection closed before HTTP response") from None
292
+ status, headers = parse_http_head(raw[:-4])
293
+ length_text = headers.get("content-length", "0")
294
+ if not length_text.isdigit() or int(length_text) > _HTTP_MAX_BODY:
295
+ raise _ApiError(f"bad Content-Length: {length_text[:20]!r}")
296
+ try:
297
+ data = await reader.readexactly(int(length_text))
298
+ except asyncio.IncompleteReadError:
299
+ raise _ApiError("short HTTP response body") from None
300
+ finally:
301
+ writer.close()
302
+ with contextlib.suppress(Exception):
303
+ await writer.wait_closed()
304
+ if not 200 <= status < 300:
305
+ raise _ApiError(f"{method} {path} returned {status}: {_fault_message(data)}")
306
+ return data
307
+
308
+
309
+ # --------------------------------------------------------------------------
310
+ # Scratch drive listing with debugfs (userspace, never mounted)
311
+ # --------------------------------------------------------------------------
312
+
313
+
314
+ @dataclass(frozen=True, slots=True)
315
+ class LsEntry:
316
+ """One directory entry from `debugfs ls -l`. Names are as debugfs escapes
317
+ them (non-printable bytes become \\xNN), so they never contain newlines."""
318
+
319
+ ino: int
320
+ mode: int
321
+ size: int
322
+ mtime: str
323
+ name: str
324
+
325
+ @property
326
+ def is_dir(self) -> bool:
327
+ return stat.S_ISDIR(self.mode)
328
+
329
+
330
+ _LS_LINE_RE = re.compile(
331
+ r" *([0-9]{1,10}) +([0-7]{1,7}) +\(([0-9]{1,3})\) +([0-9]{1,10}) +([0-9]{1,10}) +"
332
+ r"([0-9]{1,20}(?:, *[0-9]{1,10})?) +(\S{1,32} \S{1,16}) (.*)"
333
+ )
334
+ _LS_CMD_RE = re.compile(r"debugfs: ls -l <([0-9]{1,10})>")
335
+
336
+
337
+ def parse_ls_sections(output: str, expected: Sequence[int]) -> dict[int, list[LsEntry]]:
338
+ """Split `debugfs -f` output for a batch of `ls -l <ino>` commands into
339
+ entries per directory inode.
340
+
341
+ Only sections whose echo line names an inode in `expected` are kept.
342
+ Entry lines that do not parse are skipped (the result is advisory).
343
+ """
344
+ wanted = set(expected)
345
+ out: dict[int, list[LsEntry]] = {}
346
+ current: list[LsEntry] | None = None
347
+ for line in output.split("\n"):
348
+ line = line.rstrip("\r")
349
+ cmd = _LS_CMD_RE.fullmatch(line.rstrip())
350
+ if cmd is not None:
351
+ ino = int(cmd.group(1))
352
+ current = out.setdefault(ino, []) if ino in wanted else None
353
+ continue
354
+ if current is None:
355
+ continue
356
+ m = _LS_LINE_RE.fullmatch(line)
357
+ if m is None:
358
+ continue
359
+ name = m.group(8)
360
+ if not name or len(name) > _MAX_NAME_CHARS or name in (".", ".."):
361
+ continue
362
+ size_text = m.group(6).split(",")[0]
363
+ current.append(
364
+ LsEntry(
365
+ ino=int(m.group(1)),
366
+ mode=int(m.group(2), 8),
367
+ size=int(size_text),
368
+ mtime=m.group(7),
369
+ name=name,
370
+ )
371
+ )
372
+ return out
373
+
374
+
375
+ def diff_listings(
376
+ base: Mapping[str, LsEntry], current: Mapping[str, LsEntry], limit: int
377
+ ) -> tuple[str, ...]:
378
+ """Paths that are new, changed or removed relative to `base`. Directories
379
+ that exist in both are not reported (their mtime changes whenever a child
380
+ does). Changes are detected by inode, mode, size and minute-resolution
381
+ mtime: advisory, end state only."""
382
+ changed: list[str] = []
383
+ for path, entry in current.items():
384
+ old = base.get(path)
385
+ if old is None:
386
+ changed.append(path)
387
+ elif entry.is_dir and old.is_dir:
388
+ continue
389
+ elif (entry.ino, entry.mode, entry.size, entry.mtime) != (old.ino, old.mode, old.size, old.mtime):
390
+ changed.append(path)
391
+ changed.extend(path for path in base if path not in current)
392
+ changed.sort()
393
+ return tuple(changed[:limit])
394
+
395
+
396
+ # --------------------------------------------------------------------------
397
+ # Engine
398
+ # --------------------------------------------------------------------------
399
+
400
+
401
+ @dataclass(eq=False)
402
+ class _VM:
403
+ layout: JailLayout
404
+ netns: str
405
+ scratch_base: Path | None = None
406
+ proc: asyncio.subprocess.Process | None = None
407
+ drain: asyncio.Task[None] | None = None
408
+ tail: _Tail = field(default_factory=_Tail)
409
+ killed: bool = False
410
+
411
+
412
+ class FirecrackerEngine:
413
+ """Engine protocol on Firecracker under the jailer. Must run as root.
414
+
415
+ `exec_client` is used only by check_vmgenid. Without one, check_vmgenid
416
+ returns False (fail closed).
417
+ """
418
+
419
+ def __init__(self, config: FirecrackerConfig, exec_client: ExecClient | None = None) -> None:
420
+ self.config = config
421
+ self._exec = exec_client
422
+ self._vms: dict[str, _VM] = {}
423
+ self._base_listings: dict[Path, dict[str, LsEntry]] = {}
424
+
425
+ # -- public protocol --------------------------------------------------
426
+
427
+ async def build_template(self, workdir: Path, netns: str) -> Template:
428
+ cfg = self.config
429
+ validate_netns(netns)
430
+ workdir = Path(workdir)
431
+ if not workdir.is_absolute():
432
+ raise ValueError(f"workdir must be absolute: {workdir}")
433
+ workdir.mkdir(parents=True, exist_ok=True, mode=0o755)
434
+ outputs = {
435
+ name: workdir / name for name in (_ROOTFS_NAME, _STATE_NAME, _MEM_NAME, SCRATCH_BASE_NAME)
436
+ }
437
+ existing = [str(p) for p in outputs.values() if os.path.lexists(p)]
438
+ if existing:
439
+ raise EmberpoolError(f"template workdir already holds template files: {existing}")
440
+ self._check_netns(netns)
441
+ cfg.jailer.chroot_base.mkdir(parents=True, exist_ok=True, mode=0o755)
442
+ if os.stat(workdir).st_dev != os.stat(cfg.jailer.chroot_base).st_dev:
443
+ raise EmberpoolError("template workdir and chroot base must be on the same filesystem")
444
+ await self._check_rootfs_clean(cfg.rootfs_path)
445
+
446
+ vm_id = f"tmpl-{new_vm_id()}"
447
+ layout = cfg.jailer.layout(vm_id)
448
+ created: list[Path] = []
449
+ try:
450
+ create_jail(layout)
451
+ vm = self._vms[vm_id] = _VM(layout, netns)
452
+
453
+ rootfs = outputs[_ROOTFS_NAME]
454
+ await run_command(
455
+ ["cp", "--sparse=always", "--", str(cfg.rootfs_path), str(rootfs)],
456
+ timeout=cfg.copy_timeout,
457
+ )
458
+ created.append(rootfs)
459
+ _seal(rootfs, cfg.jailer.gid)
460
+ os.link(rootfs, layout.host(IN_JAIL_ROOTFS))
461
+ await asyncio.to_thread(shutil.copyfile, cfg.kernel_path, layout.host(IN_JAIL_KERNEL))
462
+ os.chmod(layout.host(IN_JAIL_KERNEL), 0o444)
463
+ await self._make_scratch(layout.scratch)
464
+
465
+ await self._spawn(vm)
466
+ sock = layout.api_sock
467
+ async with asyncio.timeout(cfg.api_timeout * 4):
468
+ await self._wait_api(vm)
469
+ self._check_cgroup(vm)
470
+ for method, path, body in self._boot_requests():
471
+ await _api_call(sock, method, path, body, cfg.api_timeout)
472
+ await self._wait_agent(vm, cfg.boot_timeout)
473
+ await _api_call(sock, "PATCH", "/vm", {"state": "Paused"}, cfg.api_timeout)
474
+ await _api_call(
475
+ sock,
476
+ "PUT",
477
+ "/snapshot/create",
478
+ {
479
+ "snapshot_type": "Full",
480
+ "snapshot_path": IN_JAIL_STATE,
481
+ "mem_file_path": IN_JAIL_MEM,
482
+ },
483
+ cfg.snapshot_timeout,
484
+ )
485
+ await self._stop(vm)
486
+
487
+ for name, in_jail in (
488
+ (_STATE_NAME, IN_JAIL_STATE),
489
+ (_MEM_NAME, IN_JAIL_MEM),
490
+ (SCRATCH_BASE_NAME, IN_JAIL_SCRATCH),
491
+ ):
492
+ src = layout.host(in_jail)
493
+ _check_regular(src)
494
+ os.rename(src, outputs[name])
495
+ created.append(outputs[name])
496
+ _seal(outputs[name], cfg.jailer.gid)
497
+ except BaseException as e:
498
+ for path in created:
499
+ with contextlib.suppress(FileNotFoundError):
500
+ os.unlink(path)
501
+ await self._discard(vm_id)
502
+ if isinstance(e, Exception) and not isinstance(e, EmberpoolError):
503
+ raise IsolationError(f"template build failed: {type(e).__name__}: {e}") from e
504
+ raise
505
+ await self._discard(vm_id)
506
+ return Template(
507
+ outputs[_STATE_NAME], outputs[_MEM_NAME], outputs[_ROOTFS_NAME], outputs[SCRATCH_BASE_NAME]
508
+ )
509
+
510
+ async def restore(self, template: Template, vm_id: str, netns: str) -> VMHandle:
511
+ cfg = self.config
512
+ validate_vm_id(vm_id)
513
+ validate_netns(netns)
514
+ if vm_id in self._vms:
515
+ raise EmberpoolError(f"vm_id already in use: {vm_id}")
516
+ layout = cfg.jailer.layout(vm_id)
517
+ registered = False
518
+ try:
519
+ self._check_netns(netns)
520
+ scratch_base = self._check_template(template)
521
+ create_jail(layout) # fails if the jail exists: never reused, never adopted
522
+ vm = self._vms[vm_id] = _VM(layout, netns, scratch_base=scratch_base)
523
+ registered = True
524
+
525
+ os.link(template.rootfs_path, layout.host(IN_JAIL_ROOTFS))
526
+ os.link(template.state_path, layout.host(IN_JAIL_STATE))
527
+ os.link(template.mem_path, layout.host(IN_JAIL_MEM))
528
+ await run_command(
529
+ ["cp", "--sparse=always", "--", str(scratch_base), str(layout.scratch)],
530
+ timeout=cfg.copy_timeout,
531
+ )
532
+ os.chown(layout.scratch, cfg.jailer.uid, cfg.jailer.gid)
533
+ os.chmod(layout.scratch, 0o600)
534
+
535
+ await self._spawn(vm)
536
+ async with asyncio.timeout(cfg.restore_timeout):
537
+ await self._wait_api(vm)
538
+ self._check_cgroup(vm)
539
+ await _api_call(
540
+ layout.api_sock,
541
+ "PUT",
542
+ "/snapshot/load",
543
+ {
544
+ "snapshot_path": IN_JAIL_STATE,
545
+ "mem_backend": {"backend_type": "File", "backend_path": IN_JAIL_MEM},
546
+ "resume_vm": True,
547
+ },
548
+ cfg.restore_timeout,
549
+ )
550
+ assert vm.proc is not None
551
+ if vm.proc.returncode is not None:
552
+ raise IsolationError(f"VM {vm_id} exited right after restore: {vm.tail.text()}")
553
+ return VMHandle(
554
+ vm_id=vm_id,
555
+ pid=vm.proc.pid,
556
+ vsock_path=layout.vsock,
557
+ scratch_path=layout.scratch,
558
+ netns=netns,
559
+ )
560
+ except BaseException as e:
561
+ if registered:
562
+ await self._discard(vm_id)
563
+ if isinstance(e, Exception) and not isinstance(e, EmberpoolError):
564
+ raise IsolationError(f"restore of {vm_id} failed: {type(e).__name__}: {e}") from e
565
+ raise
566
+
567
+ async def kill(self, vm: VMHandle) -> None:
568
+ state = self._vms.get(validate_vm_id(vm.vm_id))
569
+ if state is None:
570
+ return
571
+ try:
572
+ await self._stop(state)
573
+ finally:
574
+ for path in (state.layout.api_sock, state.layout.vsock):
575
+ with contextlib.suppress(FileNotFoundError):
576
+ os.unlink(path)
577
+
578
+ async def check_vmgenid(self, vm: VMHandle) -> bool:
579
+ """Ask the guest whether a device is bound to the vmgenid driver.
580
+
581
+ This relies on the guest's answer, so the pool must only call it on a
582
+ freshly restored VM that has run no untrusted code, and must not hand
583
+ that VM out afterwards. Any error or unexpected answer is False.
584
+ """
585
+ if self._exec is None:
586
+ log.warning("check_vmgenid: no exec client configured; failing closed")
587
+ return False
588
+ state = self._vms.get(validate_vm_id(vm.vm_id))
589
+ if state is None or state.killed:
590
+ return False
591
+ try:
592
+ result = await asyncio.wait_for(
593
+ self._exec.run(state.layout.vsock, _VMGENID_CODE, self.config.vmgenid_timeout),
594
+ self.config.vmgenid_timeout + 5,
595
+ )
596
+ except Exception as e: # noqa: BLE001 - any failure fails closed
597
+ log.warning("check_vmgenid on %s failed: %s", vm.vm_id, type(e).__name__)
598
+ return False
599
+ return result.exit_code == 0 and result.stdout == "vmgenid:bound\n"
600
+
601
+ async def list_changes(self, vm: VMHandle) -> tuple[str, ...]:
602
+ state = self._vms.get(validate_vm_id(vm.vm_id))
603
+ if state is None:
604
+ raise EmberpoolError(f"unknown VM: {vm.vm_id}")
605
+ if not state.killed:
606
+ raise EmberpoolError(f"list_changes before kill: {vm.vm_id}")
607
+ if state.scratch_base is None:
608
+ raise EmberpoolError(f"VM has no scratch drive: {vm.vm_id}")
609
+ cfg = self.config
610
+ # The VM was killed, so recent writes may sit only in the ext4 journal.
611
+ # debugfs does not replay it, so e2fsck replays it first, in userspace,
612
+ # on images that are thrown away: the VM's own scratch drive, and a
613
+ # private copy of the template's (never the sealed original).
614
+ async with asyncio.timeout(cfg.changes_timeout):
615
+ base = self._base_listings.get(state.scratch_base)
616
+ if base is None:
617
+ tmp = state.layout.id_dir / "scratch-base-scan.ext4"
618
+ try:
619
+ await run_command(
620
+ ["cp", "--sparse=always", "--", str(state.scratch_base), str(tmp)],
621
+ timeout=cfg.changes_timeout,
622
+ )
623
+ os.chown(tmp, cfg.jailer.uid, cfg.jailer.gid)
624
+ os.chmod(tmp, 0o600)
625
+ await self._replay_journal(tmp)
626
+ base = await self._scan(tmp)
627
+ finally:
628
+ with contextlib.suppress(FileNotFoundError):
629
+ os.unlink(tmp)
630
+ self._base_listings[state.scratch_base] = base
631
+ await self._replay_journal(state.layout.scratch)
632
+ current = await self._scan(state.layout.scratch)
633
+ return diff_listings(base, current, cfg.max_changes)
634
+
635
+ async def cleanup(self, vm: VMHandle) -> None:
636
+ await self._discard(validate_vm_id(vm.vm_id))
637
+
638
+ # -- introspection for the pool and tests -------------------------------
639
+
640
+ def tracked(self) -> list[str]:
641
+ """VM ids this engine still holds resources for."""
642
+ return list(self._vms)
643
+
644
+ # -- internals ------------------------------------------------------------
645
+
646
+ def _boot_requests(self) -> list[tuple[str, str, dict[str, Any]]]:
647
+ cfg = self.config
648
+ return [
649
+ ("PUT", "/boot-source", {"kernel_image_path": IN_JAIL_KERNEL, "boot_args": cfg.boot_args}),
650
+ (
651
+ "PUT",
652
+ "/drives/rootfs",
653
+ {
654
+ "drive_id": "rootfs",
655
+ "path_on_host": IN_JAIL_ROOTFS,
656
+ "is_root_device": True,
657
+ "is_read_only": True,
658
+ },
659
+ ),
660
+ (
661
+ "PUT",
662
+ "/drives/scratch",
663
+ {
664
+ "drive_id": "scratch",
665
+ "path_on_host": IN_JAIL_SCRATCH,
666
+ "is_root_device": False,
667
+ "is_read_only": False,
668
+ },
669
+ ),
670
+ (
671
+ "PUT",
672
+ "/machine-config",
673
+ {"vcpu_count": cfg.vcpu_count, "mem_size_mib": cfg.mem_size_mib},
674
+ ),
675
+ (
676
+ "PUT",
677
+ "/network-interfaces/eth0",
678
+ {"iface_id": "eth0", "host_dev_name": TAP_NAME, "guest_mac": GUEST_MAC},
679
+ ),
680
+ ("PUT", "/vsock", {"guest_cid": GUEST_CID, "uds_path": IN_JAIL_VSOCK}),
681
+ ("PUT", "/actions", {"action_type": "InstanceStart"}),
682
+ ]
683
+
684
+ @staticmethod
685
+ def _check_netns(netns: str) -> None:
686
+ path = netns_path(netns)
687
+ if not path.exists():
688
+ raise IsolationError(f"network namespace does not exist: {netns}")
689
+
690
+ def _check_template(self, template: Template) -> Path:
691
+ if not isinstance(template, Template):
692
+ raise TypeError("template must be a Template")
693
+ scratch_base = template.scratch_path or template.state_path.with_name(SCRATCH_BASE_NAME)
694
+ dev = os.stat(self.config.jailer.chroot_base).st_dev
695
+ for path in (template.state_path, template.mem_path, template.rootfs_path, scratch_base):
696
+ st = _check_regular(path)
697
+ if st.st_dev != dev:
698
+ raise EmberpoolError(f"template file not on the chroot filesystem: {path}")
699
+ if st.st_mode & 0o222 or st.st_uid != 0:
700
+ raise EmberpoolError(f"template file must be root-owned and read-only: {path}")
701
+ return scratch_base
702
+
703
+ async def _check_rootfs_clean(self, rootfs: Path) -> None:
704
+ try:
705
+ res = await run_command(["dumpe2fs", "-h", str(rootfs)], timeout=30, max_output=1 << 16)
706
+ except CommandError as e:
707
+ raise EmberpoolError(f"rootfs is not a readable ext4 image: {rootfs}") from e
708
+ text = res.stdout.decode("ascii", "replace")
709
+ features = re.search(r"^Filesystem features:(.*)$", text, re.M)
710
+ state = re.search(r"^Filesystem state:\s*(\S+)", text, re.M)
711
+ if features is None or state is None:
712
+ raise EmberpoolError(f"cannot read ext4 superblock of {rootfs}")
713
+ if "needs_recovery" in features.group(1).split() or state.group(1) != "clean":
714
+ raise EmberpoolError(
715
+ f"rootfs {rootfs} is not clean (journal needs recovery); run e2fsck on it first"
716
+ )
717
+
718
+ async def _make_scratch(self, path: Path) -> None:
719
+ cfg = self.config
720
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
721
+ try:
722
+ os.ftruncate(fd, cfg.scratch_size_mib * 1024 * 1024)
723
+ finally:
724
+ os.close(fd)
725
+ await run_command(
726
+ ["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "epscratch", "--", str(path)],
727
+ timeout=cfg.copy_timeout,
728
+ )
729
+ os.chown(path, cfg.jailer.uid, cfg.jailer.gid)
730
+
731
+ async def _spawn(self, vm: _VM) -> None:
732
+ argv = jailer_argv(self.config.jailer, vm.layout.vm_id, vm.netns)
733
+ vm.proc = await asyncio.create_subprocess_exec(
734
+ *argv,
735
+ stdin=asyncio.subprocess.DEVNULL,
736
+ stdout=asyncio.subprocess.PIPE,
737
+ stderr=asyncio.subprocess.STDOUT,
738
+ env=dict(_ENV),
739
+ start_new_session=True,
740
+ )
741
+ assert vm.proc.stdout is not None
742
+ vm.drain = asyncio.create_task(_drain(vm.proc.stdout, vm.tail))
743
+
744
+ async def _wait_api(self, vm: _VM) -> None:
745
+ """Wait until the API socket accepts connections. Caller bounds it."""
746
+ assert vm.proc is not None
747
+ sock = vm.layout.api_sock
748
+ while True:
749
+ if vm.proc.returncode is not None:
750
+ raise IsolationError(
751
+ f"jailer/firecracker for {vm.layout.vm_id} exited with "
752
+ f"{vm.proc.returncode}: {vm.tail.text()}"
753
+ )
754
+ if sock.exists():
755
+ try:
756
+ _, writer = await asyncio.open_unix_connection(str(sock))
757
+ except OSError:
758
+ pass
759
+ else:
760
+ writer.close()
761
+ with contextlib.suppress(Exception):
762
+ await writer.wait_closed()
763
+ return
764
+ await asyncio.sleep(0.02)
765
+
766
+ def _check_cgroup(self, vm: _VM) -> None:
767
+ """Fail closed unless the VMM sits in its cgroup with every configured
768
+ limit in place. The jailer writes them before it starts Firecracker,
769
+ so they are checked once the API socket is up, before the guest runs."""
770
+ assert vm.proc is not None
771
+ problems = check_cgroup(self.config.jailer, vm.layout.vm_id, vm.proc.pid)
772
+ if problems:
773
+ raise IsolationError(f"cgroup limits for {vm.layout.vm_id} not in place: " + "; ".join(problems))
774
+
775
+ async def _wait_agent(self, vm: _VM, timeout: float) -> None:
776
+ """Wait until the guest agent accepts a vsock connection on VSOCK_PORT."""
777
+ assert vm.proc is not None
778
+ try:
779
+ async with asyncio.timeout(timeout):
780
+ while True:
781
+ if vm.proc.returncode is not None:
782
+ raise IsolationError(
783
+ f"template VM exited during boot ({vm.proc.returncode}): {vm.tail.text()}"
784
+ )
785
+ if await _probe_agent(vm.layout.vsock):
786
+ return
787
+ await asyncio.sleep(0.1)
788
+ except TimeoutError:
789
+ raise IsolationError(
790
+ f"guest agent not ready on vsock port {VSOCK_PORT} after {timeout}s"
791
+ ) from None
792
+
793
+ async def _stop(self, vm: _VM) -> None:
794
+ """SIGKILL the VMM and reap it. The signal is sent synchronously, so a
795
+ cancelled caller still leaves the process dead."""
796
+ proc = vm.proc
797
+ if proc is not None and proc.returncode is None:
798
+ with contextlib.suppress(ProcessLookupError):
799
+ os.killpg(proc.pid, signal.SIGKILL)
800
+ with contextlib.suppress(ProcessLookupError):
801
+ proc.kill()
802
+ vm.killed = True
803
+ if proc is not None and proc.returncode is None:
804
+ try:
805
+ await asyncio.wait_for(asyncio.shield(proc.wait()), self.config.kill_timeout)
806
+ except TimeoutError:
807
+ log.warning("VM %s did not exit within %ss of SIGKILL", vm.layout.vm_id, self.config.kill_timeout)
808
+ if vm.drain is not None and (proc is None or proc.returncode is not None):
809
+ vm.drain.cancel()
810
+
811
+ async def _discard(self, vm_id: str) -> None:
812
+ """Kill the VM and remove its jail and cgroup. Idempotent; the
813
+ removal is synchronous after the kill signal, so cancellation while
814
+ reaping cannot leave the jail behind."""
815
+ vm = self._vms.get(vm_id)
816
+ if vm is None:
817
+ return
818
+ try:
819
+ await self._stop(vm)
820
+ finally:
821
+ remove_jail(vm.layout)
822
+ try:
823
+ remove_cgroup(self.config.jailer, vm_id)
824
+ except OSError as e:
825
+ log.warning("could not remove cgroup of %s: %s", vm_id, e)
826
+ self._vms.pop(vm_id, None)
827
+
828
+ async def _scan(self, image: Path) -> dict[str, LsEntry]:
829
+ """Walk the scratch filesystem with debugfs, by inode number, as the
830
+ jail uid. Bounded by entries, depth and the caller's timeout."""
831
+ cfg = self.config
832
+ root = await self._debugfs_ls(image, [2])
833
+ top = root.get(2, [])
834
+ start: tuple[int, str] | None = None
835
+ for entry in top:
836
+ if entry.name == cfg.scratch_upper_dir and entry.is_dir:
837
+ start = (entry.ino, "")
838
+ break
839
+ entries: dict[str, LsEntry] = {}
840
+ visited: set[int] = {2}
841
+ frontier: list[tuple[int, str, int]] = []
842
+ if start is not None:
843
+ visited.add(start[0])
844
+ frontier.append((start[0], "", 1))
845
+ else:
846
+ for entry in top:
847
+ if entry.name == "lost+found":
848
+ continue
849
+ path = "/" + entry.name
850
+ entries[path] = entry
851
+ if entry.is_dir and entry.ino not in visited:
852
+ visited.add(entry.ino)
853
+ frontier.append((entry.ino, path, 1))
854
+ while frontier and len(entries) < cfg.max_scan_entries:
855
+ batch, frontier = frontier[:_DEBUGFS_BATCH], frontier[_DEBUGFS_BATCH:]
856
+ listing = await self._debugfs_ls(image, [ino for ino, _, _ in batch])
857
+ for ino, prefix, depth in batch:
858
+ for entry in listing.get(ino, []):
859
+ if len(entries) >= cfg.max_scan_entries:
860
+ log.warning("scratch scan of %s capped at %d entries", image, len(entries))
861
+ break
862
+ path = f"{prefix}/{entry.name}"
863
+ entries[path] = entry
864
+ if entry.is_dir and entry.ino not in visited and depth < cfg.max_depth:
865
+ visited.add(entry.ino)
866
+ frontier.append((entry.ino, path, depth + 1))
867
+ return entries
868
+
869
+ def _as_jail_user(self) -> list[str]:
870
+ """Prefix that runs a host tool on guest-written data as the jail uid,
871
+ with no supplementary groups and no way to regain privileges."""
872
+ cfg = self.config.jailer
873
+ return [
874
+ "setpriv",
875
+ "--reuid", str(cfg.uid),
876
+ "--regid", str(cfg.gid),
877
+ "--clear-groups",
878
+ "--no-new-privs",
879
+ "--",
880
+ ] # fmt: skip
881
+
882
+ async def _replay_journal(self, image: Path) -> None:
883
+ """Replay the ext4 journal of a disposable image (userspace e2fsck,
884
+ journal only). Failure is logged, not raised: the listing is advisory."""
885
+ res = await run_command(
886
+ [*self._as_jail_user(), "e2fsck", "-p", "-E", "journal_only", str(image)],
887
+ timeout=self.config.changes_timeout, check=False, max_output=1 << 16,
888
+ ) # fmt: skip
889
+ if res.returncode not in (0, 1):
890
+ log.warning("journal replay on %s exited %d; change list may be partial", image, res.returncode)
891
+
892
+ async def _debugfs_ls(self, image: Path, inodes: Iterable[int]) -> dict[int, list[LsEntry]]:
893
+ inos = [int(i) for i in inodes]
894
+ if any(not 0 < i < 2**32 for i in inos):
895
+ raise ValueError("inode number out of range")
896
+ script = "".join(f"ls -l <{i}>\n" for i in inos).encode("ascii")
897
+ argv = [*self._as_jail_user(), "debugfs", "-c", "-f", "-", str(image)]
898
+ res = await run_command(
899
+ argv, timeout=self.config.changes_timeout, stdin=script, check=False,
900
+ max_output=_DEBUGFS_MAX_OUTPUT,
901
+ ) # fmt: skip
902
+ if res.returncode != 0:
903
+ raise EmberpoolError(f"debugfs failed on {image} with exit {res.returncode}")
904
+ if res.stdout_truncated:
905
+ log.warning("debugfs output for %s truncated; change list is partial", image)
906
+ return parse_ls_sections(res.stdout.decode("utf-8", "replace"), inos)
907
+
908
+
909
+ async def _probe_agent(vsock: Path) -> bool:
910
+ """True if a host-initiated vsock connection to VSOCK_PORT is accepted."""
911
+ if not vsock.exists():
912
+ return False
913
+ try:
914
+ async with asyncio.timeout(2.0):
915
+ reader, writer = await asyncio.open_unix_connection(str(vsock), limit=_READY_LINE_MAX * 2)
916
+ try:
917
+ writer.write(f"CONNECT {VSOCK_PORT}\n".encode("ascii"))
918
+ await writer.drain()
919
+ line = await reader.readline()
920
+ finally:
921
+ writer.close()
922
+ with contextlib.suppress(Exception):
923
+ await writer.wait_closed()
924
+ except (OSError, TimeoutError, ValueError, asyncio.LimitOverrunError, asyncio.IncompleteReadError):
925
+ return False
926
+ return _READY_RE.fullmatch(line) is not None
927
+
928
+
929
+ def _check_regular(path: Path) -> os.stat_result:
930
+ st = os.lstat(path)
931
+ if not stat.S_ISREG(st.st_mode):
932
+ raise EmberpoolError(f"not a regular file: {path}")
933
+ return st
934
+
935
+
936
+ def _seal(path: Path, gid: int) -> None:
937
+ """Make a template file root-owned and read-only, readable by the jail gid."""
938
+ os.chown(path, 0, gid)
939
+ os.chmod(path, 0o440)
940
+
941
+
942
+ _VMGENID_CODE = (
943
+ "import os\n"
944
+ "d = '/sys/bus/platform/drivers/vmgenid'\n"
945
+ "bound = os.path.isdir(d) and any(\n"
946
+ " e != 'module' and os.path.islink(os.path.join(d, e)) for e in os.listdir(d))\n"
947
+ "print('vmgenid:bound' if bound else 'vmgenid:unbound')\n"
948
+ )