summary.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """One summary of this machine and its OS account, for the desktop first-run onboarding.
  2. Hardware facts come from ``hermes_platform.host``. Account facts (full name, locale) come from OS
  3. user records through ``pwd`` or Win32/CoreFoundation calls, never from environment variables such
  4. as HOME or LANG, and never from a subprocess or the network. They describe the machine that runs
  5. the Hermes backend; when the desktop app drives a remote backend, that is not the user's laptop.
  6. """
  7. from __future__ import annotations
  8. import functools
  9. import os
  10. import platform
  11. import re
  12. import sys
  13. from hermes_platform.host import facts as host
  14. from hermes_platform.host import products, runtime
  15. # Generic account names that are not a person's name.
  16. _NON_NAMES = frozenset({
  17. "admin", "administrator", "default", "guest", "me", "owner", "root", "test", "user",
  18. })
  19. _HANDLE_CHARS = re.compile(r"[\d_@/\\]")
  20. # --- account facts -----------------------------------------------------------------
  21. def _posix_account() -> tuple[str, str]:
  22. """Return (login, full name) from the user database."""
  23. import pwd
  24. entry = pwd.getpwuid(os.getuid()) # windows-footgun: ok — only called off Windows (_account)
  25. return entry.pw_name, entry.pw_gecos.split(",", 1)[0].strip()
  26. def _windows_account() -> tuple[str, str]:
  27. """Return (login, display name) from Win32 account APIs."""
  28. import ctypes
  29. from ctypes import wintypes
  30. login_buf = ctypes.create_unicode_buffer(257)
  31. login_len = wintypes.DWORD(len(login_buf))
  32. login = login_buf.value if ctypes.windll.advapi32.GetUserNameW(login_buf, ctypes.byref(login_len)) else ""
  33. # EXTENDED_NAME_FORMAT NameDisplay = 3. Local accounts without a display name fail here.
  34. name_buf = ctypes.create_unicode_buffer(257)
  35. name_len = wintypes.ULONG(len(name_buf))
  36. full = name_buf.value if ctypes.windll.secur32.GetUserNameExW(3, name_buf, ctypes.byref(name_len)) else ""
  37. return login, full
  38. def _account() -> tuple[str, str]:
  39. try:
  40. return _windows_account() if sys.platform == "win32" else _posix_account()
  41. except (AttributeError, ImportError, KeyError, OSError):
  42. return "", ""
  43. def full_name_from(login: str, full: str) -> str | None:
  44. """A real full name only; a login handle is never offered as the user's name."""
  45. name = " ".join(full.split())
  46. if not (2 <= len(name) <= 40) or name.lower() in _NON_NAMES or name.lower() == login.lower():
  47. return None
  48. # Digits or underscores ("p14", "CD_01.05") or an all-lowercase cased name mark a handle.
  49. if _HANDLE_CHARS.search(name) or name == name.lower() != name.upper():
  50. return None
  51. return name
  52. def _darwin_locale() -> str:
  53. """First preferred UI language, e.g. ``de-DE``, via CoreFoundation."""
  54. import ctypes
  55. import ctypes.util
  56. cf = ctypes.CDLL(ctypes.util.find_library("CoreFoundation"))
  57. cf.CFLocaleCopyPreferredLanguages.restype = ctypes.c_void_p
  58. cf.CFArrayGetCount.argtypes = [ctypes.c_void_p]
  59. cf.CFArrayGetCount.restype = ctypes.c_long
  60. cf.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
  61. cf.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
  62. cf.CFStringGetCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]
  63. cf.CFStringGetCString.restype = ctypes.c_bool
  64. cf.CFRelease.argtypes = [ctypes.c_void_p]
  65. languages = cf.CFLocaleCopyPreferredLanguages()
  66. if not languages:
  67. return ""
  68. try:
  69. if cf.CFArrayGetCount(languages) < 1:
  70. return ""
  71. buffer = ctypes.create_string_buffer(64)
  72. # kCFStringEncodingUTF8
  73. if not cf.CFStringGetCString(cf.CFArrayGetValueAtIndex(languages, 0), buffer, 64, 0x08000100):
  74. return ""
  75. return buffer.value.decode()
  76. finally:
  77. cf.CFRelease(languages)
  78. def _windows_locale() -> str:
  79. import ctypes
  80. buffer = ctypes.create_unicode_buffer(85)
  81. return buffer.value if ctypes.windll.kernel32.GetUserDefaultLocaleName(buffer, 85) else ""
  82. def _linux_locale() -> str:
  83. """System locale from its config file; the shell's LANG is deliberately not read."""
  84. for path in ("/etc/locale.conf", "/etc/default/locale"):
  85. try:
  86. with open(path, encoding="utf-8-sig") as handle:
  87. for line in handle:
  88. key, _, value = line.strip().partition("=")
  89. if key == "LANG" and value:
  90. return value.strip("\"'").split(".", 1)[0].replace("_", "-")
  91. except OSError:
  92. continue
  93. return ""
  94. def _locale() -> str:
  95. try:
  96. if sys.platform == "darwin":
  97. return _darwin_locale()
  98. if sys.platform == "win32":
  99. return _windows_locale()
  100. return _linux_locale()
  101. except (AttributeError, OSError, TypeError, ValueError):
  102. return ""
  103. # --- the summary ----------------------------------------------------------------------
  104. def _machine_kind(os_family: str, nvidia: str | None) -> str:
  105. if nvidia in ("rtx_spark", "dgx_spark"):
  106. return "Spark"
  107. return {"darwin": "Mac", "win32": "PC"}.get(os_family, "computer")
  108. def _os_release(os_family: str) -> str:
  109. # On a Mac platform.release() is the Darwin kernel version (25.x), not the macOS version (26.x).
  110. return (platform.mac_ver()[0] if os_family == "darwin" else "") or platform.release()
  111. @functools.cache
  112. def summary() -> dict:
  113. """This machine and account as measured. ``machine`` leaves out a key that was not measured;
  114. ``locale`` and ``full_name`` are None when the OS has none to give."""
  115. os_family, arch, gpu, cpu = host.os_family(), host.native_arch(), host.gpu_class(), host.cpu_model()
  116. ram = host.ram_total_bytes()
  117. nvidia = products.nvidia_platform()
  118. machine = {
  119. "os_family": os_family,
  120. "os_release": _os_release(os_family),
  121. "native_arch": arch,
  122. "cpu_model": cpu,
  123. "ram_gb": round(ram / 2**30) if ram else None,
  124. "gpu_class": None if gpu == "unknown" else gpu,
  125. "vendor": host.cpu_vendor(),
  126. "wsl": runtime.is_wsl(),
  127. "container": runtime.is_container(),
  128. }
  129. return {
  130. "machine": {key: value for key, value in machine.items() if value not in (None, "")},
  131. "machine_kind": _machine_kind(os_family, nvidia),
  132. "has_nvidia_gpu": gpu == "nvidia",
  133. "nvidia_platform": nvidia,
  134. "locale": _locale() or None,
  135. "full_name": full_name_from(*_account()),
  136. }