suite_runner.py revision 9198db666212c457d231f2db6dd534d25f9bbc67
1# Copyright (c) 2013~2015 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"""SuiteRunner defines the interface from crosperf to test script."""
5
6from __future__ import print_function
7
8import os
9import time
10import shlex
11
12from cros_utils import command_executer
13import test_flag
14
15TEST_THAT_PATH = '/usr/bin/test_that'
16CHROME_MOUNT_DIR = '/tmp/chrome_root'
17
18
19def GetProfilerArgs(profiler_args):
20  # Remove "--" from in front of profiler args.
21  args_list = shlex.split(profiler_args)
22  new_list = []
23  for arg in args_list:
24    if arg[0:2] == '--':
25      arg = arg[2:]
26    new_list.append(arg)
27  args_list = new_list
28
29  # Remove "perf_options=" from middle of profiler args.
30  new_list = []
31  for arg in args_list:
32    idx = arg.find('perf_options=')
33    if idx != -1:
34      prefix = arg[0:idx]
35      suffix = arg[idx + len('perf_options=') + 1:-1]
36      new_arg = prefix + "'" + suffix + "'"
37      new_list.append(new_arg)
38    else:
39      new_list.append(arg)
40  args_list = new_list
41
42  return ' '.join(args_list)
43
44
45class SuiteRunner(object):
46  """This defines the interface from crosperf to test script."""
47
48  def __init__(self,
49               logger_to_use=None,
50               log_level='verbose',
51               cmd_exec=None,
52               cmd_term=None):
53    self._logger = logger_to_use
54    self.log_level = log_level
55    self._ce = cmd_exec or command_executer.GetCommandExecuter(
56        self._logger,
57        log_level=self.log_level)
58    self._ct = cmd_term or command_executer.CommandTerminator()
59
60  def Run(self, machine, label, benchmark, test_args, profiler_args):
61    for i in range(0, benchmark.retries + 1):
62      self.DecreaseWaitTime(machine, label.chromeos_root)
63      self.PinGovernorExecutionFrequencies(machine, label.chromeos_root)
64      if benchmark.suite == 'telemetry':
65        ret_tup = self.Telemetry_Run(machine, label, benchmark, profiler_args)
66      elif benchmark.suite == 'telemetry_Crosperf':
67        ret_tup = self.Telemetry_Crosperf_Run(machine, label, benchmark,
68                                              test_args, profiler_args)
69      else:
70        ret_tup = self.Test_That_Run(machine, label, benchmark, test_args,
71                                     profiler_args)
72      if ret_tup[0] != 0:
73        self._logger.LogOutput('benchmark %s failed. Retries left: %s' %
74                               (benchmark.name, benchmark.retries - i))
75      elif i > 0:
76        self._logger.LogOutput('benchmark %s succeded after %s retries' %
77                               (benchmark.name, i))
78        break
79      else:
80        self._logger.LogOutput('benchmark %s succeded on first try' %
81                               benchmark.name)
82        break
83    return ret_tup
84
85  def GetHighestStaticFrequency(self, machine_name, chromeos_root):
86    """Gets the highest static frequency for the specified machine."""
87    get_avail_freqs = ('cd /sys/devices/system/cpu/cpu0/cpufreq/; '
88                       'if [[ -e scaling_available_frequencies ]]; then '
89                       '  cat scaling_available_frequencies; '
90                       'else '
91                       '  cat scaling_max_freq ; '
92                       'fi')
93    ret, freqs_str, _ = self._ce.CrosRunCommandWOutput(
94        get_avail_freqs,
95        machine=machine_name,
96        chromeos_root=chromeos_root)
97    self._logger.LogFatalIf(ret, 'Could not get available frequencies '
98                            'from machine: %s' % machine_name)
99    freqs = freqs_str.split()
100    # We need to make sure that the frequencies are sorted in decreasing
101    # order
102    freqs.sort(key=int, reverse=True)
103
104    ## When there is no scaling_available_frequencies file,
105    ## we have only 1 choice.
106    if len(freqs) == 1:
107      return freqs[0]
108    # The dynamic frequency ends with a "1000". So, ignore it if found.
109    if freqs[0].endswith('1000'):
110      return freqs[1]
111    else:
112      return freqs[0]
113
114  def PinGovernorExecutionFrequencies(self, machine_name, chromeos_root):
115    """Set min and max frequencies to max static frequency."""
116    highest_freq = self.GetHighestStaticFrequency(machine_name, chromeos_root)
117    BASH_FOR = 'for f in {list}; do {body}; done'
118    CPUFREQ_DIRS = '/sys/devices/system/cpu/cpu*/cpufreq/'
119    change_max_freq = BASH_FOR.format(list=CPUFREQ_DIRS + 'scaling_max_freq',
120                                      body='echo %s > $f' % highest_freq)
121    change_min_freq = BASH_FOR.format(list=CPUFREQ_DIRS + 'scaling_min_freq',
122                                      body='echo %s > $f' % highest_freq)
123    change_perf_gov = BASH_FOR.format(list=CPUFREQ_DIRS + 'scaling_governor',
124                                      body='echo performance > $f')
125    if self.log_level == 'average':
126      self._logger.LogOutput('Pinning governor execution frequencies for %s' %
127                             machine_name)
128    ret = self._ce.CrosRunCommand(' && '.join((
129        'set -e ', change_max_freq, change_min_freq, change_perf_gov)),
130                                  machine=machine_name,
131                                  chromeos_root=chromeos_root)
132    self._logger.LogFatalIf(ret, 'Could not pin frequencies on machine: %s' %
133                            machine_name)
134
135  def DecreaseWaitTime(self, machine_name, chromeos_root):
136    """Change the ten seconds wait time for pagecycler to two seconds."""
137    FILE = '/usr/local/telemetry/src/tools/perf/page_sets/page_cycler_story.py'
138    ret = self._ce.CrosRunCommand(command='ls ' + FILE,
139                                  machine=machine_name,
140                                  chromeos_root=chromeos_root)
141    self._logger.LogFatalIf(ret, 'Could not find {} on machine: {}'.format(
142        FILE, machine_name))
143
144    if not ret:
145      sed_command = 'sed -i "s/_TTI_WAIT_TIME = 10/_TTI_WAIT_TIME = 2/g" '
146      ret = self._ce.CrosRunCommand(sed_command + FILE,
147                                    machine=machine_name,
148                                    chromeos_root=chromeos_root)
149      self._logger.LogFatalIf(ret, 'Could not modify {} on machine: {}'.format(
150          FILE, machine_name))
151
152
153  def RebootMachine(self, machine_name, chromeos_root):
154    command = 'reboot && exit'
155    self._ce.CrosRunCommand(command,
156                            machine=machine_name,
157                            chromeos_root=chromeos_root)
158    time.sleep(60)
159    # Whenever we reboot the machine, we need to restore the governor settings.
160    self.PinGovernorExecutionFrequencies(machine_name, chromeos_root)
161
162  def Test_That_Run(self, machine, label, benchmark, test_args, profiler_args):
163    """Run the test_that test.."""
164    options = ''
165    if label.board:
166      options += ' --board=%s' % label.board
167    if test_args:
168      options += ' %s' % test_args
169    if profiler_args:
170      self._logger.LogFatal('test_that does not support profiler.')
171    command = 'rm -rf /usr/local/autotest/results/*'
172    self._ce.CrosRunCommand(command,
173                            machine=machine,
174                            chromeos_root=label.chromeos_root)
175
176    # We do this because some tests leave the machine in weird states.
177    # Rebooting between iterations has proven to help with this.
178    self.RebootMachine(machine, label.chromeos_root)
179
180    command = (
181        ('%s --autotest_dir ~/trunk/src/third_party/autotest/files --fast '
182         '%s %s %s') % (TEST_THAT_PATH, options, machine, benchmark.test_name))
183    if self.log_level != 'verbose':
184      self._logger.LogOutput('Running test.')
185      self._logger.LogOutput('CMD: %s' % command)
186    # Use --no-ns-pid so that cros_sdk does not create a different
187    # process namespace and we can kill process created easily by
188    # their process group.
189    return self._ce.ChrootRunCommandWOutput(label.chromeos_root,
190                                            command,
191                                            command_terminator=self._ct,
192                                            cros_sdk_options='--no-ns-pid')
193
194  def RemoveTelemetryTempFile(self, machine, chromeos_root):
195    filename = 'telemetry@%s' % machine
196    fullname = os.path.join(chromeos_root, 'chroot', 'tmp', filename)
197    if os.path.exists(fullname):
198      os.remove(fullname)
199
200  def Telemetry_Crosperf_Run(self, machine, label, benchmark, test_args,
201                             profiler_args):
202    if not os.path.isdir(label.chrome_src):
203      self._logger.LogFatal('Cannot find chrome src dir to'
204                            ' run telemetry: %s' % label.chrome_src)
205
206    # Check for and remove temporary file that may have been left by
207    # previous telemetry runs (and which might prevent this run from
208    # working).
209    self.RemoveTelemetryTempFile(machine, label.chromeos_root)
210
211    # For telemetry runs, we can use the autotest copy from the source
212    # location. No need to have one under /build/<board>.
213    autotest_dir_arg = '--autotest_dir ~/trunk/src/third_party/autotest/files'
214
215    profiler_args = GetProfilerArgs(profiler_args)
216    fast_arg = ''
217    if not profiler_args:
218      # --fast works unless we are doing profiling (autotest limitation).
219      # --fast avoids unnecessary copies of syslogs.
220      fast_arg = '--fast'
221    args_string = ''
222    if test_args:
223      # Strip double quotes off args (so we can wrap them in single
224      # quotes, to pass through to Telemetry).
225      if test_args[0] == '"' and test_args[-1] == '"':
226        test_args = test_args[1:-1]
227      args_string = "test_args='%s'" % test_args
228
229    cmd = ('{} {} {} --board={} --args="{} run_local={} test={} '
230           '{}" {} telemetry_Crosperf'.format(
231               TEST_THAT_PATH, autotest_dir_arg, fast_arg, label.board,
232               args_string, benchmark.run_local, benchmark.test_name,
233               profiler_args, machine))
234
235    # Use --no-ns-pid so that cros_sdk does not create a different
236    # process namespace and we can kill process created easily by their
237    # process group.
238    chrome_root_options = ('--no-ns-pid '
239                           '--chrome_root={} --chrome_root_mount={} '
240                           "FEATURES=\"-usersandbox\" "
241                           'CHROME_ROOT={}'.format(label.chrome_src,
242                                                   CHROME_MOUNT_DIR,
243                                                   CHROME_MOUNT_DIR))
244    if self.log_level != 'verbose':
245      self._logger.LogOutput('Running test.')
246      self._logger.LogOutput('CMD: %s' % cmd)
247    return self._ce.ChrootRunCommandWOutput(
248        label.chromeos_root,
249        cmd,
250        command_terminator=self._ct,
251        cros_sdk_options=chrome_root_options)
252
253  def Telemetry_Run(self, machine, label, benchmark, profiler_args):
254    telemetry_run_path = ''
255    if not os.path.isdir(label.chrome_src):
256      self._logger.LogFatal('Cannot find chrome src dir to' ' run telemetry.')
257    else:
258      telemetry_run_path = os.path.join(label.chrome_src, 'src/tools/perf')
259      if not os.path.exists(telemetry_run_path):
260        self._logger.LogFatal('Cannot find %s directory.' % telemetry_run_path)
261
262    if profiler_args:
263      self._logger.LogFatal('Telemetry does not support the perf profiler.')
264
265    # Check for and remove temporary file that may have been left by
266    # previous telemetry runs (and which might prevent this run from
267    # working).
268    if not test_flag.GetTestMode():
269      self.RemoveTelemetryTempFile(machine, label.chromeos_root)
270
271    rsa_key = os.path.join(
272        label.chromeos_root,
273        'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa')
274
275    cmd = ('cd {0} && '
276           './run_measurement '
277           '--browser=cros-chrome '
278           '--output-format=csv '
279           '--remote={1} '
280           '--identity {2} '
281           '{3} {4}'.format(telemetry_run_path, machine, rsa_key,
282                            benchmark.test_name, benchmark.test_args))
283    if self.log_level != 'verbose':
284      self._logger.LogOutput('Running test.')
285      self._logger.LogOutput('CMD: %s' % cmd)
286    return self._ce.RunCommandWOutput(cmd, print_to_console=False)
287
288  def CommandTerminator(self):
289    return self._ct
290
291  def Terminate(self):
292    self._ct.Terminate()
293
294
295class MockSuiteRunner(object):
296  """Mock suite runner for test."""
297
298  def __init__(self):
299    self._true = True
300
301  def Run(self, *_args):
302    if self._true:
303      return [0, '', '']
304    else:
305      return [0, '', '']
306