runner.py 6.5 KB

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