• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6import os
7
8from autotest_lib.client.bin import test, utils
9from autotest_lib.client.common_lib import error
10from autotest_lib.client.cros import perf
11from autotest_lib.client.cros import service_stopper
12from autotest_lib.client.cros.graphics import graphics_utils
13
14
15class graphics_GLBench(graphics_utils.GraphicsTest):
16  """Run glbench, a benchmark that times graphics intensive activities."""
17  version = 1
18  preserve_srcdir = True
19  _services = None
20
21  # Good images.
22  reference_images_file = 'deps/glbench/glbench_reference_images.txt'
23  # Images that are bad but for which the bug has not been fixed yet.
24  knownbad_images_file = 'deps/glbench/glbench_knownbad_images.txt'
25  # Images that are bad and for which a fix has been submitted.
26  fixedbad_images_file = 'deps/glbench/glbench_fixedbad_images.txt'
27
28  # These tests do not draw anything, they can only be used to check
29  # performance.
30  no_checksum_tests = set([
31      'compositing_no_fill',
32      'pixel_read',
33      'texture_reuse_luminance_teximage2d',
34      'texture_reuse_luminance_texsubimage2d',
35      'texture_reuse_rgba_teximage2d',
36      'texture_reuse_rgba_texsubimage2d',
37      'context_glsimple',
38      'swap_glsimple',
39  ])
40
41  blacklist = ''
42
43  unit_higher_is_better = {
44      'mpixels_sec': True,
45      'mtexel_sec': True,
46      'mtri_sec': True,
47      'mvtx_sec': True,
48      'us': False,
49      '1280x768_fps': True
50  }
51
52  def setup(self):
53    self.job.setup_dep(['glbench'])
54
55  def initialize(self):
56    super(graphics_GLBench, self).initialize()
57    # If UI is running, we must stop it and restore later.
58    self._services = service_stopper.ServiceStopper(['ui'])
59    self._services.stop_services()
60
61  def cleanup(self):
62    if self._services:
63      self._services.restore_services()
64    super(graphics_GLBench, self).cleanup()
65
66  def report_temperature(self, keyname):
67    """Report current max observed temperature with given keyname.
68
69    @param keyname: key to be used when reporting perf value.
70    """
71    temperature = utils.get_temperature_input_max()
72    logging.info('%s = %f degree Celsius', keyname, temperature)
73    self.output_perf_value(
74        description=keyname,
75        value=temperature,
76        units='Celsius',
77        higher_is_better=False)
78
79  def report_temperature_critical(self, keyname):
80    """Report temperature at which we will see throttling with given keyname.
81
82    @param keyname: key to be used when reporting perf value.
83    """
84    temperature = utils.get_temperature_critical()
85    logging.info('%s = %f degree Celsius', keyname, temperature)
86    self.output_perf_value(
87        description=keyname,
88        value=temperature,
89        units='Celsius',
90        higher_is_better=False)
91
92  def is_no_checksum_test(self, testname):
93    """Check if given test requires no screenshot checksum.
94
95    @param testname: name of test to check.
96    """
97    for prefix in self.no_checksum_tests:
98      if testname.startswith(prefix):
99        return True
100    return False
101
102  def load_imagenames(self, filename):
103    """Loads text file with MD5 file names.
104
105    @param filename: name of file to load.
106    """
107    imagenames = os.path.join(self.autodir, filename)
108    with open(imagenames, 'r') as f:
109      imagenames = f.read()
110      return imagenames
111
112  @graphics_utils.GraphicsTest.failure_report_decorator('graphics_GLBench')
113  def run_once(self, options='', hasty=False):
114    dep = 'glbench'
115    dep_dir = os.path.join(self.autodir, 'deps', dep)
116    self.job.install_pkg(dep, 'dep', dep_dir)
117
118    options += self.blacklist
119
120    # Run the test, saving is optional and helps with debugging
121    # and reference image management. If unknown images are
122    # encountered one can take them from the outdir and copy
123    # them (after verification) into the reference image dir.
124    exefile = os.path.join(self.autodir, 'deps/glbench/glbench')
125    outdir = self.outputdir
126    options += ' -save -outdir=' + outdir
127    # Using the -hasty option we run only a subset of tests without waiting
128    # for thermals to normalize. Test should complete in 15-20 seconds.
129    if hasty:
130      options += ' -hasty'
131
132    cmd = '%s %s' % (exefile, options)
133    summary = None
134    try:
135      if hasty:
136        # On BVT the test will not monitor thermals so we will not verify its
137        # correct status using PerfControl
138        summary = utils.run(cmd,
139                            stderr_is_expected=False,
140                            stdout_tee=utils.TEE_TO_LOGS,
141                            stderr_tee=utils.TEE_TO_LOGS).stdout
142      else:
143        self.report_temperature_critical('temperature_critical')
144        self.report_temperature('temperature_1_start')
145        # Wrap the test run inside of a PerfControl instance to make machine
146        # behavior more consistent.
147        with perf.PerfControl() as pc:
148          if not pc.verify_is_valid():
149            raise error.TestFail('Failed: %s' % pc.get_error_reason())
150          self.report_temperature('temperature_2_before_test')
151
152          # Run the test. If it gets the CPU too hot pc should notice.
153          summary = utils.run(cmd,
154                              stderr_is_expected=False,
155                              stdout_tee=utils.TEE_TO_LOGS,
156                              stderr_tee=utils.TEE_TO_LOGS).stdout
157          if not pc.verify_is_valid():
158            raise error.TestFail('Failed: %s' % pc.get_error_reason())
159    except error.CmdError:
160      raise error.TestFail('Failed: CmdError running %s' % cmd)
161    except error.CmdTimeoutError:
162      raise error.TestFail('Failed: CmdTimeout running %s' % cmd)
163
164    # Write a copy of stdout to help debug failures.
165    results_path = os.path.join(self.outputdir, 'summary.txt')
166    f = open(results_path, 'w+')
167    f.write('# ---------------------------------------------------\n')
168    f.write('# [' + cmd + ']\n')
169    f.write(summary)
170    f.write('\n# -------------------------------------------------\n')
171    f.write('# [graphics_GLBench.py postprocessing]\n')
172
173    # Analyze the output. Sample:
174    ## board_id: NVIDIA Corporation - Quadro FX 380/PCI/SSE2
175    ## Running: ../glbench -save -outdir=img
176    #swap_swap = 221.36 us [swap_swap.pixmd5-20dbc...f9c700d2f.png]
177    results = summary.splitlines()
178    if not results:
179      f.close()
180      raise error.TestFail('Failed: No output from test. Check /tmp/' +
181                           'test_that_latest/graphics_GLBench/summary.txt' +
182                           ' for details.')
183
184    # The good images, the silenced and the zombie/recurring failures.
185    reference_imagenames = self.load_imagenames(self.reference_images_file)
186    knownbad_imagenames = self.load_imagenames(self.knownbad_images_file)
187    fixedbad_imagenames = self.load_imagenames(self.fixedbad_images_file)
188
189    # Check if we saw GLBench end as expected (without crashing).
190    test_ended_normal = False
191    for line in results:
192      if line.strip().startswith('@TEST_END'):
193        test_ended_normal = True
194
195    # Analyze individual test results in summary.
196    # TODO(pwang): Raise TestFail if an error is detected during glbench.
197    keyvals = {}
198    failed_tests = {}
199    for line in results:
200      if not line.strip().startswith('@RESULT: '):
201        continue
202      keyval, remainder = line[9:].split('[')
203      key, val = keyval.split('=')
204      testname = key.strip()
205      score, unit = val.split()
206      testrating = float(score)
207      imagefile = remainder.split(']')[0]
208
209      higher = self.unit_higher_is_better.get(unit)
210      if higher is None:
211        raise error.TestFail('Failed: Unknown test unit "%s" for %s' %
212                             (unit, testname))
213
214      if not hasty:
215        # Prepend unit to test name to maintain backwards compatibility with
216        # existing per data.
217        perf_value_name = '%s_%s' % (unit, testname)
218        self.output_perf_value(
219            description=perf_value_name,
220            value=testrating,
221            units=unit,
222            higher_is_better=higher,
223            graph=perf_value_name)
224        # Add extra value to the graph distinguishing different boards.
225        variant = utils.get_board_with_frequency_and_memory()
226        desc = '%s-%s' % (perf_value_name, variant)
227        self.output_perf_value(
228            description=desc,
229            value=testrating,
230            units=unit,
231            higher_is_better=higher,
232            graph=perf_value_name)
233
234      # Classify result image.
235      if testrating == -1.0:
236        # Tests that generate GL Errors.
237        glerror = imagefile.split('=')[1]
238        f.write('# GLError ' + glerror + ' during test (perf set to -3.0)\n')
239        keyvals[testname] = -3.0
240        failed_tests[testname] = 'GLError'
241      elif testrating == 0.0:
242        # Tests for which glbench does not generate a meaningful perf score.
243        f.write('# No score for test\n')
244        keyvals[testname] = 0.0
245      elif imagefile in fixedbad_imagenames:
246        # We know the image looked bad at some point in time but we thought
247        # it was fixed. Throw an exception as a reminder.
248        keyvals[testname] = -2.0
249        f.write('# fixedbad [' + imagefile + '] (setting perf as -2.0)\n')
250        failed_tests[testname] = imagefile
251      elif imagefile in knownbad_imagenames:
252        # We have triaged the failure and have filed a tracking bug.
253        # Don't throw an exception and remind there is a problem.
254        keyvals[testname] = -1.0
255        f.write('# knownbad [' + imagefile + '] (setting perf as -1.0)\n')
256        # This failure is whitelisted so don't add to failed_tests.
257      elif imagefile in reference_imagenames:
258        # Known good reference images (default).
259        keyvals[testname] = testrating
260      elif imagefile == 'none':
261        # Tests that do not write images can't fail because of them.
262        keyvals[testname] = testrating
263      elif self.is_no_checksum_test(testname):
264        # TODO(ihf): these really should not write any images
265        keyvals[testname] = testrating
266      else:
267        # Completely unknown images. Raise a failure.
268        keyvals[testname] = -2.0
269        failed_tests[testname] = imagefile
270        f.write('# unknown [' + imagefile + '] (setting perf as -2.0)\n')
271    f.close()
272    if not hasty:
273      self.report_temperature('temperature_3_after_test')
274      self.write_perf_keyval(keyvals)
275
276    # Raise exception if images don't match.
277    if failed_tests:
278      logging.info('Some images are not matching their reference in %s.',
279                   self.reference_images_file)
280      logging.info('Please verify that the output images are correct '
281                   'and if so copy them to the reference directory.')
282      raise error.TestFail('Failed: Some images are not matching their '
283                           'references. Check /tmp/'
284                           'test_that_latest/graphics_GLBench/summary.txt'
285                           ' for details.')
286
287    if not test_ended_normal:
288      raise error.TestFail(
289          'Failed: No end marker. Presumed crash/missing images.')
290