Debian Codegraph @

vmtest/chroot.py

raw
1 # Copyright (c) 2025 Oracle and/or its affiliates
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3 import argparse
4 import os
5 from pathlib import Path
6 import shlex
7 import subprocess
8 import sys
9 from typing import List
10
11 from vmtest.config import ARCHITECTURES, HOST_ARCHITECTURE
12
13 _PASSTHROUGH_ENV_VARS = (
14 "TERM",
15 "COLORTERM",
16 "http_proxy",
17 "https_proxy",
18 "ftp_proxy",
19 "no_proxy",
20 )
21
22
23 # When entering a chroot, we want a clean environment. These functions preserve
24 # only a few specific environment variables and execute a login shell, which
25 # will define anything else important.
26 def chroot_sh_args(new_root: str) -> List[str]:
27 return [
28 "chroot",
29 new_root,
30 "env",
31 "-i",
32 *(
33 f"{var}={value}"
34 for var in _PASSTHROUGH_ENV_VARS
35 if (value := os.getenv(var)) is not None
36 ),
37 "/bin/sh",
38 "-l",
39 "-c",
40 ]
41
42
43 def chroot_sh_cmd(new_root: str) -> str:
44 return " ".join(
45 [
46 "chroot",
47 new_root,
48 "env",
49 "-i",
50 *(f'${{{var}+{var}="${var}"}}' for var in _PASSTHROUGH_ENV_VARS),
51 "/bin/sh",
52 "-l",
53 "-c",
54 ]
55 )
56
57
58 if __name__ == "__main__":
59 parser = argparse.ArgumentParser(
60 description="run commands in the root filesystems for vmtest",
61 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
62 )
63 parser.add_argument(
64 "-d",
65 "--directory",
66 metavar="DIR",
67 type=Path,
68 default="build/vmtest",
69 help="directory for vmtest artifacts",
70 )
71 parser.add_argument(
72 "-a",
73 "--architecture",
74 type=str,
75 choices=sorted(ARCHITECTURES),
76 default=None if HOST_ARCHITECTURE is None else HOST_ARCHITECTURE.name,
77 required=HOST_ARCHITECTURE is None,
78 help="architecture to run in",
79 )
80 parser.add_argument(
81 "command",
82 type=str,
83 nargs=argparse.REMAINDER,
84 help="command to run in rootfs (default: bash -i)",
85 )
86 args = parser.parse_args()
87 arch = ARCHITECTURES[args.architecture]
88 dir = args.directory / arch.name / "rootfs"
89 command = (
90 " ".join([shlex.quote(arg) for arg in args.command])
91 if args.command
92 else "bash -i"
93 )
94 sys.exit(
95 subprocess.run(
96 [
97 "unshare",
98 "--map-root-user",
99 "--map-auto",
100 "--fork",
101 "--pid",
102 f"--mount-proc={dir / 'proc'}",
103 *chroot_sh_args(dir),
104 command,
105 ],
106 ).returncode
107 )