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/__init__.py +10 -0
- emberpool/_assets/__init__.py +7 -0
- emberpool/_assets/ep-init +52 -0
- emberpool/_assets/inittab +4 -0
- emberpool/_firecracker.py +948 -0
- emberpool/_jailer.py +304 -0
- emberpool/_ledger.py +815 -0
- emberpool/_names.py +272 -0
- emberpool/_protocol.py +255 -0
- emberpool/_resolver.py +436 -0
- emberpool/_settings.py +317 -0
- emberpool/_setup.py +897 -0
- emberpool/_types.py +433 -0
- emberpool/_wiring.py +365 -0
- emberpool/cli.py +146 -0
- emberpool/engine.py +123 -0
- emberpool/exec_client.py +145 -0
- emberpool/guest/_protocol.py +255 -0
- emberpool/guest/agent.py +412 -0
- emberpool/netpolicy.py +864 -0
- emberpool/pool.py +668 -0
- emberpool/py.typed +0 -0
- emberpool/trace.py +780 -0
- emberpool-0.1.0a1.dist-info/METADATA +234 -0
- emberpool-0.1.0a1.dist-info/RECORD +28 -0
- emberpool-0.1.0a1.dist-info/WHEEL +4 -0
- emberpool-0.1.0a1.dist-info/entry_points.txt +3 -0
- emberpool-0.1.0a1.dist-info/licenses/LICENSE +21 -0
emberpool/_settings.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Settings: where the backend files are, and how sandboxes are named.
|
|
2
|
+
|
|
3
|
+
Every field left as None is filled when the pool is created: from an
|
|
4
|
+
environment variable, else from the config file `emberpool setup` writes,
|
|
5
|
+
else from the default below. Required fields still missing after that, and any
|
|
6
|
+
invalid value, raise ValueError before anything is created (fail closed).
|
|
7
|
+
|
|
8
|
+
The config file is $EMBERPOOL_CONFIG, or /var/lib/emberpool/config.json. It
|
|
9
|
+
must be a regular file owned by root (or the current user) that nobody else
|
|
10
|
+
can write; it may set firecracker, jailer, kernel, rootfs and jail_base.
|
|
11
|
+
|
|
12
|
+
On a host that is not Linux, or has no /dev/kvm, resolve() raises
|
|
13
|
+
IsolationError naming what is missing.
|
|
14
|
+
|
|
15
|
+
field variable default
|
|
16
|
+
firecracker EMBERPOOL_FIRECRACKER required
|
|
17
|
+
jailer EMBERPOOL_JAILER required
|
|
18
|
+
kernel EMBERPOOL_KERNEL required
|
|
19
|
+
rootfs EMBERPOOL_ROOTFS required
|
|
20
|
+
jail_base EMBERPOOL_JAIL_BASE /srv/jailer
|
|
21
|
+
jail_uid EMBERPOOL_JAIL_UID 10123
|
|
22
|
+
jail_gid EMBERPOOL_JAIL_GID 10123
|
|
23
|
+
prefix EMBERPOOL_PREFIX ep
|
|
24
|
+
vcpus EMBERPOOL_VCPUS 1
|
|
25
|
+
memory_mib EMBERPOOL_MEMORY_MIB 512
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import re
|
|
33
|
+
import stat
|
|
34
|
+
import sys
|
|
35
|
+
from collections.abc import Mapping
|
|
36
|
+
from dataclasses import dataclass, fields, replace
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
from emberpool._types import IsolationError
|
|
40
|
+
|
|
41
|
+
__all__ = ["Settings"]
|
|
42
|
+
|
|
43
|
+
DEFAULT_DIR = Path("/var/lib/emberpool")
|
|
44
|
+
CONFIG_ENV = "EMBERPOOL_CONFIG"
|
|
45
|
+
CONFIG_NAME = "config.json"
|
|
46
|
+
CONFIG_VERSION = 1
|
|
47
|
+
_CONFIG_KEYS = ("firecracker", "jailer", "kernel", "rootfs", "jail_base")
|
|
48
|
+
_CONFIG_MAX = 64 * 1024
|
|
49
|
+
_KVM = Path("/dev/kvm")
|
|
50
|
+
SETUP_HINT = "run `sudo emberpool setup`"
|
|
51
|
+
|
|
52
|
+
_ENV = {
|
|
53
|
+
"firecracker": "EMBERPOOL_FIRECRACKER",
|
|
54
|
+
"jailer": "EMBERPOOL_JAILER",
|
|
55
|
+
"kernel": "EMBERPOOL_KERNEL",
|
|
56
|
+
"rootfs": "EMBERPOOL_ROOTFS",
|
|
57
|
+
"jail_base": "EMBERPOOL_JAIL_BASE",
|
|
58
|
+
"jail_uid": "EMBERPOOL_JAIL_UID",
|
|
59
|
+
"jail_gid": "EMBERPOOL_JAIL_GID",
|
|
60
|
+
"prefix": "EMBERPOOL_PREFIX",
|
|
61
|
+
"vcpus": "EMBERPOOL_VCPUS",
|
|
62
|
+
"memory_mib": "EMBERPOOL_MEMORY_MIB",
|
|
63
|
+
}
|
|
64
|
+
_DEFAULTS: dict[str, object] = {
|
|
65
|
+
"jail_base": Path("/srv/jailer"),
|
|
66
|
+
"jail_uid": 10123,
|
|
67
|
+
"jail_gid": 10123,
|
|
68
|
+
"prefix": "ep",
|
|
69
|
+
"vcpus": 1,
|
|
70
|
+
"memory_mib": 512,
|
|
71
|
+
}
|
|
72
|
+
_FILES = ("firecracker", "jailer", "kernel", "rootfs")
|
|
73
|
+
_EXECUTABLES = ("firecracker", "jailer")
|
|
74
|
+
# Names become namespace, interface, table and cgroup names: keep them short
|
|
75
|
+
# and plain. Interface names are "<prefix>-h<N>", at most 15 characters.
|
|
76
|
+
_PREFIX_RE = re.compile(r"ep(-[a-z0-9]{1,5})?")
|
|
77
|
+
_MAX_ID = 2**31 - 1
|
|
78
|
+
# Guest shape. Firecracker allows at most 32 vCPUs; below 128 MiB the guest
|
|
79
|
+
# kernel and agent do not fit, and 64 GiB is far beyond one run's needs.
|
|
80
|
+
_SIZES = {"vcpus": (1, 32), "memory_mib": (128, 65536)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class Settings:
|
|
85
|
+
"""Backend paths and naming for a SandboxPool.
|
|
86
|
+
|
|
87
|
+
firecracker, jailer: the Firecracker and jailer binaries.
|
|
88
|
+
kernel: the guest kernel image.
|
|
89
|
+
rootfs: the guest root filesystem with the emberpool agent.
|
|
90
|
+
jail_base: folder for jails and the template snapshot.
|
|
91
|
+
jail_uid, jail_gid: identity the VMM runs as (never 0).
|
|
92
|
+
prefix: start of every namespace, interface, nftables table
|
|
93
|
+
and cgroup name, so pools on one host stay apart.
|
|
94
|
+
vcpus: guest vCPUs (1-32). The VMM's cgroup gets as many
|
|
95
|
+
CPUs' worth of time.
|
|
96
|
+
memory_mib: guest memory in MiB (128-65536). The VMM's cgroup
|
|
97
|
+
memory limit is this plus a fixed VMM overhead.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
firecracker: Path | None = None
|
|
101
|
+
jailer: Path | None = None
|
|
102
|
+
kernel: Path | None = None
|
|
103
|
+
rootfs: Path | None = None
|
|
104
|
+
jail_base: Path | None = None
|
|
105
|
+
jail_uid: int | None = None
|
|
106
|
+
jail_gid: int | None = None
|
|
107
|
+
prefix: str | None = None
|
|
108
|
+
vcpus: int | None = None
|
|
109
|
+
memory_mib: int | None = None
|
|
110
|
+
|
|
111
|
+
def resolve(self, environ: Mapping[str, str] | None = None) -> Settings:
|
|
112
|
+
"""A copy with every unset field filled from the environment (then the
|
|
113
|
+
defaults), validated. Raises ValueError naming what is missing or wrong."""
|
|
114
|
+
problem = platform_problem()
|
|
115
|
+
if problem is not None:
|
|
116
|
+
raise IsolationError(problem)
|
|
117
|
+
env = os.environ if environ is None else environ
|
|
118
|
+
values, missing, config = self._merged(env)
|
|
119
|
+
if missing:
|
|
120
|
+
text = "emberpool settings missing: " + ", ".join(f"{n} (set {_ENV[n]})" for n in missing)
|
|
121
|
+
if config is None:
|
|
122
|
+
text = f"emberpool is not set up: {SETUP_HINT}. {text}"
|
|
123
|
+
raise ValueError(text)
|
|
124
|
+
out = replace(self, **values) # type: ignore[arg-type]
|
|
125
|
+
return out._validated()
|
|
126
|
+
|
|
127
|
+
def _merged(self, env: Mapping[str, str]) -> tuple[dict[str, object], list[str], Path | None]:
|
|
128
|
+
"""Unvalidated values (field, then environment, then config file, then
|
|
129
|
+
default), the required fields still missing, and the config file read
|
|
130
|
+
(None if there was none). Raises ValueError for a bad config file."""
|
|
131
|
+
config_path, file_values = read_config(env)
|
|
132
|
+
values: dict[str, object] = {}
|
|
133
|
+
missing: list[str] = []
|
|
134
|
+
for f in fields(self):
|
|
135
|
+
value = getattr(self, f.name)
|
|
136
|
+
if value is None:
|
|
137
|
+
text = env.get(_ENV[f.name])
|
|
138
|
+
if text:
|
|
139
|
+
value = text
|
|
140
|
+
elif f.name in file_values:
|
|
141
|
+
value = file_values[f.name]
|
|
142
|
+
elif f.name in _DEFAULTS:
|
|
143
|
+
value = _DEFAULTS[f.name]
|
|
144
|
+
else:
|
|
145
|
+
missing.append(f.name)
|
|
146
|
+
continue
|
|
147
|
+
values[f.name] = value
|
|
148
|
+
return values, missing, config_path
|
|
149
|
+
|
|
150
|
+
def _validated(self) -> Settings:
|
|
151
|
+
paths: dict[str, Path] = {}
|
|
152
|
+
for name in (*_FILES, "jail_base"):
|
|
153
|
+
value = getattr(self, name)
|
|
154
|
+
if not isinstance(value, (str, Path)):
|
|
155
|
+
raise ValueError(f"settings.{name} must be a path: {value!r}")
|
|
156
|
+
path = Path(value)
|
|
157
|
+
if not path.is_absolute():
|
|
158
|
+
raise ValueError(f"settings.{name} must be an absolute path: {str(path)!r}")
|
|
159
|
+
paths[name] = path
|
|
160
|
+
for name in _FILES:
|
|
161
|
+
try:
|
|
162
|
+
st = os.stat(paths[name])
|
|
163
|
+
except OSError as e:
|
|
164
|
+
raise ValueError(f"settings.{name} does not exist: {str(paths[name])!r}") from e
|
|
165
|
+
if not stat.S_ISREG(st.st_mode):
|
|
166
|
+
raise ValueError(f"settings.{name} is not a regular file: {str(paths[name])!r}")
|
|
167
|
+
if name in _EXECUTABLES and not os.access(paths[name], os.X_OK):
|
|
168
|
+
raise ValueError(f"settings.{name} is not executable: {str(paths[name])!r}")
|
|
169
|
+
if not os.access(paths[name], os.R_OK):
|
|
170
|
+
raise ValueError(f"settings.{name} is not readable: {str(paths[name])!r}")
|
|
171
|
+
base = paths["jail_base"]
|
|
172
|
+
if base.exists() and not base.is_dir():
|
|
173
|
+
raise ValueError(f"settings.jail_base is not a folder: {str(base)!r}")
|
|
174
|
+
ids: dict[str, int] = {}
|
|
175
|
+
for name in ("jail_uid", "jail_gid"):
|
|
176
|
+
value = getattr(self, name)
|
|
177
|
+
if isinstance(value, str):
|
|
178
|
+
if not value.isdigit():
|
|
179
|
+
raise ValueError(f"settings.{name} must be a number: {value!r}")
|
|
180
|
+
value = int(value)
|
|
181
|
+
if isinstance(value, bool) or not isinstance(value, int) or not 0 < value <= _MAX_ID:
|
|
182
|
+
raise ValueError(f"settings.{name} must be a positive id, never root: {value!r}")
|
|
183
|
+
ids[name] = value
|
|
184
|
+
for name, (lo, hi) in _SIZES.items():
|
|
185
|
+
value = getattr(self, name)
|
|
186
|
+
if isinstance(value, str):
|
|
187
|
+
if not (value.isascii() and value.isdigit() and len(value) <= 6):
|
|
188
|
+
raise ValueError(f"settings.{name} must be a number: {value!r}")
|
|
189
|
+
value = int(value)
|
|
190
|
+
if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
|
|
191
|
+
raise ValueError(f"settings.{name} must be an int in {lo}..{hi}: {value!r}")
|
|
192
|
+
ids[name] = value
|
|
193
|
+
prefix = self.prefix
|
|
194
|
+
if not isinstance(prefix, str) or _PREFIX_RE.fullmatch(prefix) is None:
|
|
195
|
+
raise ValueError(f'settings.prefix must be "ep" or "ep-" plus 1-5 of a-z0-9: {prefix!r}')
|
|
196
|
+
return replace(self, **paths, **ids, prefix=prefix) # type: ignore[arg-type]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def platform_problem() -> str | None:
|
|
200
|
+
"""What this host lacks to run sandboxes, or None."""
|
|
201
|
+
if not sys.platform.startswith("linux"):
|
|
202
|
+
return (
|
|
203
|
+
f"emberpool needs Linux with KVM; this host runs {sys.platform}. "
|
|
204
|
+
"On a Mac, use a Linux VM with nested virtualization."
|
|
205
|
+
)
|
|
206
|
+
try:
|
|
207
|
+
st = os.stat(_KVM)
|
|
208
|
+
except FileNotFoundError:
|
|
209
|
+
return (
|
|
210
|
+
f"emberpool needs KVM: {_KVM} does not exist on this host. Use bare metal, or a VM "
|
|
211
|
+
"or instance type with (nested) virtualization enabled."
|
|
212
|
+
)
|
|
213
|
+
except OSError as e:
|
|
214
|
+
return f"emberpool needs KVM: cannot inspect {_KVM}: {e.strerror}"
|
|
215
|
+
if not stat.S_ISCHR(st.st_mode):
|
|
216
|
+
return f"emberpool needs KVM: {_KVM} is not a character device"
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def config_path(env: Mapping[str, str] | None = None) -> tuple[Path, bool]:
|
|
221
|
+
"""The config file to read, and whether it was named explicitly."""
|
|
222
|
+
env = os.environ if env is None else env
|
|
223
|
+
text = env.get(CONFIG_ENV)
|
|
224
|
+
if text:
|
|
225
|
+
path = Path(text)
|
|
226
|
+
if not path.is_absolute():
|
|
227
|
+
raise ValueError(f"{CONFIG_ENV} must be an absolute path: {text!r}")
|
|
228
|
+
return path, True
|
|
229
|
+
return DEFAULT_DIR / CONFIG_NAME, False
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def read_config(env: Mapping[str, str]) -> tuple[Path | None, dict[str, str]]:
|
|
233
|
+
"""The config file's path and values, or (None, {}) when the default file
|
|
234
|
+
does not exist. A file named by EMBERPOOL_CONFIG must exist. The file must
|
|
235
|
+
be a private regular file (owned by root or this user, writable by nobody
|
|
236
|
+
else, not a symlink) holding strict JSON with known keys and absolute
|
|
237
|
+
paths; anything else raises ValueError (fail closed)."""
|
|
238
|
+
path, explicit = config_path(env)
|
|
239
|
+
try:
|
|
240
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK)
|
|
241
|
+
except FileNotFoundError:
|
|
242
|
+
if explicit:
|
|
243
|
+
raise ValueError(f"emberpool config file does not exist: {str(path)!r}") from None
|
|
244
|
+
return None, {}
|
|
245
|
+
except OSError as e:
|
|
246
|
+
raise ValueError(f"cannot open emberpool config file {str(path)!r}: {e.strerror}") from None
|
|
247
|
+
try:
|
|
248
|
+
st = os.fstat(fd)
|
|
249
|
+
if not stat.S_ISREG(st.st_mode):
|
|
250
|
+
raise ValueError(f"emberpool config file is not a regular file: {str(path)!r}")
|
|
251
|
+
if st.st_uid not in (0, os.geteuid()) or st.st_mode & 0o022:
|
|
252
|
+
raise ValueError(
|
|
253
|
+
f"emberpool config file must be owned by root and writable only by its owner: {str(path)!r}"
|
|
254
|
+
)
|
|
255
|
+
if st.st_size > _CONFIG_MAX:
|
|
256
|
+
raise ValueError(f"emberpool config file is too large: {str(path)!r}")
|
|
257
|
+
data = os.read(fd, _CONFIG_MAX + 1)
|
|
258
|
+
finally:
|
|
259
|
+
os.close(fd)
|
|
260
|
+
return path, parse_config(data, path)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _no_duplicates(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
264
|
+
out: dict[str, object] = {}
|
|
265
|
+
for key, value in pairs:
|
|
266
|
+
if key in out:
|
|
267
|
+
raise ValueError(f"duplicate key {key!r}")
|
|
268
|
+
out[key] = value
|
|
269
|
+
return out
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _reject_constant(name: str) -> object:
|
|
273
|
+
raise ValueError(f"invalid number {name}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def parse_config(data: bytes, path: Path) -> dict[str, str]:
|
|
277
|
+
"""Strict parse of a config file's bytes. Raises ValueError."""
|
|
278
|
+
where = f"emberpool config file {str(path)!r}"
|
|
279
|
+
if len(data) > _CONFIG_MAX:
|
|
280
|
+
raise ValueError(f"{where} is too large")
|
|
281
|
+
try:
|
|
282
|
+
doc = json.loads(
|
|
283
|
+
data.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_reject_constant
|
|
284
|
+
)
|
|
285
|
+
except (UnicodeDecodeError, ValueError) as e:
|
|
286
|
+
raise ValueError(f"{where} is not valid JSON: {e}") from None
|
|
287
|
+
if not isinstance(doc, dict):
|
|
288
|
+
raise ValueError(f"{where} must hold a JSON object")
|
|
289
|
+
version = doc.get("version")
|
|
290
|
+
if isinstance(version, bool) or version != CONFIG_VERSION:
|
|
291
|
+
raise ValueError(f"{where} has unsupported version {version!r} (expected {CONFIG_VERSION})")
|
|
292
|
+
out: dict[str, str] = {}
|
|
293
|
+
for key, value in doc.items():
|
|
294
|
+
if key == "version":
|
|
295
|
+
continue
|
|
296
|
+
if key not in _CONFIG_KEYS:
|
|
297
|
+
raise ValueError(f"{where} has unknown key {key!r}")
|
|
298
|
+
if not isinstance(value, str) or not value or "\0" in value or not Path(value).is_absolute():
|
|
299
|
+
raise ValueError(f"{where}: {key} must be an absolute path")
|
|
300
|
+
out[key] = value
|
|
301
|
+
return out
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def render_config(values: Mapping[str, Path]) -> bytes:
|
|
305
|
+
"""The config file for `values` (keys from firecracker, jailer, kernel,
|
|
306
|
+
rootfs, jail_base)."""
|
|
307
|
+
doc: dict[str, object] = {"version": CONFIG_VERSION}
|
|
308
|
+
for key in _CONFIG_KEYS:
|
|
309
|
+
if key in values:
|
|
310
|
+
path = Path(values[key])
|
|
311
|
+
if not path.is_absolute():
|
|
312
|
+
raise ValueError(f"{key} must be an absolute path: {str(path)!r}")
|
|
313
|
+
doc[key] = str(path)
|
|
314
|
+
unknown = set(values) - set(_CONFIG_KEYS)
|
|
315
|
+
if unknown:
|
|
316
|
+
raise ValueError(f"unknown config keys: {sorted(unknown)}")
|
|
317
|
+
return (json.dumps(doc, indent=2) + "\n").encode()
|