runtime.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Cached runtime-environment predicates for WSL, containers, and Termux."""
  2. from __future__ import annotations
  3. import os
  4. def is_termux() -> bool:
  5. """Return whether this process runs inside Termux."""
  6. prefix = os.getenv("PREFIX", "")
  7. return bool(os.getenv("TERMUX_VERSION") or "com.termux/files/usr" in prefix)
  8. _wsl_detected: bool | None = None
  9. def is_wsl() -> bool:
  10. """Return whether this process runs inside WSL."""
  11. global _wsl_detected
  12. if _wsl_detected is None:
  13. try:
  14. with open("/proc/version", "r", encoding="utf-8") as f:
  15. _wsl_detected = "microsoft" in f.read().lower()
  16. except Exception:
  17. _wsl_detected = False
  18. return _wsl_detected
  19. _container_detected: bool | None = None
  20. def is_container() -> bool:
  21. """Return whether this process runs inside a container."""
  22. global _container_detected
  23. if _container_detected is None:
  24. _container_detected = _detect_container()
  25. return _container_detected
  26. def _read_proc(path: str) -> str:
  27. try:
  28. with open(path, "r", encoding="utf-8") as f:
  29. return f.read()
  30. except OSError:
  31. return ""
  32. def _proc_file_has_marker(path: str, markers: tuple[str, ...]) -> bool:
  33. content = _read_proc(path)
  34. return any(marker in content for marker in markers)
  35. def _detect_container() -> bool:
  36. if (
  37. os.path.exists("/.dockerenv")
  38. or os.path.exists("/run/.containerenv")
  39. or os.environ.get("KUBERNETES_SERVICE_HOST")
  40. or _proc_file_has_marker("/proc/1/cgroup", ("docker", "podman", "/lxc/", "kubepods", "containerd", "crio"))
  41. ):
  42. return True
  43. # Under cgroup v2, only the root mount identifies this process's container.
  44. # Scanning all mountinfo lines misclassifies hosts that run containers (#58135).
  45. return _root_mount_has_marker("/proc/self/mountinfo", ("kubepods", "containerd", "crio"))
  46. def _root_mount_has_marker(path: str, markers: tuple[str, ...]) -> bool:
  47. """Return whether the root mount contains any marker."""
  48. root_lines = [line for line in _read_proc(path).splitlines() if len(f := line.split()) >= 5 and f[4] == "/"]
  49. return any(marker in line for line in root_lines for marker in markers)