runner.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """Where a session's programs run: natively when they are installed, in a distribution rootfs under proot otherwise.
  2. Sessions never inherit the caller's environment, a sandbox shares its host's display, audio and D-Bus sockets and a
  3. test must never reach them.
  4. """
  5. import os
  6. import shutil
  7. import signal
  8. import subprocess
  9. import time
  10. from pathlib import Path
  11. REPO = Path(__file__).resolve().parents[2]
  12. BASE = Path(os.environ.get("LWE_DESKTOPS_DIR", "/tmp/lwe-d"))
  13. ROOTFS_DIR = Path(os.environ.get("LWE_ROOTFS_DIR", Path.home() / ".local/share/distro-rootfs"))
  14. ROOTFS = {
  15. "fedora": Path(os.environ.get("LWE_FEDORA_ROOTFS", ROOTFS_DIR / "fedora-44-sys")),
  16. "arch": Path(os.environ.get("LWE_ARCH_ROOTFS", ROOTFS_DIR / "arch-compositors")),
  17. # older GNOME Shells for the gnome45..gnome49 sessions
  18. "gnome45": ROOTFS_DIR / "ubuntu-23.10-gnome",
  19. "gnome46": ROOTFS_DIR / "ubuntu-24.04-gnome",
  20. "gnome47": ROOTFS_DIR / "ubuntu-24.10-gnome",
  21. "gnome48": ROOTFS_DIR / "ubuntu-25.04-gnome",
  22. "gnome49": ROOTFS_DIR / "fedora-43-gnome",
  23. "kde5": ROOTFS_DIR / "ubuntu-24.04-kde5",
  24. }
  25. BIN_DIRS = ("usr/bin", "usr/sbin", "usr/libexec", "bin", "sbin")
  26. SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  27. def proot_binary():
  28. return os.environ.get("PROOT") or shutil.which("proot") or str(Path.home() / ".local/share/arch-proot/proot")
  29. class Userland:
  30. """native, or the programs of one of the ROOTFS"""
  31. def __init__(self, name):
  32. self.name = name
  33. def __repr__(self):
  34. return f"Userland({self.name})"
  35. def has(self, program):
  36. if self.name == "native":
  37. return shutil.which(program) is not None
  38. root = ROOTFS[self.name]
  39. return any((root / directory / program).exists() for directory in BIN_DIRS)
  40. def exists(self, path):
  41. """an absolute path inside the userland"""
  42. root = Path("/") if self.name == "native" else ROOTFS[self.name]
  43. return (root / path.lstrip("/")).exists()
  44. def path(self, program):
  45. if self.name == "native":
  46. return shutil.which(program) or next(
  47. (str(Path("/") / d / program) for d in BIN_DIRS if (Path("/") / d / program).exists()), None
  48. )
  49. root = ROOTFS[self.name]
  50. return next((f"/{d}/{program}" for d in BIN_DIRS if (root / d / program).exists()), None)
  51. @staticmethod
  52. def pick(*programs, prefer=("native", "fedora", "arch")):
  53. """the first userland that has all of the programs"""
  54. for name in prefer:
  55. userland = Userland(name)
  56. if (name == "native" or ROOTFS[name].is_dir()) and all(userland.has(p) for p in programs):
  57. return userland
  58. raise RuntimeError(
  59. f"none of {', '.join(programs)} is installed here and no rootfs has it, "
  60. f"run: python3 tools/desktop_session.py setup"
  61. )
  62. def command(self, argv, env):
  63. assignments = [f"{key}={value}" for key, value in env.items()]
  64. if self.name == "native":
  65. home = env.get("HOME", "/tmp")
  66. argv = [_without_file_capabilities(argv[0]), *argv[1:]]
  67. command = ["env", "-i", f"PATH={os.environ.get('PATH', SYSTEM_PATH)}", f"HOME={home}", "LANG=C.UTF-8", *assignments, *argv]
  68. # a read-only shared /tmp/.X11-unix stops compositors from starting Xwayland
  69. if not os.access("/tmp/.X11-unix", os.W_OK):
  70. sockets = BASE / "x11-unix"
  71. sockets.mkdir(parents=True, exist_ok=True, mode=0o1777)
  72. command = [proot_binary(), "-b", f"{sockets}:/tmp/.X11-unix", *command]
  73. return command
  74. return [str(REPO / "tools/distro_rootfs.sh"), "run", str(ROOTFS[self.name]), "-u", "env", *assignments, *argv]
  75. def process_env(self):
  76. env = dict(os.environ)
  77. if self.name != "native":
  78. env["BINDS"] = f"-b {BASE}:{BASE} -b {REPO}:{REPO}"
  79. env["PROOT"] = proot_binary()
  80. return env
  81. def spawn(self, argv, env, log):
  82. """starts a program in a session of its own, so that its whole tree can be taken down"""
  83. with open(log, "ab") as out:
  84. return subprocess.Popen(
  85. self.command(argv, env), stdout=out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
  86. env=self.process_env(), start_new_session=True,
  87. )
  88. def run(self, argv, env, timeout=60, check=False):
  89. return subprocess.run(
  90. self.command(argv, env), capture_output=True, text=True, timeout=timeout, check=check,
  91. stdin=subprocess.DEVNULL, env=self.process_env(),
  92. )
  93. def _without_file_capabilities(program):
  94. """no_new_privs (Docker) refuses to exec files with capabilities (Fedora's sway/kwin_wayland), a copy has none"""
  95. path = shutil.which(program) or program
  96. if not os.path.isabs(path):
  97. return program
  98. try:
  99. os.getxattr(path, "security.capability")
  100. except OSError:
  101. return program
  102. with open("/proc/self/status") as status:
  103. if "NoNewPrivs:\t1" not in status.read():
  104. return program
  105. copy = BASE / "nocap" / os.path.basename(path)
  106. if not copy.exists() or copy.stat().st_mtime < os.stat(path).st_mtime:
  107. copy.parent.mkdir(parents=True, exist_ok=True)
  108. shutil.copyfile(path, copy)
  109. copy.chmod(0o755)
  110. return str(copy)
  111. def wait_for(what, check, timeout=30.0, interval=0.2):
  112. deadline = time.monotonic() + timeout
  113. while time.monotonic() < deadline:
  114. value = check()
  115. if value:
  116. return value
  117. time.sleep(interval)
  118. raise TimeoutError(f"timed out after {timeout:.0f}s waiting for {what}")
  119. def terminate(pids, grace=3.0):
  120. """SIGTERM to the process groups, SIGKILL for what is left after the grace time"""
  121. for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, 1.0)):
  122. for pid in pids:
  123. try:
  124. os.killpg(pid, sig)
  125. except (ProcessLookupError, PermissionError):
  126. pass
  127. deadline = time.monotonic() + wait
  128. while time.monotonic() < deadline and any(_alive(pid) for pid in pids):
  129. time.sleep(0.1)
  130. def _alive(pid):
  131. try:
  132. with open(f"/proc/{pid}/stat") as stat:
  133. return stat.read().rsplit(")", 1)[1].split()[0] != "Z"
  134. except (FileNotFoundError, ProcessLookupError):
  135. return False
  136. def kill_with_runtime_dir(run_dir):
  137. """what changed its session id (daemons started through D-Bus activation) is found by its runtime dir"""
  138. needle = f"XDG_RUNTIME_DIR={run_dir}".encode() + b"\0"
  139. for entry in Path("/proc").iterdir():
  140. if not entry.name.isdigit() or int(entry.name) == os.getpid():
  141. continue
  142. try:
  143. if needle in (entry / "environ").read_bytes():
  144. os.kill(int(entry.name), signal.SIGKILL)
  145. except (OSError, ProcessLookupError):
  146. pass