xvfb.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Runs tests with Xvfb and Openbox or Weston on Linux and normally on other
  6. platforms."""
  7. from __future__ import print_function
  8. import copy
  9. import os
  10. import os.path
  11. import random
  12. import re
  13. import signal
  14. import subprocess
  15. import sys
  16. import threading
  17. import time
  18. import psutil
  19. import test_env
  20. class _XvfbProcessError(Exception):
  21. """Exception raised when Xvfb cannot start."""
  22. pass
  23. class _WestonProcessError(Exception):
  24. """Exception raised when Weston cannot start."""
  25. pass
  26. def kill(proc, name, timeout_in_seconds=10):
  27. """Tries to kill |proc| gracefully with a timeout for each signal."""
  28. if not proc:
  29. return
  30. proc.terminate()
  31. thread = threading.Thread(target=proc.wait)
  32. thread.start()
  33. thread.join(timeout_in_seconds)
  34. if thread.is_alive():
  35. print('%s running after SIGTERM, trying SIGKILL.\n' % name, file=sys.stderr)
  36. proc.kill()
  37. thread.join(timeout_in_seconds)
  38. if thread.is_alive():
  39. print('%s running after SIGTERM and SIGKILL; good luck!\n' % name,
  40. file=sys.stderr)
  41. def launch_dbus(env):
  42. """Starts a DBus session.
  43. Works around a bug in GLib where it performs operations which aren't
  44. async-signal-safe (in particular, memory allocations) between fork and exec
  45. when it spawns subprocesses. This causes threads inside Chrome's browser and
  46. utility processes to get stuck, and this harness to hang waiting for those
  47. processes, which will never terminate. This doesn't happen on users'
  48. machines, because they have an active desktop session and the
  49. DBUS_SESSION_BUS_ADDRESS environment variable set, but it can happen on
  50. headless environments. This is fixed by glib commit [1], but this workaround
  51. will be necessary until the fix rolls into Chromium's CI.
  52. [1] f2917459f745bebf931bccd5cc2c33aa81ef4d12
  53. Modifies the passed in environment with at least DBUS_SESSION_BUS_ADDRESS and
  54. DBUS_SESSION_BUS_PID set.
  55. Returns the pid of the dbus-daemon if started, or None otherwise.
  56. """
  57. if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
  58. return
  59. try:
  60. dbus_output = subprocess.check_output(
  61. ['dbus-launch'], env=env).decode('utf-8').split('\n')
  62. for line in dbus_output:
  63. m = re.match(r'([^=]+)\=(.+)', line)
  64. if m:
  65. env[m.group(1)] = m.group(2)
  66. return int(env['DBUS_SESSION_BUS_PID'])
  67. except (subprocess.CalledProcessError, OSError, KeyError, ValueError) as e:
  68. print('Exception while running dbus_launch: %s' % e)
  69. # TODO(crbug.com/949194): Encourage setting flags to False.
  70. def run_executable(
  71. cmd, env, stdoutfile=None, use_openbox=True, use_xcompmgr=True):
  72. """Runs an executable within Weston or Xvfb on Linux or normally on other
  73. platforms.
  74. The method sets SIGUSR1 handler for Xvfb to return SIGUSR1
  75. when it is ready for connections.
  76. https://www.x.org/archive/X11R7.5/doc/man/man1/Xserver.1.html under Signals.
  77. Args:
  78. cmd: Command to be executed.
  79. env: A copy of environment variables. "DISPLAY" and will be set if Xvfb is
  80. used. "WAYLAND_DISPLAY" will be set if Weston is used.
  81. stdoutfile: If provided, symbolization via script is disabled and stdout
  82. is written to this file as well as to stdout.
  83. use_openbox: A flag to use openbox process.
  84. Some ChromeOS tests need a window manager.
  85. use_xcompmgr: A flag to use xcompmgr process.
  86. Some tests need a compositing wm to make use of transparent visuals.
  87. Returns:
  88. the exit code of the specified commandline, or 1 on failure.
  89. """
  90. # It might seem counterintuitive to support a --no-xvfb flag in a script
  91. # whose only job is to start xvfb, but doing so allows us to consolidate
  92. # the logic in the layers of buildbot scripts so that we *always* use
  93. # xvfb by default and don't have to worry about the distinction, it
  94. # can remain solely under the control of the test invocation itself.
  95. use_xvfb = True
  96. if '--no-xvfb' in cmd:
  97. use_xvfb = False
  98. cmd.remove('--no-xvfb')
  99. # Tests that run on Linux platforms with Ozone/Wayland backend require
  100. # a Weston instance. However, it is also required to disable xvfb so
  101. # that Weston can run in a pure headless environment.
  102. use_weston = False
  103. if '--use-weston' in cmd:
  104. if use_xvfb:
  105. print('Unable to use Weston with xvfb.\n', file=sys.stderr)
  106. return 1
  107. use_weston = True
  108. cmd.remove('--use-weston')
  109. if sys.platform.startswith('linux') and use_xvfb:
  110. return _run_with_xvfb(cmd, env, stdoutfile, use_openbox, use_xcompmgr)
  111. elif use_weston:
  112. return _run_with_weston(cmd, env, stdoutfile)
  113. else:
  114. return test_env.run_executable(cmd, env, stdoutfile)
  115. def _run_with_xvfb(cmd, env, stdoutfile, use_openbox, use_xcompmgr):
  116. openbox_proc = None
  117. openbox_ready = MutableBoolean()
  118. def set_openbox_ready(*_):
  119. openbox_ready.setvalue(True)
  120. xcompmgr_proc = None
  121. xvfb_proc = None
  122. xvfb_ready = MutableBoolean()
  123. def set_xvfb_ready(*_):
  124. xvfb_ready.setvalue(True)
  125. dbus_pid = None
  126. try:
  127. signal.signal(signal.SIGTERM, raise_xvfb_error)
  128. signal.signal(signal.SIGINT, raise_xvfb_error)
  129. # Before [1], the maximum number of X11 clients was 256. After, the default
  130. # limit is 256 with a configurable maximum of 512. On systems with a large
  131. # number of CPUs, the old limit of 256 may be hit for certain test suites
  132. # [2] [3], so we set the limit to 512 when possible. This flag is not
  133. # available on Ubuntu 16.04 or 18.04, so a feature check is required. Xvfb
  134. # does not have a '-version' option, so checking the '-help' output is
  135. # required.
  136. #
  137. # [1] d206c240c0b85c4da44f073d6e9a692afb6b96d2
  138. # [2] https://crbug.com/1187948
  139. # [3] https://crbug.com/1120107
  140. xvfb_help = subprocess.check_output(
  141. ['Xvfb', '-help'], stderr=subprocess.STDOUT).decode('utf8')
  142. # Due to race condition for display number, Xvfb might fail to run.
  143. # If it does fail, try again up to 10 times, similarly to xvfb-run.
  144. for _ in range(10):
  145. xvfb_ready.setvalue(False)
  146. display = find_display()
  147. xvfb_cmd = ['Xvfb', display, '-screen', '0', '1280x800x24', '-ac',
  148. '-nolisten', 'tcp', '-dpi', '96', '+extension', 'RANDR']
  149. if '-maxclients' in xvfb_help:
  150. xvfb_cmd += ['-maxclients', '512']
  151. # Sets SIGUSR1 to ignore for Xvfb to signal current process
  152. # when it is ready. Due to race condition, USR1 signal could be sent
  153. # before the process resets the signal handler, we cannot rely on
  154. # signal handler to change on time.
  155. signal.signal(signal.SIGUSR1, signal.SIG_IGN)
  156. xvfb_proc = subprocess.Popen(xvfb_cmd, stderr=subprocess.STDOUT, env=env)
  157. signal.signal(signal.SIGUSR1, set_xvfb_ready)
  158. for _ in range(10):
  159. time.sleep(.1) # gives Xvfb time to start or fail.
  160. if xvfb_ready.getvalue() or xvfb_proc.poll() is not None:
  161. break # xvfb sent ready signal, or already failed and stopped.
  162. if xvfb_proc.poll() is None:
  163. break # xvfb is running, can proceed.
  164. if xvfb_proc.poll() is not None:
  165. raise _XvfbProcessError('Failed to start after 10 tries')
  166. env['DISPLAY'] = display
  167. # Set dummy variable for scripts.
  168. env['XVFB_DISPLAY'] = display
  169. dbus_pid = launch_dbus(env)
  170. if use_openbox:
  171. # Openbox will send a SIGUSR1 signal to the current process notifying the
  172. # script it has started up.
  173. current_proc_id = os.getpid()
  174. # The CMD that is passed via the --startup flag.
  175. openbox_startup_cmd = 'kill --signal SIGUSR1 %s' % str(current_proc_id)
  176. # Setup the signal handlers before starting the openbox instance.
  177. signal.signal(signal.SIGUSR1, signal.SIG_IGN)
  178. signal.signal(signal.SIGUSR1, set_openbox_ready)
  179. openbox_proc = subprocess.Popen(
  180. ['openbox', '--sm-disable', '--startup',
  181. openbox_startup_cmd], stderr=subprocess.STDOUT, env=env)
  182. for _ in range(10):
  183. time.sleep(.1) # gives Openbox time to start or fail.
  184. if openbox_ready.getvalue() or openbox_proc.poll() is not None:
  185. break # openbox sent ready signal, or failed and stopped.
  186. if openbox_proc.poll() is not None:
  187. raise _XvfbProcessError('Failed to start OpenBox.')
  188. if use_xcompmgr:
  189. xcompmgr_proc = subprocess.Popen(
  190. 'xcompmgr', stderr=subprocess.STDOUT, env=env)
  191. return test_env.run_executable(cmd, env, stdoutfile)
  192. except OSError as e:
  193. print('Failed to start Xvfb or Openbox: %s\n' % str(e), file=sys.stderr)
  194. return 1
  195. except _XvfbProcessError as e:
  196. print('Xvfb fail: %s\n' % str(e), file=sys.stderr)
  197. return 1
  198. finally:
  199. kill(openbox_proc, 'openbox')
  200. kill(xcompmgr_proc, 'xcompmgr')
  201. kill(xvfb_proc, 'Xvfb')
  202. # dbus-daemon is not a subprocess, so we can't SIGTERM+waitpid() on it.
  203. # To ensure it exits, use SIGKILL which should be safe since all other
  204. # processes that it would have been servicing have exited.
  205. if dbus_pid:
  206. os.kill(dbus_pid, signal.SIGKILL)
  207. # TODO(https://crbug.com/1060466): Write tests.
  208. def _run_with_weston(cmd, env, stdoutfile):
  209. weston_proc = None
  210. try:
  211. signal.signal(signal.SIGTERM, raise_weston_error)
  212. signal.signal(signal.SIGINT, raise_weston_error)
  213. dbus_pid = launch_dbus(env)
  214. # The bundled weston (//third_party/weston) is used by Linux Ozone Wayland
  215. # CI and CQ testers and compiled by //ui/ozone/platform/wayland whenever
  216. # there is a dependency on the Ozone/Wayland and use_bundled_weston is set
  217. # in gn args. However, some tests do not require Wayland or do not use
  218. # //ui/ozone at all, but still have --use-weston flag set by the
  219. # OZONE_WAYLAND variant (see //testing/buildbot/variants.pyl). This results
  220. # in failures and those tests cannot be run because of the exception that
  221. # informs about missing weston binary. Thus, to overcome the issue before
  222. # a better solution is found, add a check for the "weston" binary here and
  223. # run tests without Wayland compositor if the weston binary is not found.
  224. # TODO(https://1178788): find a better solution.
  225. if not os.path.isfile("./weston"):
  226. print('Weston is not available. Starting without Wayland compositor')
  227. return test_env.run_executable(cmd, env, stdoutfile)
  228. # Set $XDG_RUNTIME_DIR if it is not set.
  229. _set_xdg_runtime_dir(env)
  230. # Weston is compiled along with the Ozone/Wayland platform, and is
  231. # fetched as data deps. Thus, run it from the current directory.
  232. #
  233. # Weston is used with the following flags:
  234. # 1) --backend=headless-backend.so - runs Weston in a headless mode
  235. # that does not require a real GPU card.
  236. # 2) --idle-time=0 - disables idle timeout, which prevents Weston
  237. # to enter idle state. Otherwise, Weston stops to send frame callbacks,
  238. # and tests start to time out (this typically happens after 300 seconds -
  239. # the default time after which Weston enters the idle state).
  240. # 3) --width && --height set size of a virtual display: we need to set
  241. # an adequate size so that tests can have more room for managing size
  242. # of windows.
  243. # 4) --use-gl - Runs Weston using hardware acceleration instead of
  244. # SwiftShader.
  245. weston_cmd = ['./weston', '--backend=headless-backend.so', '--idle-time=0',
  246. '--width=1024', '--height=768', '--modules=test-plugin.so']
  247. if '--weston-use-gl' in cmd:
  248. weston_cmd.append('--use-gl')
  249. cmd.remove('--weston-use-gl')
  250. if '--weston-debug-logging' in cmd:
  251. cmd.remove('--weston-debug-logging')
  252. env = copy.deepcopy(env)
  253. env['WAYLAND_DEBUG'] = '1'
  254. weston_proc_display = None
  255. for _ in range(10):
  256. weston_proc = subprocess.Popen(
  257. weston_cmd,
  258. stderr=subprocess.STDOUT, env=env)
  259. # Get the $WAYLAND_DISPLAY set by Weston and pass it to the test launcher.
  260. # Please note that this env variable is local for the process. That's the
  261. # reason we have to read it from Weston separately.
  262. weston_proc_display = _get_display_from_weston(weston_proc.pid)
  263. if weston_proc_display is not None:
  264. break # Weston could launch and we found the display.
  265. # If we couldn't find the display after 10 tries, raise an exception.
  266. if weston_proc_display is None:
  267. raise _WestonProcessError('Failed to start Weston.')
  268. env['WAYLAND_DISPLAY'] = weston_proc_display
  269. return test_env.run_executable(cmd, env, stdoutfile)
  270. except OSError as e:
  271. print('Failed to start Weston: %s\n' % str(e), file=sys.stderr)
  272. return 1
  273. except _WestonProcessError as e:
  274. print('Weston fail: %s\n' % str(e), file=sys.stderr)
  275. return 1
  276. finally:
  277. kill(weston_proc, 'weston')
  278. # dbus-daemon is not a subprocess, so we can't SIGTERM+waitpid() on it.
  279. # To ensure it exits, use SIGKILL which should be safe since all other
  280. # processes that it would have been servicing have exited.
  281. if dbus_pid:
  282. os.kill(dbus_pid, signal.SIGKILL)
  283. def _get_display_from_weston(weston_proc_pid):
  284. """Retrieves $WAYLAND_DISPLAY set by Weston.
  285. Searches for the child "weston-desktop-shell" process, takes its
  286. environmental variables, and returns $WAYLAND_DISPLAY variable set
  287. by that process. If the variable is not set, tries up to 10 times
  288. and then gives up.
  289. Args:
  290. weston_proc_pid: The process of id of the main Weston process.
  291. Returns:
  292. the display set by Wayland, which clients can use to connect to.
  293. TODO(https://crbug.com/1060469): This is potentially error prone
  294. function. See the bug for further details.
  295. """
  296. # Try 100 times as it is not known when Weston spawn child desktop shell
  297. # process. The most seen so far is ~50 checks/~2.5 seconds, but startup
  298. # is usually almost instantaneous.
  299. for _ in range(100):
  300. # gives weston time to start or fail.
  301. time.sleep(.05)
  302. # Take the parent process.
  303. parent = psutil.Process(weston_proc_pid)
  304. if parent is None:
  305. break # The process is not found. Give up.
  306. # Traverse through all the children processes and find the
  307. # "weston-desktop-shell" process that sets local to process env variables
  308. # including the $WAYLAND_DISPLAY.
  309. children = parent.children(recursive=True)
  310. for process in children:
  311. if process.name() == "weston-desktop-shell":
  312. weston_proc_display = process.environ().get('WAYLAND_DISPLAY')
  313. # If display is set, Weston could start successfully and we can use
  314. # that display for Wayland connection in Chromium.
  315. if weston_proc_display is not None:
  316. return weston_proc_display
  317. return None
  318. class MutableBoolean(object):
  319. """Simple mutable boolean class. Used to be mutated inside an handler."""
  320. def __init__(self):
  321. self._val = False
  322. def setvalue(self, val):
  323. assert isinstance(val, bool)
  324. self._val = val
  325. def getvalue(self):
  326. return self._val
  327. def raise_xvfb_error(*_):
  328. raise _XvfbProcessError('Terminated')
  329. def raise_weston_error(*_):
  330. raise _WestonProcessError('Terminated')
  331. def find_display():
  332. """Iterates through X-lock files to find an available display number.
  333. The lower bound follows xvfb-run standard at 99, and the upper bound
  334. is set to 119.
  335. Returns:
  336. A string of a random available display number for Xvfb ':{99-119}'.
  337. Raises:
  338. _XvfbProcessError: Raised when displays 99 through 119 are unavailable.
  339. """
  340. available_displays = [
  341. d for d in range(99, 120)
  342. if not os.path.isfile('/tmp/.X{}-lock'.format(d))
  343. ]
  344. if available_displays:
  345. return ':{}'.format(random.choice(available_displays))
  346. raise _XvfbProcessError('Failed to find display number')
  347. def _set_xdg_runtime_dir(env):
  348. """Sets the $XDG_RUNTIME_DIR variable if it hasn't been set before."""
  349. runtime_dir = env.get('XDG_RUNTIME_DIR')
  350. if not runtime_dir:
  351. runtime_dir = '/tmp/xdg-tmp-dir/'
  352. if not os.path.exists(runtime_dir):
  353. os.makedirs(runtime_dir, 0o700)
  354. env['XDG_RUNTIME_DIR'] = runtime_dir
  355. def main():
  356. usage = 'Usage: xvfb.py [command [--no-xvfb or --use-weston] args...]'
  357. if len(sys.argv) < 2:
  358. print(usage + '\n', file=sys.stderr)
  359. return 2
  360. # If the user still thinks the first argument is the execution directory then
  361. # print a friendly error message and quit.
  362. if os.path.isdir(sys.argv[1]):
  363. print('Invalid command: \"%s\" is a directory\n' % sys.argv[1],
  364. file=sys.stderr)
  365. print(usage + '\n', file=sys.stderr)
  366. return 3
  367. return run_executable(sys.argv[1:], os.environ.copy())
  368. if __name__ == '__main__':
  369. sys.exit(main())