liveprops.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/bin/env python3
  2. """Checks that user property changes apply live: for every user property of every scene wallpaper,
  3. one render launches with the property already changed (--set-property) and one launches with the
  4. default and changes it through the control file on an early frame (LWE_HOTSWAP_AT_FRAME). Both
  5. screenshots should match. A third render with nothing changed tells whether the property shows on
  6. that frame at all.
  7. tools/regression/liveprops.py build/output/linux-wallpaperengine runs/live --gpu
  8. tools/regression/liveprops.py build/output/linux-wallpaperengine runs/live --gpu --force --ids 2937687740
  9. --force sets LWE_FORCE_LIVE_PROPERTIES, which applies every change live even where the engine would
  10. still reload, so it lists the uses that don't follow a change yet. Without it a change that needs a
  11. reload restarts the wallpaper and the frames differ for that reason, the log line says which way it
  12. went. Results go to <out>/results.json and a summary is printed.
  13. """
  14. import argparse
  15. import concurrent.futures
  16. import hashlib
  17. import json
  18. import os
  19. import signal
  20. import subprocess
  21. import sys
  22. import threading
  23. import time
  24. from pathlib import Path
  25. import regress
  26. SKIPPED_TYPES = {'file', 'directory', 'scenetexture', 'usershortcut', 'text', 'group'}
  27. def alternative (prop):
  28. """A value different from the property's default, as the control file / --set-property take it."""
  29. kind = str (prop.get ('type', '')).lower ()
  30. value = prop.get ('value')
  31. if kind == 'bool':
  32. return 'false' if value in (True, 1, 'true', '1') else 'true'
  33. if kind == 'slider':
  34. low, high = float (prop.get ('min', 0)), float (prop.get ('max', 100))
  35. current = float (value if value is not None else low)
  36. target = high if abs (current - high) > abs (current - low) else low
  37. if target == current:
  38. target = (low + high) / 2
  39. if not prop.get ('fraction', False):
  40. target = round (target)
  41. return f'{target:g}'
  42. if kind == 'combo':
  43. for option in prop.get ('options', []):
  44. if str (option.get ('value')) != str (value):
  45. return str (option.get ('value'))
  46. return None
  47. if kind == 'color':
  48. return '0 0 1' if str (value).split ()[:1] != ['0'] else '1 0 0'
  49. if kind == 'textinput':
  50. return 'LIVE PROPERTY TEST'
  51. return None
  52. def available_memory_gb ():
  53. with open ('/proc/meminfo') as f:
  54. for line in f:
  55. if line.startswith ('MemAvailable:'):
  56. return int (line.split ()[1]) / 1024 ** 2
  57. return 0.0
  58. def engine_processes (binary_name):
  59. """(pid, rss in GB, command line) of every running engine started from this binary."""
  60. found = []
  61. for pid in os.listdir ('/proc'):
  62. if not pid.isdigit ():
  63. continue
  64. try:
  65. with open (f'/proc/{pid}/cmdline', 'rb') as f:
  66. command = f.read ().split (b'\0')
  67. if not command or Path (command[0].decode (errors = 'replace')).name != binary_name:
  68. continue
  69. with open (f'/proc/{pid}/statm') as f:
  70. rss = int (f.read ().split ()[1]) * os.sysconf ('SC_PAGE_SIZE') / 1024 ** 3
  71. found.append ((int (pid), rss, b' '.join (command).decode (errors = 'replace')))
  72. except (OSError, ValueError, IndexError):
  73. continue
  74. return found
  75. def watchdog (binary_name, minimum_gb, log_path, stop):
  76. """Kills the biggest engine whenever the machine runs low on memory, a runaway render must not take the desktop
  77. down with it (this sandbox shares the host's memory). Every kill and every engine past 2GB is logged."""
  78. seen = set ()
  79. while not stop.is_set ():
  80. processes = engine_processes (binary_name)
  81. for pid, rss, command in processes:
  82. if rss > 2 and pid not in seen:
  83. seen.add (pid)
  84. with open (log_path, 'a') as log:
  85. log.write (f'{time.strftime ("%H:%M:%S")} big {rss:.1f}GB pid {pid}: {command}\n')
  86. if processes and available_memory_gb () < minimum_gb:
  87. pid, rss, command = max (processes, key = lambda p: p[1])
  88. try:
  89. os.kill (pid, signal.SIGKILL)
  90. except OSError:
  91. pass
  92. with open (log_path, 'a') as log:
  93. log.write (f'{time.strftime ("%H:%M:%S")} KILLED {rss:.1f}GB pid {pid}: {command}\n')
  94. stop.wait (0.5)
  95. def cases (workshop, ids):
  96. for folder in sorted (workshop.iterdir ()):
  97. if not folder.is_dir () or (ids and folder.name not in ids):
  98. continue
  99. project = regress.read_project (folder) or {}
  100. if str (project.get ('type', '')).lower () != 'scene':
  101. continue
  102. properties = project.get ('general', {}).get ('properties', {}) or {}
  103. for name, prop in properties.items ():
  104. if not isinstance (prop, dict) or str (prop.get ('type', '')).lower () in SKIPPED_TYPES:
  105. continue
  106. value = alternative (prop)
  107. if value is not None:
  108. yield folder, name, str (prop.get ('type')), value
  109. def main ():
  110. parser = argparse.ArgumentParser (description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
  111. parser.add_argument ('binary', type = Path)
  112. parser.add_argument ('out', type = Path)
  113. parser.add_argument ('--workshop', type = Path, default = regress.env_path ('LWE_WORKSHOP_DIR', regress.DEFAULT_WORKSHOP))
  114. parser.add_argument ('--assets', type = Path, default = regress.env_path ('LWE_ASSETS_DIR', regress.DEFAULT_ASSETS))
  115. parser.add_argument ('--ids', nargs = '*')
  116. parser.add_argument ('--gpu', nargs = '?', const = 'auto', metavar = 'RENDER_NODE')
  117. parser.add_argument ('--jobs', type = int, default = 4)
  118. parser.add_argument ('--memory-limit', type = float, default = 4, help = 'GB of data per engine (RLIMIT_DATA)')
  119. parser.add_argument ('--min-available', type = float, default = 6,
  120. help = 'GB of available memory below which the biggest engine is killed')
  121. parser.add_argument ('--frame', type = int, default = 20, help = 'frame to screenshot (default: 20)')
  122. parser.add_argument ('--change-frame', type = int, default = 0, help = 'frame the live change happens on')
  123. parser.add_argument ('--step', type = float, default = 0.1)
  124. parser.add_argument ('--clock', type = int, default = 1767268800)
  125. parser.add_argument ('--width', type = int, default = 960)
  126. parser.add_argument ('--height', type = int, default = 540)
  127. parser.add_argument ('--timeout', type = float, default = 120)
  128. parser.add_argument ('--threshold', type = int, default = 16)
  129. parser.add_argument ('--tolerance', type = float, default = 0.2, help = 'percent of changed pixels still a match')
  130. parser.add_argument ('--force', action = 'store_true', help = 'set LWE_FORCE_LIVE_PROPERTIES')
  131. args = parser.parse_args ()
  132. args.binary = args.binary.resolve ()
  133. args.out = args.out.resolve ()
  134. args.out.mkdir (parents = True, exist_ok = True)
  135. preload = regress.build_shims (args.out)
  136. todo = list (cases (args.workshop, set (args.ids or [])))
  137. stop_watchdog = threading.Event ()
  138. threading.Thread (
  139. target = watchdog, args = (args.binary.name, args.min_available, args.out / 'memory.log', stop_watchdog),
  140. daemon = True
  141. ).start ()
  142. # one bus for the run, dbus-run-session per render left engines unreaped
  143. bus = subprocess.Popen (['dbus-daemon', '--session', '--nofork', '--print-address', '--address',
  144. f'unix:path={args.out}/bus'], stdout = subprocess.PIPE, stdin = subprocess.DEVNULL, text = True)
  145. address = bus.stdout.readline ().strip ()
  146. def private_env ():
  147. return dict (regress.render_env (args, preload, None), DBUS_SESSION_BUS_ADDRESS = address)
  148. if not todo:
  149. sys.exit ('no user properties found')
  150. def base (folder):
  151. target = args.out / folder.name
  152. target.mkdir (parents = True, exist_ok = True)
  153. shot = target / 'default.png'
  154. if not shot.exists ():
  155. env = private_env ()
  156. regress.render_once (args, env, folder, shot, target / 'default.txt', [])
  157. return shot
  158. def job (case):
  159. folder, name, kind, value = case
  160. target = args.out / folder.name
  161. safe = ''.join (c if c.isalnum () else '_' for c in name)[:40] + '_' + hashlib.sha1 (name.encode ()).hexdigest ()[:8]
  162. env = private_env ()
  163. launched = target / f'{safe}.launch.png'
  164. live = target / f'{safe}.live.png'
  165. control = target / f'{safe}.control'
  166. control.write_text (f'property={name}={value}\n')
  167. regress.render_once (args, env, folder, launched, target / f'{safe}.launch.txt', [f'{name}={value}'])
  168. live_env = dict (env, LWE_HOTSWAP_AT_FRAME = str (args.change_frame))
  169. if args.force:
  170. live_env['LWE_FORCE_LIVE_PROPERTIES'] = '1'
  171. regress.render_once (
  172. args, live_env, folder, live, target / f'{safe}.live.txt', [], ['--control-file', str (control)]
  173. )
  174. log = (target / f'{safe}.live.txt').read_text (errors = 'replace') if (target / f'{safe}.live.txt').exists () else ''
  175. result = {'id': folder.name, 'property': name, 'type': kind, 'value': value,
  176. 'mode': 'live' if 'applied property' in log else ('reload' if 'Hotswapping' in log else 'none')}
  177. if not launched.exists () or not live.exists ():
  178. result['status'] = 'render failed'
  179. return result
  180. default = base (folder)
  181. result['effect'] = round (regress.changed_fraction (default, launched, args.threshold), 3) if default.exists () else None
  182. result['difference'] = round (regress.changed_fraction (launched, live, args.threshold), 3)
  183. result['status'] = 'match' if result['difference'] <= args.tolerance else 'DIFFERENT'
  184. if result['effect'] is not None and result['effect'] <= args.tolerance and result['status'] == 'match':
  185. result['status'] = 'no visible effect'
  186. return result
  187. # the default first, the other jobs compare against it
  188. with concurrent.futures.ThreadPoolExecutor (args.jobs) as pool:
  189. list (pool.map (base, sorted ({case[0] for case in todo})))
  190. results = []
  191. with concurrent.futures.ThreadPoolExecutor (args.jobs) as pool:
  192. for done, result in enumerate (pool.map (job, todo), 1):
  193. results.append (result)
  194. print (f'[{done}/{len (todo)}] {result["id"]} {result["property"]} ({result["type"]}={result["value"]}) '
  195. f'{result["mode"]} {result["status"]} effect={result.get ("effect")} diff={result.get ("difference")}',
  196. flush = True)
  197. bus.terminate ()
  198. stop_watchdog.set ()
  199. (args.out / 'results.json').write_text (json.dumps (results, ensure_ascii = False, indent = 1))
  200. different = [r for r in results if r['status'] == 'DIFFERENT']
  201. print (f'\n{len (results)} properties, {len (different)} different:')
  202. for r in different:
  203. print (f' {r["id"]} {r["property"]} ({r["type"]}) effect={r.get ("effect")} diff={r["difference"]} mode={r["mode"]}')
  204. if __name__ == '__main__':
  205. main ()