hostinfo.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # SPDX-FileCopyrightText: 2026 MOD Audio UG
  2. # SPDX-License-Identifier: AGPL-3.0-or-later
  3. """What "Report a problem" can say about the computer mod-ui runs on.
  4. Only used where mod-ui runs on a user's own computer (MOD Desktop): a MOD device
  5. has a hardware descriptor, a release file and a controller, a computer has none
  6. of them. Standard library only, every probe is best effort and returns None when
  7. it cannot answer. Nothing here identifies the user: no hostname, no serial, and
  8. the home folder is replaced by "~" in anything copied from a log.
  9. """
  10. import os
  11. import platform
  12. import re
  13. import subprocess
  14. import sys
  15. LOG_LINES = 12
  16. JACKD_LINE = re.compile(r'Starting jackd using:\s*(.*)$')
  17. PROBLEM_LINE = re.compile(r'error|fail|invalid|unable|cannot|can\'t|xrun|warning|critical', re.I)
  18. def _run(args):
  19. try:
  20. out = subprocess.run(args, capture_output=True, text=True, timeout=3).stdout
  21. return out.strip() or None
  22. except Exception:
  23. return None
  24. def _read(path):
  25. try:
  26. with open(path, 'r') as fh:
  27. return fh.read()
  28. except (IOError, OSError):
  29. return None
  30. def os_name():
  31. system = platform.system()
  32. if system == 'Darwin':
  33. return "macOS %s (%s)" % (platform.mac_ver()[0] or '?', platform.machine())
  34. if system == 'Windows':
  35. # platform.release() says "10" on Windows 11; the build number tells them apart
  36. build = 0
  37. try:
  38. build = int(platform.version().split('.')[2])
  39. except (IndexError, ValueError):
  40. pass
  41. return "Windows %s (build %s, %s)" % ('11' if build >= 22000 else platform.release(),
  42. platform.version(), platform.machine())
  43. if system == 'Linux':
  44. name = None
  45. for line in (_read('/etc/os-release') or '').splitlines():
  46. if line.startswith('PRETTY_NAME='):
  47. name = line.split('=', 1)[1].strip().strip('"')
  48. return "%s (kernel %s, %s)" % (name or 'Linux', platform.release(), platform.machine())
  49. return "%s %s (%s)" % (system, platform.release(), platform.machine())
  50. def cpu_name():
  51. system = platform.system()
  52. name = None
  53. if system == 'Windows':
  54. try:
  55. import winreg
  56. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
  57. r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as key:
  58. name = winreg.QueryValueEx(key, "ProcessorNameString")[0]
  59. except Exception:
  60. name = None
  61. elif system == 'Darwin':
  62. name = _run(['sysctl', '-n', 'machdep.cpu.brand_string'])
  63. elif system == 'Linux':
  64. for line in (_read('/proc/cpuinfo') or '').splitlines():
  65. if line.startswith('model name'):
  66. name = line.split(':', 1)[1].strip()
  67. break
  68. name = re.sub(r'\s+', ' ', name or platform.processor() or '').strip()
  69. cores = os.cpu_count()
  70. if not name:
  71. return None
  72. return "%s, %s threads" % (name, cores) if cores else name
  73. def memory_gb():
  74. total = None
  75. system = platform.system()
  76. try:
  77. if system == 'Windows':
  78. import ctypes
  79. class MEMORYSTATUSEX(ctypes.Structure):
  80. _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
  81. ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
  82. ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
  83. ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
  84. ("sullAvailExtendedVirtual", ctypes.c_ulonglong)]
  85. stat = MEMORYSTATUSEX()
  86. stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
  87. if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)):
  88. total = stat.ullTotalPhys
  89. elif system == 'Darwin':
  90. total = int(_run(['sysctl', '-n', 'hw.memsize']) or 0) or None
  91. elif system == 'Linux':
  92. for line in (_read('/proc/meminfo') or '').splitlines():
  93. if line.startswith('MemTotal:'):
  94. total = int(line.split()[1]) * 1024
  95. break
  96. except Exception:
  97. total = None
  98. return round(total / (1024 ** 3), 1) if total else None
  99. def uptime_seconds():
  100. system = platform.system()
  101. try:
  102. if system == 'Windows':
  103. import ctypes
  104. return int(ctypes.windll.kernel32.GetTickCount64() / 1000)
  105. if system == 'Darwin':
  106. m = re.search(r'sec = (\d+)', _run(['sysctl', '-n', 'kern.boottime']) or '')
  107. if m:
  108. import time
  109. return int(time.time()) - int(m.group(1))
  110. if system == 'Linux':
  111. return int(float((_read('/proc/uptime') or '').split()[0]))
  112. except Exception:
  113. pass
  114. return None
  115. def _scrub(text, home):
  116. if home:
  117. text = text.replace(home, '~').replace(home.replace('\\', '/'), '~')
  118. return text
  119. def launcher_log(directories, home):
  120. """The audio setup the launcher started and its latest problem lines.
  121. directories: folders that may hold launcher.log. Returns None when there is none.
  122. """
  123. for directory in directories:
  124. content = _read(os.path.join(directory, 'launcher.log'))
  125. if content:
  126. break
  127. else:
  128. return None
  129. lines = content.splitlines()
  130. jackd = None
  131. for line in lines:
  132. m = JACKD_LINE.search(line)
  133. if m:
  134. jackd = m.group(1).strip()
  135. # only what happened since the last start, so an old session cannot mislead
  136. start = max([i for i, line in enumerate(lines) if JACKD_LINE.search(line)] or [0])
  137. problems = [l for l in lines[start:] if PROBLEM_LINE.search(l)][-LOG_LINES:]
  138. return {
  139. "jackd": _scrub(jackd, home) if jackd else None,
  140. "problems": [_scrub(re.sub(r'\x1b\[[0-9;]*m', '', l), home) for l in problems],
  141. "path": _scrub(os.path.join(directory, 'launcher.log'), home),
  142. }
  143. def collect(log_directories, home=None):
  144. home = home or os.path.expanduser('~')
  145. return {
  146. "os": os_name(),
  147. "cpu": cpu_name(),
  148. "memory_gb": memory_gb(),
  149. "uptime": uptime_seconds(),
  150. "python": sys.version.split()[0],
  151. "launcher": launcher_log(log_directories, home),
  152. }