graphics_GLBench: Use existing X session if possible (for factory)

The factory test relies on an X session. If we always restart a X to run
graphics_GLBench, factory test will be killed.

This CL helps GLBench to use existing X session, especially when running under
factory test environment.

BUG=chrome-os-partner:2890
TEST=(edit factory test list to enable graphics_GLbench)
     Run grahpics_GLBench in factory test, seeing the Green box in left-top
     corner; factory test is still running.

Change-Id: I976af5c69311e63c5e18ac6ccfd7b869a6b330f5
Reviewed-on: http://gerrit.chromium.org/gerrit/751
Reviewed-by: Nick Sanders <nsanders@chromium.org>
Reviewed-by: Hung-Te Lin <hungte@chromium.org>
Tested-by: Hung-Te Lin <hungte@chromium.org>
diff --git a/client/site_tests/graphics_GLBench/graphics_GLBench.py b/client/site_tests/graphics_GLBench/graphics_GLBench.py
index 3a40802..374a341 100644
--- a/client/site_tests/graphics_GLBench/graphics_GLBench.py
+++ b/client/site_tests/graphics_GLBench/graphics_GLBench.py
@@ -76,7 +76,7 @@
     outdir = self.outputdir
     options += ' -save -outdir=' + outdir
 
-    cmd = 'X :1 & sleep 1; DISPLAY=:1 %s %s; kill $!' % (exefile, options)
+    cmd = '%s %s' % (exefile, options)
 
     # If UI is running, we must stop it and restore later.
     need_restart_ui = False
@@ -86,6 +86,11 @@
     logging.info('initctl status ui returns: %s', status_output)
     need_restart_ui = status_output.startswith('ui start')
 
+    # If UI is just stopped or if there's no known X session, we have to start a
+    # new one. For factory test, it provides X (DISPLAY) so we can reuse it.
+    if need_restart_ui or (not os.getenv('DISPLAY')):
+        cmd = 'X :1 & sleep 1; DISPLAY=:1 %s; kill $!' % cmd
+
     if need_restart_ui:
       utils.system('initctl stop ui', ignore_status=True)