runner.py 6.8 KB

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