diagnostics.service.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { execFile } from 'child_process'
  2. import { promisify } from 'util'
  3. import * as fs from 'fs'
  4. import * as os from 'os'
  5. import { app } from 'electron'
  6. import { getAllWallpapers, getWallpaper } from './library.service'
  7. import { compatStatus } from '@shared/compat'
  8. import { applyWallpaperMeta } from './wallpaper.service'
  9. import {
  10. getEngineHistory,
  11. getLweStatus,
  12. getRunningInstances,
  13. onLweExit,
  14. setDiagnosticStats,
  15. type EngineHistory
  16. } from './lwe.service'
  17. import { stopDisplay } from './display.service'
  18. import { getPlaybackStates, pausePlaylist, resumePlaylist } from './playlist-player.service'
  19. import { detectDesktopEnv, detectDisplayServer, getConnectedScreens, runningAppImage } from '../utils/platform'
  20. import { hostCommand, hostAppPath, isFlatpak } from '../utils/flatpak'
  21. const execFileAsync = promisify(execFile)
  22. const DEFAULT_SECONDS = 20
  23. const SOFTWARE_RENDERER = /llvmpipe|softpipe|swrast/i
  24. const ENV_PREFIXES = ['XDG_', 'WAYLAND', 'DISPLAY', 'LIBGL', '__EGL', '__GLX', 'MESA', 'GBM', 'LD_', 'FLATPAK_', 'QT_QPA', 'GDK_']
  25. const PROJECT_JSON_LIMIT = 8192
  26. const CRASHED_LIMIT = 8
  27. export interface DiagnosticsTarget {
  28. wallpaperId: string
  29. screen: string
  30. }
  31. export class NoEngineRunningError extends Error {
  32. constructor() {
  33. super('No wallpaper is running')
  34. }
  35. }
  36. async function tryRun(cmd: string, args: string[], onHost = false, lines = 60): Promise<string> {
  37. const [file, fileArgs] = onHost ? hostCommand(cmd, args) : [cmd, args]
  38. try {
  39. const { stdout, stderr } = await execFileAsync(file, fileArgs, { timeout: 8000, maxBuffer: 1 << 20 })
  40. const text = (stdout || stderr).trim()
  41. return text ? text.split('\n').slice(0, lines).join('\n') : '(no output)'
  42. } catch (err) {
  43. const e = err as NodeJS.ErrnoException & { stdout?: string }
  44. if (e.code === 'ENOENT') return '(not installed)'
  45. return `(failed: ${e.message.split('\n')[0]})`
  46. }
  47. }
  48. function readText(file: string, limit = 4096): string {
  49. try {
  50. return fs.readFileSync(file, 'utf8').slice(0, limit).trim()
  51. } catch {
  52. return '(unreadable)'
  53. }
  54. }
  55. function section(title: string, body: string): string {
  56. return `\n## ${title}\n\n${body.trim() || '(empty)'}\n`
  57. }
  58. function pathRedactor(): (text: string) => string {
  59. const home = os.homedir()
  60. const user = os.userInfo().username
  61. return (text) => {
  62. let out = text.split(home).join('~')
  63. if (user.length >= 3) out = out.replace(new RegExp(`\\b${user.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g'), '<user>')
  64. return out
  65. }
  66. }
  67. function gpuLines(lspci: string): string {
  68. const found = lspci.split('\n').filter((line) => /vga|3d controller|display controller/i.test(line))
  69. return found.length ? found.join('\n') : lspci
  70. }
  71. function summarize(histories: EngineHistory[]): string[] {
  72. const notes: string[] = []
  73. const all = histories.flatMap((h) => h.lines)
  74. const renderer = all.find((line) => line.includes('OpenGL renderer:'))
  75. if (renderer) {
  76. notes.push(`Renderer: ${renderer.replace(/^.*OpenGL renderer:\s*/, '')}`)
  77. if (SOFTWARE_RENDERER.test(renderer)) {
  78. notes.push('PROBLEM: the engine renders on the CPU (software OpenGL), not on the GPU')
  79. }
  80. } else {
  81. notes.push('Renderer: not logged (older engine build)')
  82. if (all.some((line) => /failed to create dri2 screen|driver \(null\)/.test(line))) {
  83. notes.push('SUSPECT: Mesa could not open the GPU driver, rendering is probably done on the CPU')
  84. }
  85. }
  86. for (const h of histories) {
  87. const stats = h.lines.filter((line) => line.includes('FRAME-STATS'))
  88. if (stats.length) notes.push(`${h.screen}: ${stats[stats.length - 1].replace(/^.*FRAME-STATS\s*/, '')}`)
  89. }
  90. return notes
  91. }
  92. async function snapshotInstances(): Promise<string> {
  93. const pids = getRunningInstances().map((i) => i.pid).filter((pid) => pid > 0)
  94. const engines = pids.length
  95. ? await tryRun('ps', ['-o', 'pid,pcpu,pmem,rss,nlwp,etime,args', '-p', pids.join(',')])
  96. : '(none)'
  97. const busiest = await tryRun('ps', ['-eo', 'pcpu,pmem,comm', '--sort=-pcpu'], true, 9)
  98. return `Engine processes (as seen by WE Manager):\n${engines}\n\nBusiest processes on the machine:\n${busiest}`
  99. }
  100. async function restartPlaying(): Promise<string[]> {
  101. const notes: string[] = []
  102. const library = getAllWallpapers()
  103. for (const inst of getRunningInstances()) {
  104. const wallpaper = library.find((w) => w.localPath === inst.wallpaperPath)
  105. if (inst.split || !wallpaper) {
  106. notes.push(`${inst.screen}: not restarted (${inst.split ? 'split screen' : 'not in the library'})`)
  107. continue
  108. }
  109. await applyWallpaperMeta(wallpaper, { screen: inst.screen, forceFresh: true })
  110. }
  111. return notes
  112. }
  113. function systemInfo(): string {
  114. const cpus = os.cpus()
  115. const packaging = isFlatpak() ? 'Flatpak' : runningAppImage() ? 'AppImage' : app.isPackaged ? 'native package' : 'source'
  116. const env = Object.entries(process.env)
  117. .filter(([key]) => ENV_PREFIXES.some((prefix) => key.startsWith(prefix)))
  118. .map(([key, value]) => `${key}=${value}`)
  119. .sort()
  120. const lines = [
  121. `WE Manager: ${app.getVersion()} (${packaging})`,
  122. `OS: ${readText('/etc/os-release').split('\n').find((l) => l.startsWith('PRETTY_NAME=')) ?? os.type()}`,
  123. `Kernel: ${os.release()}`,
  124. `Desktop: ${detectDesktopEnv()} on ${detectDisplayServer()}`,
  125. `Screens: ${getConnectedScreens().join(', ') || '(none found)'}`,
  126. `CPU: ${cpus[0]?.model ?? 'unknown'} x${cpus.length}`,
  127. `Memory: ${Math.round(os.totalmem() / 2 ** 20)} MiB total, ${Math.round(os.freemem() / 2 ** 20)} MiB free`
  128. ]
  129. const engine = getLweStatus()
  130. lines.push(`Engine: ${engine.installed ? `${engine.path}${engine.version ? ` (${engine.version})` : ''}` : 'not installed'}`)
  131. if (isFlatpak()) {
  132. lines.push(`Flatpak app path: ${hostAppPath() ?? 'unknown'}`)
  133. }
  134. return `${lines.join('\n')}\n\nEnvironment:\n${env.join('\n')}`
  135. }
  136. async function graphicsInfo(): Promise<string> {
  137. const [lspci, nvidia, eglinfo, glxinfo, vulkan] = await Promise.all([
  138. tryRun('lspci', ['-nn'], true, 200),
  139. tryRun('nvidia-smi', ['--query-gpu=name,driver_version', '--format=csv,noheader'], true),
  140. tryRun('eglinfo', ['-B'], false, 80),
  141. tryRun('glxinfo', ['-B'], false, 40),
  142. tryRun('vulkaninfo', ['--summary'], false, 40)
  143. ])
  144. const parts = [
  145. `GPUs (host lspci):\n${gpuLines(lspci)}`,
  146. `NVIDIA driver (host):\n${nvidia}`,
  147. `eglinfo -B (as the engine sees it):\n${eglinfo}`,
  148. `glxinfo -B:\n${glxinfo}`,
  149. `vulkaninfo --summary:\n${vulkan}`
  150. ]
  151. if (isFlatpak()) {
  152. const runtimes = await tryRun('flatpak', ['list', '--runtime', '--columns=application,version,branch'], true, 400)
  153. const gl = runtimes.split('\n').filter((line) => /\.GL\b|\.GL\.|nvidia|Platform\s/i.test(line))
  154. parts.push(`Flatpak runtimes and GL extensions (host):\n${gl.join('\n') || runtimes}`)
  155. parts.push(`/.flatpak-info:\n${readText('/.flatpak-info', 2048)}`)
  156. }
  157. return parts.join('\n\n')
  158. }
  159. function wallpaperInfo(histories: EngineHistory[]): string {
  160. return histories
  161. .map((h) => {
  162. const project = readText(`${h.wallpaperPath}/project.json`, PROJECT_JSON_LIMIT)
  163. return `### ${h.screen}: ${h.wallpaperPath}\n\nproject.json:\n${project}`
  164. })
  165. .join('\n\n')
  166. }
  167. function crashedWallpapers(): string {
  168. const flagged = getAllWallpapers().filter((w) => w.compat && compatStatus(w.compat) !== 'ok')
  169. if (flagged.length === 0) return 'none'
  170. const shown = flagged
  171. .sort((a, b) => (b.compat?.lastCrash?.at ?? 0) - (a.compat?.lastCrash?.at ?? 0))
  172. .slice(0, CRASHED_LIMIT)
  173. const entries = shown.map((w) => {
  174. const crash = w.compat?.lastCrash
  175. const head = `### ${w.id} ${w.title} (${compatStatus(w.compat)}, ${w.type}, ${w.compat?.runtimeCrashes ?? 0} runtime crashes)`
  176. if (!crash) return head
  177. const when = new Date(crash.at).toISOString()
  178. return `${head}\n${crash.phase} crash on ${crash.screen} at ${when}\n${crash.log.join('\n')}`
  179. })
  180. const more = flagged.length > shown.length ? `\n\n(${flagged.length - shown.length} more flagged)` : ''
  181. return `${flagged.length} flagged of ${getAllWallpapers().length}\n\n${entries.join('\n\n')}${more}`
  182. }
  183. /**
  184. * Restarts what is playing with per-frame timings on, lets it run, then collects its output and
  185. * the machine's graphics setup into one text report. The wallpapers are restarted again afterwards.
  186. */
  187. async function runTarget(target: DiagnosticsTarget, seconds: number, notes: string[]): Promise<{ histories: EngineHistory[]; snapshot: string }> {
  188. const wallpaper = getWallpaper(target.wallpaperId)
  189. if (!wallpaper) throw new Error(`Wallpaper ${target.wallpaperId} is not in the library`)
  190. const library = getAllWallpapers()
  191. const before = getRunningInstances().find((i) => i.screen === target.screen)
  192. const previous = before && !before.split ? library.find((w) => w.localPath === before.wallpaperPath) : undefined
  193. const pausedPlaylists = getPlaybackStates().filter(
  194. (s) => s.isPlaying && (s.screen === target.screen || s.screen === '*' || target.screen === '*')
  195. )
  196. for (const state of pausedPlaylists) pausePlaylist(state.screen)
  197. const exits: EngineHistory[] = []
  198. const exit = { at: 0 }
  199. const stopListening = onLweExit((info) => {
  200. if (info.screen !== target.screen) return
  201. exit.at = Date.now()
  202. notes.push(`${info.screen}: the engine exited (${info.phase}${info.crashed ? ', crashed' : ''}): ${info.description}`)
  203. exits.push({ screen: info.screen, wallpaperPath: info.wallpaperPath, pid: 0, startedAt: 0, lines: info.log })
  204. })
  205. let histories: EngineHistory[] = []
  206. let snapshot = '(engine not running)'
  207. setDiagnosticStats(true)
  208. try {
  209. notes.push(`Launched "${wallpaper.title}" (${wallpaper.id}) on ${target.screen} for this run`)
  210. try {
  211. await applyWallpaperMeta(wallpaper, { screen: target.screen, forceFresh: true, dependencyPrompt: 'once' })
  212. } catch (err) {
  213. notes.push(`launch failed: ${(err as Error).message}`)
  214. }
  215. const deadline = Date.now() + seconds * 1000
  216. while (Date.now() < deadline && !(exit.at && Date.now() - exit.at > 1500)) {
  217. await new Promise((resolve) => setTimeout(resolve, 250))
  218. }
  219. histories = getEngineHistory().filter((h) => h.screen === target.screen)
  220. if (histories.length > 0) snapshot = await snapshotInstances()
  221. } finally {
  222. setDiagnosticStats(false)
  223. stopListening()
  224. try {
  225. if (previous) await applyWallpaperMeta(previous, { screen: target.screen, forceFresh: true })
  226. else await stopDisplay(target.screen)
  227. } catch (err) {
  228. notes.push(`could not restore the previous wallpaper: ${(err as Error).message}`)
  229. }
  230. for (const state of pausedPlaylists) resumePlaylist(state.screen)
  231. }
  232. return { histories: histories.length > 0 ? histories : exits, snapshot }
  233. }
  234. export async function collectDiagnostics(seconds = DEFAULT_SECONDS, target?: DiagnosticsTarget): Promise<string> {
  235. if (!target && getRunningInstances().length === 0) throw new NoEngineRunningError()
  236. let histories: EngineHistory[]
  237. let snapshot: string
  238. const notes: string[] = []
  239. if (target) {
  240. ;({ histories, snapshot } = await runTarget(target, seconds, notes))
  241. } else {
  242. setDiagnosticStats(true)
  243. try {
  244. notes.push(...(await restartPlaying()))
  245. await new Promise((resolve) => setTimeout(resolve, seconds * 1000))
  246. histories = getEngineHistory()
  247. snapshot = await snapshotInstances()
  248. } finally {
  249. setDiagnosticStats(false)
  250. notes.push(...(await restartPlaying().catch(() => ['could not restart the wallpapers after the run'])))
  251. }
  252. }
  253. const graphics = await graphicsInfo()
  254. const summary = summarize(histories)
  255. const report = [
  256. `# WE Manager diagnostics (${new Date().toISOString()}, ${seconds}s run)`,
  257. section('Summary', [...summary, ...notes].join('\n')),
  258. section('System', systemInfo()),
  259. section('Graphics', graphics),
  260. section('CPU use during the run', snapshot),
  261. section('Wallpapers', wallpaperInfo(histories)),
  262. section('Wallpapers marked as crashed', crashedWallpapers()),
  263. ...histories.map((h) =>
  264. section(`Engine output: ${h.screen}${h.pid > 0 ? ` (pid ${h.pid})` : ' (last lines before it exited)'}`, h.lines.join('\n') || '(nothing printed)')
  265. )
  266. ].join('')
  267. return pathRedactor()(report)
  268. }