1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
|
#!/usr/bin/python3
# Copyright 2026 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: LGPL-2.0-or-later
"""
This is an autopkgtest virtualization server that implements system containers
from scratch. It runs an init system such as systemd as pid1 as a regular user
account. To do so it requires a subuid allocation granted via /etc/subuid and
/etc/subgid (via newuidmap and newgidmap setuid binaries) as well as a systemd
user manager process reachable via dbus to delegate a control group.
Doing so requires several processes to work in cooperation. The following graph
is structured around how processes fork and describes their purpose.
frontend: The first process is the autopkgtest process. It acts as the
| frontend to the user and drives the interaction.
|-- virtserver: The second process is the main virtualization backend
| | process. It is forked from the autopkgtest process and communicates
| | with it via pipes on stdin and stdout. This process remains in the
| | initial namespaces, because it must be able to access host paths
| | e.g. for copydown and copyup commands.
| +-- runtime: The third process is a varlink server using the pconr API.
| | It moves to a new set of namespaces and mounts the root
| | filesystem.
| +-- fusedriver: Optionally, the varlink server spawns a fuse driver
| | process for the root filesystem.
| +-- loader: On issuing an open command, runtime process spawns an
| | intermediate process for sealing the mount namespace using
| | a new user namespace. It also creates a new pid namespace
| | but does not enter the pid namespace itself. It immediately
| | creates an init process.
| +-- init: The container init process is forked from the
| | loader process and becomes pid1 in the target namespaces.
+-- execomm: The script can be reinvoked by the frontend with
--execute-command to launch a command into the container. It
communicates with the loader process via varlink and makes it fork
the actual command process into the container. The stdio file
descriptors are of this process are forwarded and connected to the
new process.
|
+- command: When the --execute-command is invoked, the
loader forks this process into the container and
then executes the requested command there.
The input image is supposed to be an erofs disk image. It can be created as
follows:
mmdebstrap unstable container.tar --variant=apt --format=tar
--include dbus,dpkg-dev,libpam-systemd,mount,passwd,python3,systemd-sysv,udev
--customize-hook=/usr/share/autopkgtest/setup-commands/setup-testbed
mkfs.erofs --tar container.erofs container.tar
Note that since the container image lacks apt caches, --apt-upgrade should be
passed to autopkgtest when using this backend.
"""
import argparse
import asyncio
import errno
import os
from pathlib import Path, PurePath
import signal
import stat
import sys
import typing
import uuid
import urllib.parse
if __file__.split("/")[-2:-1] == ["examples"]:
sys.path.insert(0, "/".join(__file__.split("/")[:-2]))
import asyncvarlink
import linuxnamespaces
import linuxnamespaces.systemd
import pconr
async def connect_pipes() -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
"""Connect and return a StreamReader for stdin and a StreamWriter for
stdout.
"""
os.set_blocking(sys.stdin.fileno(), False)
loop = asyncio.get_running_loop()
reader = asyncio.StreamReader()
read_protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pipe(lambda: read_protocol, sys.stdin.buffer)
write_transport, write_protocol = await loop.connect_write_pipe(
asyncio.streams.FlowControlMixin, sys.stdout.buffer
)
writer = asyncio.StreamWriter(
write_transport, write_protocol, reader, loop
)
return reader, writer
class AutopkgtestCommandError(Exception):
def __init__(self, message: str):
self.message = message
def expect_args(command: str, args: list[str], nargs: int) -> None:
"""Validate argument count of a autpkgtest virtualisation protocol
command.
"""
if len(args) < nargs:
raise AutopkgtestCommandError(
f"too few arguments to command {command}"
)
if len(args) > nargs:
raise AutopkgtestCommandError(
f"too many arguments to command {command}"
)
class AutopkgtestServer:
def __init__(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
self._reader = reader
self._writer = writer
self._quitting = False
def send(self, *verbs: str) -> None:
self._writer.write(" ".join(verbs).encode("utf8") + b"\n")
async def capabilities(self) -> list[str]:
"""Return available capabilities."""
raise NotImplementedError
async def close(self) -> None:
"""Close the testbed."""
raise NotImplementedError
async def copydown_dir(self, source: Path, destination: PurePath) -> None:
"""Recursively copy a directory from the host to the testbed.
Fails by default.
"""
raise AutopkgtestCommandError("copyup is not implemented")
async def copydown_file(self, source: Path, destination: PurePath) -> None:
"""Copy a file from the host to the testbed.
Fails by default.
"""
raise AutopkgtestCommandError("copyup is not implemented")
async def copyup_dir(self, source: PurePath, destination: Path) -> None:
"""Recursively copy a directory from the testbed to the host.
Fails by default.
"""
raise AutopkgtestCommandError("copyup is not implemented")
async def copyup_file(self, source: PurePath, destination: Path) -> None:
"""Copy a file from the testbed to the host.
Fails by default.
"""
raise AutopkgtestCommandError("copyup is not implemented")
async def open(self) -> PurePath:
"""Open the testbed. Return the scratchspace path inside the testbed.
"""
raise NotImplementedError
async def print_execute_command(self) -> list[str]:
"""Return the unquoted execute command used for launching commands into
the testbed.
"""
raise NotImplementedError
async def quit(self) -> None:
"""Handle the quit command.
By default, this closes the testbed.
"""
await self.close()
async def revert(self) -> PurePath:
"""Revert the testbed to a fresh state and return the new scratchspace.
The default implementation runs close() and open() unless the revert
capability is missing.
"""
if "revert" not in await self.capabilities():
raise AutopkgtestCommandError("revert is not supported")
await self.close()
return await self.open()
async def cmd_capabilities(self, args: list[str]) -> list[str]:
expect_args("capabilities", args, 0)
return ["ok"] + await self.capabilities()
async def cmd_close(self, args: list[str]) -> list[str]:
expect_args("close", args, 0)
await self.close()
return ["ok"]
async def cmd_copydown(self, args: list[str]) -> list[str]:
expect_args("copydown", args, 2)
if args[0].endswith("/") and args[1].endswith("/"):
await self.copydown_dir(Path(args[0]), PurePath(args[1]))
elif args[0].endswith("/") or args[1].endswith("/"):
raise AutopkgtestCommandError(
"paths given to copydown must either both or neither end in a slash"
)
else:
await self.copydown_file(Path(args[0]), PurePath(args[1]))
return ["ok"]
async def cmd_copyup(self, args: list[str]) -> list[str]:
expect_args("copyup", args, 2)
if args[0].endswith("/") and args[1].endswith("/"):
await self.copyup_dir(PurePath(args[0]), Path(args[1]))
elif args[0].endswith("/") or args[1].endswith("/"):
raise AutopkgtestCommandError(
"paths given to copyup must either both or neither end in a slash"
)
else:
await self.copyup_file(PurePath(args[0]), Path(args[1]))
return ["ok"]
async def cmd_open(self, args: list[str]) -> list[str]:
expect_args("open", args, 0)
scratchspace = await self.open()
return ["ok", os.fspath(scratchspace)]
async def cmd_print_execute_command(self, args: list[str]) -> list[str]:
expect_args("print-execute-command", args, 0)
command = await self.print_execute_command()
return ["ok", urllib.parse.quote(",".join(command))]
async def cmd_quit(self, args: list[str]) -> list[str]:
expect_args("quit", args, 0)
self._quitting = True
await self.quit()
return ["ok"]
async def cmd_revert(self, args: list[str]) -> list[str]:
expect_args("revert", args, 0)
scratchspace = await self.revert()
return ["ok", os.fspath(scratchspace)]
async def main(self) -> int:
"""The main loop of the autopkgtest virtualisation server. It processes
commands on the input stream and dispatches them to the various "cmd_*"
methods defined on this class. Each of them receives an unquoted
argument list and is supposed to return a response list or raise an
AutopkgtestCommandError to indicate an unrecoverable failure. The
returned integer is supposed to become the exit code of the process.
"""
self.send("ok")
try:
while (
(not self._quitting)
and (line := await self._reader.readline())
):
args = list(
map(urllib.parse.unquote, line.decode("utf8").split())
)
try:
command = args.pop(0)
except IndexError:
raise AutopkgtestCommandError(
"empty commands are not permitted"
) from None
try:
method = getattr(self, "cmd_" + command.replace("-", "_"))
except AttributeError:
self.send("error", f"unknown command {command!r}")
return 12
result = await method(args)
self.send(*result)
except AutopkgtestCommandError as err:
self.send("error", err.message)
return 12
return 0
def varlink_socket_path(session: str) -> Path:
"""Compute the varlink socket path from the session identifier."""
return Path(f"/tmp/pconr-{session}")
class AutopkgtestPconrServer(AutopkgtestServer):
"""autopkgtest virtualisation server implementation based on pconr"""
runtime_namespaces = (
linuxnamespaces.CloneFlags.NEWUSER | linuxnamespaces.CloneFlags.NEWNS
)
loader_namespaces = (
runtime_namespaces
| linuxnamespaces.CloneFlags.NEWIPC
| linuxnamespaces.CloneFlags.NEWUTS
| linuxnamespaces.CloneFlags.NEWPID
| linuxnamespaces.CloneFlags.NEWCGROUP
)
def __init__(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
image: Path,
*,
show_boot: bool = False,
):
super().__init__(reader, writer)
self.image = image
self.show_boot = show_boot
self.session: str | None = None
self.runtime: pconr.SpawnedContainerConnection | None = None
self.root_cgroup: PurePath | None = None
self.loader: pconr.SpawnedContainerConnection | None = None
self.init: pconr.SpawnedContainerConnection | None = None
self.console: int | None = None
async def mount_overlayfs_hierarchy(self) -> None:
assert self.runtime is not None
assert self.console is not None
await self.runtime.mount_overlayfs(
"/mnt/lower",
"/mnt/mnt",
upper="/mnt/upper",
work="/mnt/work",
options={"userxattr": None},
)
await self.runtime.populate_dev("/mnt/mnt/dev")
await self.runtime.write_text("/mnt/mnt/dev/console", "")
await self.runtime.bind_mount(
os.ptsname(self.console), "/mnt/mnt/dev/console"
)
await self.runtime.populate_sys(
"/mnt/mnt/sys", self.loader_namespaces, str(self.root_cgroup)
)
async def create_runtime(self) -> None:
assert self.runtime is None
assert self.console is None
uidmap = [
linuxnamespaces.IDAllocation.loadsubid("uid").allocatemap(65536),
linuxnamespaces.IDMapping(65536, os.getuid(), 1),
]
gidmap = [
linuxnamespaces.IDAllocation.loadsubid("gid").allocatemap(65536),
linuxnamespaces.IDMapping(65536, os.getgid(), 1),
]
self.runtime = await pconr.launch_manager()
try:
await linuxnamespaces.systemd.start_transient_unit(
f"pconr-autopkgtest-{self.runtime.pid}.scope",
pids=[self.runtime.pid],
)
self.root_cgroup = linuxnamespaces.get_cgroup(self.runtime.pid)
await self.runtime.setpriv(pdeathsig=signal.SIGTERM)
await self.runtime.unshare(self.runtime_namespaces)
linuxnamespaces.newidmaps(self.runtime.pid, uidmap, gidmap)
await self.runtime.setpriv(uid=0, gid=0, groups=[0], dumpable=True)
self.console = await self.runtime.open_file("/dev/ptmx")
try:
os.unlockpt(self.console)
await self.runtime.chown(
Path("/sys/fs/cgroup", self.root_cgroup.relative_to("/")),
0,
0,
recursive=True,
)
await self.runtime.mount_tmpfs(
"/mnt", options={"mode": "0755", "size": "10G"}
)
await self.runtime.mkdir("/mnt/lower")
await self.runtime.mkdir("/mnt/upper")
await self.runtime.mkdir("/mnt/work")
await self.runtime.mkdir("/mnt/mnt")
with await self.runtime.mount_fuse(
"/mnt/lower",
source=os.fspath(self.image),
options={
"rootmode": "040755",
"user_id": "0",
"group_id": "0",
"allow_other": None,
},
fstype="erofs",
) as fusefd:
argv = [
"erofsfuse",
"-f",
os.fspath(self.image),
f"/dev/fd/{fusefd.fileno()}",
]
@linuxnamespaces.run_in_fork.now
def _() -> None:
linuxnamespaces.prctl_set_pdeathsig(signal.SIGTERM)
linuxnamespaces.close_all_but([2, fusefd])
fd = os.open("/dev/null", os.O_RDONLY)
if fd != 0:
os.dup2(fd, 0)
os.close(fd)
fd = os.open("/dev/null", os.O_WRONLY)
if fd != 1:
os.dup2(fd, 1)
os.close(fd)
os.execvp(argv[0], argv)
await self.mount_overlayfs_hierarchy()
except:
os.close(self.console)
self.console = None
raise
except:
self.runtime.close()
self.runtime = None
await asyncio.sleep(0)
raise
async def create_loader(self) -> None:
assert self.runtime is not None
assert self.console is not None
assert self.session is None
assert self.loader is None
assert self.init is None
self.session = str(uuid.uuid4())
self.loader = await self.runtime.fork()
try:
await self.loader.setpriv(pdeathsig=signal.SIGKILL)
await self.loader.listen_varlink(varlink_socket_path(self.session))
await self.loader.unshare(self.loader_namespaces)
identity = [linuxnamespaces.IDMapping.identity(0, 65536)]
await self.runtime.newidmaps(self.loader.pid, identity, identity)
await self.loader.bind_mount("/mnt/mnt", "/mnt/mnt")
await self.loader.chdir("/mnt/mnt")
# Retain a /proc mount to be able to mount a new instance later
await self.loader.bind_mount("/proc", "/mnt/mnt/bin")
await self.loader.pivot_root(".", ".", umount_old=True)
self.init = await self.loader.fork()
try:
await self.init.setpriv(pdeathsig=signal.SIGKILL)
# The init process can mount /proc, because it is in the right
# pid namespace and still sees the original proc mounted to
# /bin.
await self.init.mount_proc("/proc")
await self.init.umount("/bin", detach=True)
if self.show_boot:
copyfut = linuxnamespaces.async_copyfd(self.console, 2)
await self.init.exec(
["/sbin/init"],
fds=[
asyncvarlink.FileDescriptor(0),
asyncvarlink.FileDescriptor(1),
asyncvarlink.FileDescriptor(2),
],
)
with await self.loader.fork() as bootwait:
await bootwait.setpriv(pdeathsig=signal.SIGKILL)
await bootwait.exec(
["/bin/systemctl", "is-system-running", "--wait"],
fds=[],
)
assert bootwait.pidfd is not None
await self.loader.waitpidfd(bootwait.pidfd)
if self.show_boot:
copyfut.cancel()
except:
self.init.close()
self.init = None
raise
except:
self.loader.close()
self.loader = None
varlink_socket_path(self.session).unlink(missing_ok=True)
self.session = None
await asyncio.sleep(0)
raise
async def terminate_loader(self) -> None:
if self.init is not None:
self.init.close()
self.init = None
if self.loader is not None:
await self.loader.exit()
self.loader.close()
self.loader = None
if self.session is not None:
varlink_socket_path(self.session).unlink()
self.session = None
async def terminate_runtime(self) -> None:
await self.terminate_loader()
if self.console is not None:
os.close(self.console)
self.console = None
if self.runtime is not None:
await self.runtime.exit()
self.runtime = None
async def __aenter__(self) -> typing.Self:
await self.create_runtime()
return self
async def __aexit__(self, *_: object) -> None:
await self.terminate_runtime()
@typing.override
async def open(self) -> PurePath:
await self.create_loader()
assert self.loader is not None
downtmp = PurePath("/srv/downtmp")
await self.loader.mkdir(downtmp)
await self.loader.chmod(downtmp, 0o1777)
return downtmp
@typing.override
async def print_execute_command(self) -> list[str]:
assert self.loader is not None
assert self.session is not None
return [sys.argv[0], "--execute-command", self.session]
@typing.override
async def capabilities(self) -> list[str]:
return [
"isolation-container",
"revert",
"revert-full-system",
"root-on-testbed",
]
@typing.override
async def close(self) -> None:
assert self.runtime is not None
await self.terminate_loader()
await self.runtime.umount("/mnt/mnt", detach=True)
await self.runtime.remove_tree("/mnt/upper", keepdir=True)
await self.runtime.remove_tree("/mnt/work", keepdir=True)
await self.mount_overlayfs_hierarchy()
@typing.override
async def copydown_file(self, source: Path, destination: PurePath) -> None:
assert self.loader is not None
with source.open(mode="rb") as srcfobj:
with await self.loader.open_file(
destination, read=False, write=True, creat=True, trunc=True
) as destfd:
while data := srcfobj.read(65536):
os.write(destfd, data)
await asyncio.sleep(0)
@typing.override
async def copydown_dir(self, source: Path, destination: PurePath) -> None:
assert self.loader is not None
for dirpath, _dirnames, files in source.walk():
destdir = destination / dirpath.relative_to(source)
await self.loader.mkdir(destdir)
for name in files:
srcpath = dirpath / name
if srcpath.is_file():
await self.copydown_file(srcpath, destdir / name)
# Should we copy other file types such as symlinks?
@typing.override
async def copyup_file(self, source: PurePath, destination: Path) -> None:
assert self.loader is not None
with destination.open(mode="wb") as destfobj:
with await self.loader.open_file(source) as srcfd:
while data := os.read(srcfd, 65536):
destfobj.write(data)
await asyncio.sleep(0)
@typing.override
async def copyup_dir(self, source: PurePath, destination: Path) -> None:
assert self.loader is not None
with await self.loader.open_file(source) as srcfd:
statres = os.fstat(srcfd)
if not stat.S_ISDIR(statres.st_mode):
raise OSError(errno.ENOTDIR)
destination.mkdir(exist_ok=True)
for entry in os.scandir(srcfd):
if entry.is_dir():
await self.copyup_dir(
source / entry.name, destination / entry.name
)
elif entry.is_file():
await self.copyup_file(
source / entry.name, destination / entry.name
)
# Ignore any other file types including symlinks as copying
# them is not generally safe.
@typing.override
async def quit(self) -> None:
await self.terminate_runtime()
async def main() -> None:
# Parsing the execute command with remainder is difficult without
# introducing a subcommand, so parse it without argparse.
if len(sys.argv) >= 4 and sys.argv[1] == "--execute-command":
session = sys.argv[2]
command = sys.argv[3:]
environ = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin"}
with (
await pconr.connect_manager(varlink_socket_path(session)) as conn,
await conn.fork() as childconn,
):
await childconn.setpriv(pdeathsig=signal.SIGKILL)
await childconn.exec(
command,
fds=[
asyncvarlink.FileDescriptor(0),
asyncvarlink.FileDescriptor(1),
asyncvarlink.FileDescriptor(2),
],
environ=environ,
)
assert childconn.pidfd is not None
sys.exit(await conn.waitpidfd(childconn.pidfd))
else:
parser = argparse.ArgumentParser()
parser.add_argument("--show-boot", action="store_true")
parser.add_argument("image", type=Path)
args = parser.parse_args()
async with AutopkgtestPconrServer(
*await connect_pipes(), args.image, show_boot=args.show_boot
) as adt_server:
sys.exit(await adt_server.main())
if __name__ == "__main__":
asyncio.run(main())
|