libatomic.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """Install the host libatomic package required by official Linux Node.
  2. Two entry points: install_before_lock() lets an interactive update install
  3. the package (asking for sudo) before PM takes its install lock, and
  4. try_install_libatomic() is the non-interactive repair run from Nodejs.repair_staged_verification().
  5. Package verification itself remains diagnostic and side-effect free.
  6. """
  7. from __future__ import annotations
  8. import os
  9. import platform
  10. import shlex
  11. import shutil
  12. import subprocess
  13. _INSTALLERS: dict[str, tuple[str, ...]] = {
  14. "apt-get": ("apt-get", "install", "-y", "libatomic1"),
  15. "dnf": ("dnf", "install", "-y", "libatomic"),
  16. "yum": ("yum", "install", "-y", "libatomic"),
  17. "zypper": ("zypper", "--non-interactive", "install", "libatomic1"),
  18. "pacman": ("pacman", "-S", "--needed", "--noconfirm", "gcc-libs"),
  19. "apk": ("apk", "add", "libatomic"),
  20. }
  21. _DEBIAN = {"debian", "ubuntu", "linuxmint", "pop", "raspbian", "kali", "elementary"}
  22. _RPM = {"rhel", "fedora", "centos", "rocky", "almalinux", "ol", "oracle", "amzn"}
  23. _ARCH = {"arch", "manjaro", "endeavouros", "garuda", "artix"}
  24. # One attempt per process: every root that depends on node (npm, browser
  25. # tools) re-stages it after a failure, and each would otherwise re-run the
  26. # package manager under PM's install lock. A later process retries.
  27. _ATTEMPT: tuple[bool, str] | None = None
  28. def _release_tokens() -> set[str]:
  29. try:
  30. fields = platform.freedesktop_os_release()
  31. except OSError:
  32. return set()
  33. blob = f"{fields.get('ID', '')} {fields.get('ID_LIKE', '')}".lower()
  34. return set(blob.replace(",", " ").split())
  35. def _manager_order(tokens: set[str]) -> tuple[str, ...]:
  36. if tokens & _DEBIAN:
  37. return ("apt-get",)
  38. if tokens & _RPM:
  39. return ("dnf", "yum")
  40. if any("suse" in token or token.startswith("sles") for token in tokens):
  41. return ("zypper",)
  42. if tokens & _ARCH:
  43. return ("pacman",)
  44. if "alpine" in tokens:
  45. return ("apk",)
  46. return ("dnf", "yum", "apt-get", "zypper", "pacman", "apk")
  47. def _host_install_command() -> tuple[str, ...] | None:
  48. for manager in _manager_order(_release_tokens()):
  49. if shutil.which(manager):
  50. return _INSTALLERS[manager]
  51. return None
  52. def _is_root() -> bool:
  53. return bool(hasattr(os, "geteuid") and os.geteuid() == 0)
  54. def _command_plan(command: tuple[str, ...]) -> tuple[list[str] | None, str, str]:
  55. """Return auto-repair argv, its display form, and a runnable manual remedy.
  56. Host-package repair runs while PM owns its publication lock, so it must never
  57. wait on an interactive privilege prompt. Non-root repair therefore uses
  58. ``sudo -n`` even on a TTY. The manual remedy may use normal ``sudo``
  59. outside that lock. If sudo is unavailable, don't advertise it at all.
  60. """
  61. if _is_root():
  62. argv = list(command)
  63. shown = shlex.join(argv)
  64. return argv, shown, shown
  65. sudo = shutil.which("sudo")
  66. if sudo:
  67. argv = [sudo, "-n", *command]
  68. return argv, shlex.join(["sudo", "-n", *command]), shlex.join(["sudo", *command])
  69. return None, "", f"as root: {shlex.join(command)}"
  70. def install_before_lock() -> None:
  71. """Install the libatomic package interactively before PM takes its lock.
  72. Inside the lock the repair may only use ``sudo -n``, so a password-sudo
  73. host needs the password asked here, where a prompt cannot wedge PM. Run
  74. only on a glibc Linux host still missing libatomic.so.1, with a
  75. controlling terminal sudo can read from (detached children, gateway and
  76. Desktop updates have none), and only when sudo would actually ask.
  77. """
  78. import ctypes
  79. import sys
  80. from pm.store import MUSL_TARGETS, current_target
  81. if not sys.platform.startswith("linux") or _is_root() or not _has_terminal():
  82. return
  83. try:
  84. target = current_target()
  85. except RuntimeError: # unsupported architecture: PM reports it elsewhere
  86. return
  87. if target in MUSL_TARGETS or target.endswith("-bionic"):
  88. return
  89. try:
  90. ctypes.CDLL("libatomic.so.1")
  91. return
  92. except OSError:
  93. pass
  94. command = _host_install_command()
  95. if command is None:
  96. return
  97. argv = _command_plan(command)[0]
  98. if not argv:
  99. return
  100. sudo = argv[0]
  101. if _run([sudo, "-n", "true"], timeout=10):
  102. return # the non-interactive repair will succeed on its own
  103. print("→ Node.js needs libatomic.so.1; sudo may ask for your password to install it", flush=True)
  104. # Outside PM's lock: no timeout, so a slow prompt or mirror is never killed mid-dpkg.
  105. _install([sudo], command, stdin=None, timeout=None)
  106. def _has_terminal() -> bool:
  107. try:
  108. os.close(os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY))
  109. except OSError:
  110. return False
  111. return True
  112. def _run(argv: list[str], stdin: int | None = subprocess.DEVNULL, timeout: float | None = 300) -> bool:
  113. try:
  114. return subprocess.run(argv, stdin=stdin, timeout=timeout, check=False).returncode == 0
  115. except (OSError, subprocess.TimeoutExpired):
  116. return False
  117. def _install(prefix: list[str], command: tuple[str, ...], stdin: int | None = subprocess.DEVNULL,
  118. timeout: float | None = 300) -> bool:
  119. if _run([*prefix, *command], stdin, timeout):
  120. return True
  121. if command[0] != "apt-get":
  122. return False
  123. # Minimal Debian/Ubuntu images ship empty package lists.
  124. return (_run([*prefix, "apt-get", "update", "-qq"], stdin, timeout)
  125. and _run([*prefix, *command], stdin, timeout))
  126. def try_install_libatomic() -> tuple[bool, str]:
  127. """Try the distro-native libatomic package; return (attempt_succeeded, hint).
  128. Success means the package-manager command completed successfully. The Node
  129. smoke probe remains the authority and is always repeated by the caller.
  130. """
  131. global _ATTEMPT
  132. if _ATTEMPT is None:
  133. _ATTEMPT = _attempt()
  134. return _ATTEMPT
  135. def _attempt() -> tuple[bool, str]:
  136. command = _host_install_command()
  137. if command is None:
  138. return (
  139. False,
  140. "official Node needs libatomic.so.1; install the distro package that provides it and rerun",
  141. )
  142. argv, attempt_display, remedy_display = _command_plan(command)
  143. remedy = f"install the missing runtime library with {remedy_display} and rerun"
  144. if argv is None:
  145. return False, remedy
  146. print(f"→ Node needs libatomic.so.1; trying non-interactive {attempt_display}", flush=True)
  147. return _install(argv[: len(argv) - len(command)], command), remedy