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/_jailer.py ADDED
@@ -0,0 +1,304 @@
1
+ """Jailer chroot layout, command line and teardown.
2
+
3
+ Every Firecracker process emberpool starts runs under the jailer
4
+ (docs/40-rules.md rule 4): chroot, uid/gid drop, seccomp, optional cgroups and
5
+ the VM's network namespace.
6
+
7
+ The jailer puts each VM in `<chroot_base>/<exec name>/<vm_id>/root`. emberpool
8
+ creates that directory itself before starting the jailer, places the VM's
9
+ files in it, and removes the whole `<vm_id>` directory on cleanup. Every path
10
+ here is derived from the configured base and a validated VM id, never from
11
+ anything the guest reports (rule 1).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import errno
17
+ import os
18
+ import re
19
+ import shutil
20
+ import stat
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+
24
+ from emberpool._names import validate_netns, validate_vm_id
25
+
26
+ __all__ = [
27
+ "JailerConfig",
28
+ "JailLayout",
29
+ "NETNS_DIR",
30
+ "CGROUP_ROOT",
31
+ "MAX_UNIX_PATH",
32
+ "IN_JAIL_API_SOCK",
33
+ "IN_JAIL_VSOCK",
34
+ "IN_JAIL_KERNEL",
35
+ "IN_JAIL_ROOTFS",
36
+ "IN_JAIL_SCRATCH",
37
+ "IN_JAIL_STATE",
38
+ "IN_JAIL_MEM",
39
+ "netns_path",
40
+ "jailer_argv",
41
+ "create_jail",
42
+ "remove_jail",
43
+ "remove_cgroup",
44
+ "VMM_MEMORY_OVERHEAD_MIB",
45
+ "VMM_PIDS_MAX",
46
+ "CPU_PERIOD_US",
47
+ "vmm_cgroups",
48
+ "cgroup_path",
49
+ "check_cgroup",
50
+ ]
51
+
52
+ NETNS_DIR = Path("/var/run/netns")
53
+ CGROUP_ROOT = Path("/sys/fs/cgroup")
54
+
55
+ # sockaddr_un.sun_path is 108 bytes including the trailing NUL.
56
+ MAX_UNIX_PATH = 107
57
+
58
+ # Paths as Firecracker sees them inside the chroot. The snapshot records the
59
+ # drive and vsock paths, so they must be identical for the template and every
60
+ # clone.
61
+ IN_JAIL_API_SOCK = "/api.sock"
62
+ IN_JAIL_VSOCK = "/v.sock"
63
+ IN_JAIL_KERNEL = "/kernel"
64
+ IN_JAIL_ROOTFS = "/rootfs.ext4"
65
+ IN_JAIL_SCRATCH = "/scratch.ext4"
66
+ IN_JAIL_STATE = "/snapshot.state"
67
+ IN_JAIL_MEM = "/snapshot.mem"
68
+
69
+ # Limits for the VMM's cgroup, derived from the guest's shape by vmm_cgroups().
70
+ # The guest cannot use more memory than it was given, so memory.max is the
71
+ # guest memory plus a fixed allowance for Firecracker itself (its own heap,
72
+ # device buffers, KVM page tables). cpu.max gives the VMM one CPU per vCPU
73
+ # per period; its I/O and API threads share that budget.
74
+ VMM_MEMORY_OVERHEAD_MIB = 64
75
+ VMM_PIDS_MAX = 64
76
+ CPU_PERIOD_US = 100_000
77
+ _MIB = 1024 * 1024
78
+
79
+ _EXEC_NAME_RE = re.compile(r"[A-Za-z0-9._-]*firecracker[A-Za-z0-9._-]*")
80
+ _CGROUP_RE = re.compile(r"[a-z]+\.[a-z_.]+=[A-Za-z0-9 ._-]{1,64}")
81
+ _PARENT_CGROUP_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
82
+ _RLIMIT_RE = re.compile(r"(fsize|no-file)=[0-9]{1,20}")
83
+
84
+
85
+ def _check_id(kind: str, value: object) -> int:
86
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 < value < 2**31:
87
+ raise ValueError(f"{kind} must be a positive int (never root): {value!r}")
88
+ return value
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class JailerConfig:
93
+ """Where the binaries live and what the jailer confines the VMM to.
94
+
95
+ uid/gid: identity Firecracker runs as. Never 0.
96
+ cgroups: `<file>=<value>` entries for the VM's cgroup (cgroup v2),
97
+ for example "pids.max=64". Empty means no cgroup.
98
+ parent_cgroup: parent of the per-VM cgroups.
99
+ resource_limits: `fsize=<n>` or `no-file=<n>` entries.
100
+ """
101
+
102
+ jailer_bin: Path
103
+ firecracker_bin: Path
104
+ chroot_base: Path = Path("/srv/jailer")
105
+ uid: int = 10123
106
+ gid: int = 10123
107
+ cgroups: tuple[str, ...] = ()
108
+ parent_cgroup: str = "emberpool"
109
+ resource_limits: tuple[str, ...] = ()
110
+
111
+ def __post_init__(self) -> None:
112
+ for name in ("jailer_bin", "firecracker_bin", "chroot_base"):
113
+ value = getattr(self, name)
114
+ if not isinstance(value, Path):
115
+ object.__setattr__(self, name, Path(value))
116
+ if not getattr(self, name).is_absolute():
117
+ raise ValueError(f"{name} must be an absolute path: {value!r}")
118
+ _check_id("uid", self.uid)
119
+ _check_id("gid", self.gid)
120
+ if _EXEC_NAME_RE.fullmatch(self.firecracker_bin.name) is None:
121
+ raise ValueError(f"firecracker binary name must contain 'firecracker': {self.firecracker_bin.name!r}")
122
+ if not isinstance(self.cgroups, tuple) or any(
123
+ not isinstance(c, str) or _CGROUP_RE.fullmatch(c) is None for c in self.cgroups
124
+ ):
125
+ raise ValueError(f"invalid cgroups: {self.cgroups!r}")
126
+ if not isinstance(self.parent_cgroup, str) or _PARENT_CGROUP_RE.fullmatch(self.parent_cgroup) is None:
127
+ raise ValueError(f"invalid parent_cgroup: {self.parent_cgroup!r}")
128
+ if not isinstance(self.resource_limits, tuple) or any(
129
+ not isinstance(r, str) or _RLIMIT_RE.fullmatch(r) is None for r in self.resource_limits
130
+ ):
131
+ raise ValueError(f"invalid resource_limits: {self.resource_limits!r}")
132
+
133
+ @property
134
+ def exec_name(self) -> str:
135
+ return self.firecracker_bin.name
136
+
137
+ def layout(self, vm_id: str) -> JailLayout:
138
+ return JailLayout(self.chroot_base, self.exec_name, validate_vm_id(vm_id))
139
+
140
+
141
+ @dataclass(frozen=True, slots=True)
142
+ class JailLayout:
143
+ """Host paths of one VM's jail."""
144
+
145
+ base: Path
146
+ exec_name: str
147
+ vm_id: str
148
+
149
+ def __post_init__(self) -> None:
150
+ validate_vm_id(self.vm_id)
151
+ if _EXEC_NAME_RE.fullmatch(self.exec_name) is None:
152
+ raise ValueError(f"invalid exec name: {self.exec_name!r}")
153
+ # Both sockets must fit in sun_path. Firecracker also binds
154
+ # "<vsock>_<port>" for guest-initiated vsock connections.
155
+ for sock in (self.api_sock, Path(f"{self.vsock}_{2**32 - 1}")):
156
+ if len(os.fsencode(sock)) > MAX_UNIX_PATH:
157
+ raise ValueError(f"chroot base too long for Unix socket paths: {self.base}")
158
+
159
+ @property
160
+ def id_dir(self) -> Path:
161
+ """`<base>/<exec>/<vm_id>`: removed as a whole on cleanup."""
162
+ return self.base / self.exec_name / self.vm_id
163
+
164
+ @property
165
+ def root(self) -> Path:
166
+ return self.id_dir / "root"
167
+
168
+ def host(self, in_jail: str) -> Path:
169
+ """Host path of a path as Firecracker sees it inside the chroot."""
170
+ if not in_jail.startswith("/") or ".." in in_jail.split("/"):
171
+ raise ValueError(f"bad in-jail path: {in_jail!r}")
172
+ return self.root / in_jail.lstrip("/")
173
+
174
+ @property
175
+ def api_sock(self) -> Path:
176
+ return self.host(IN_JAIL_API_SOCK)
177
+
178
+ @property
179
+ def vsock(self) -> Path:
180
+ return self.host(IN_JAIL_VSOCK)
181
+
182
+ @property
183
+ def scratch(self) -> Path:
184
+ return self.host(IN_JAIL_SCRATCH)
185
+
186
+
187
+ def vmm_cgroups(vcpus: int, memory_mib: int) -> tuple[str, ...]:
188
+ """cgroup v2 entries for a VMM whose guest has `vcpus` and `memory_mib`.
189
+
190
+ memory.max: guest memory plus VMM_MEMORY_OVERHEAD_MIB, in bytes.
191
+ cpu.max: `vcpus` CPUs' worth of time per CPU_PERIOD_US.
192
+ pids.max: VMM_PIDS_MAX tasks (Firecracker uses one thread per vCPU and
193
+ a few more).
194
+ """
195
+ for name, value, hi in (("vcpus", vcpus, 32), ("memory_mib", memory_mib, 1 << 20)):
196
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 < value <= hi:
197
+ raise ValueError(f"{name} must be an int in 1..{hi}: {value!r}")
198
+ return (
199
+ f"memory.max={(memory_mib + VMM_MEMORY_OVERHEAD_MIB) * _MIB}",
200
+ f"cpu.max={vcpus * CPU_PERIOD_US} {CPU_PERIOD_US}",
201
+ f"pids.max={VMM_PIDS_MAX}",
202
+ )
203
+
204
+
205
+ def cgroup_path(cfg: JailerConfig, vm_id: str) -> Path:
206
+ """Host path of the cgroup the jailer creates for `vm_id`."""
207
+ return CGROUP_ROOT / cfg.parent_cgroup / validate_vm_id(vm_id)
208
+
209
+
210
+ def check_cgroup(cfg: JailerConfig, vm_id: str, pid: int) -> list[str]:
211
+ """Problems with the VM's cgroup, read from the host: every configured
212
+ limit must hold its value and `pid` must be a member. Empty means all is
213
+ as configured (or no cgroup is configured)."""
214
+ if not cfg.cgroups:
215
+ return []
216
+ path = cgroup_path(cfg, vm_id)
217
+ problems: list[str] = []
218
+ for entry in cfg.cgroups:
219
+ name, _, want = entry.partition("=")
220
+ try:
221
+ got = (path / name).read_text(encoding="ascii", errors="replace")[:256].strip()
222
+ except OSError as e:
223
+ problems.append(f"{name}: cannot read ({e.strerror})")
224
+ continue
225
+ if got != want.strip():
226
+ problems.append(f"{name} is {got!r}, expected {want!r}")
227
+ try:
228
+ procs = (path / "cgroup.procs").read_text(encoding="ascii", errors="replace").split()
229
+ except OSError as e:
230
+ problems.append(f"cgroup.procs: cannot read ({e.strerror})")
231
+ else:
232
+ if str(pid) not in procs:
233
+ problems.append(f"process {pid} is not in the cgroup")
234
+ return problems
235
+
236
+
237
+ def netns_path(netns: str) -> Path:
238
+ """Path the jailer joins for `netns`. The namespace must already exist."""
239
+ return NETNS_DIR / validate_netns(netns)
240
+
241
+
242
+ def jailer_argv(cfg: JailerConfig, vm_id: str, netns: str, *, log_level: str = "Warning") -> list[str]:
243
+ """Command line for one jailed Firecracker process."""
244
+ validate_vm_id(vm_id)
245
+ if log_level not in ("Error", "Warning", "Info", "Debug"):
246
+ raise ValueError(f"invalid log level: {log_level!r}")
247
+ argv = [
248
+ str(cfg.jailer_bin),
249
+ "--id", vm_id,
250
+ "--exec-file", str(cfg.firecracker_bin),
251
+ "--uid", str(cfg.uid),
252
+ "--gid", str(cfg.gid),
253
+ "--chroot-base-dir", str(cfg.chroot_base),
254
+ "--netns", str(netns_path(netns)),
255
+ ] # fmt: skip
256
+ if cfg.cgroups:
257
+ argv += ["--cgroup-version", "2", "--parent-cgroup", cfg.parent_cgroup]
258
+ for entry in cfg.cgroups:
259
+ argv += ["--cgroup", entry]
260
+ for limit in cfg.resource_limits:
261
+ argv += ["--resource-limit", limit]
262
+ argv += ["--", "--api-sock", IN_JAIL_API_SOCK, "--level", log_level]
263
+ return argv
264
+
265
+
266
+ def create_jail(layout: JailLayout) -> None:
267
+ """Create `<id_dir>/root`. Fails if `<id_dir>` already exists: a jail is
268
+ never reused, and a directory emberpool did not just create is never
269
+ adopted (and so never removed) by this VM."""
270
+ exec_dir = layout.id_dir.parent
271
+ exec_dir.mkdir(parents=True, exist_ok=True, mode=0o755)
272
+ if exec_dir.is_symlink() or not exec_dir.is_dir():
273
+ raise FileExistsError(f"jail parent is not a plain directory: {exec_dir}")
274
+ layout.id_dir.mkdir(mode=0o755) # raises FileExistsError if present
275
+ layout.root.mkdir(mode=0o755)
276
+
277
+
278
+ def remove_jail(layout: JailLayout) -> None:
279
+ """Remove `<id_dir>` and everything in it. Idempotent. Does not follow
280
+ symlinks (shutil.rmtree uses fd-based traversal on Linux)."""
281
+ path = layout.id_dir
282
+ try:
283
+ st = os.lstat(path)
284
+ except FileNotFoundError:
285
+ return
286
+ if not stat.S_ISDIR(st.st_mode):
287
+ raise RuntimeError(f"jail path is not a directory: {path}")
288
+ shutil.rmtree(path)
289
+
290
+
291
+ def remove_cgroup(cfg: JailerConfig, vm_id: str) -> None:
292
+ """Remove the VM's cgroup directory if the jailer created one. The VM
293
+ process must be gone. Idempotent."""
294
+ if not cfg.cgroups:
295
+ return
296
+ path = cgroup_path(cfg, vm_id)
297
+ try:
298
+ os.rmdir(path)
299
+ except FileNotFoundError:
300
+ return
301
+ except OSError as e:
302
+ if e.errno == errno.ENOENT:
303
+ return
304
+ raise