blob: c930100e71845bb23cd957f1abf7a664a9274eda [file] [log] [blame]
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3# Copyright 2018 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Evaluate ChromeOS autotest.
7
8Note that by default 'test_that' will install dependency packages of autotest
9only once. For example, if you overwrote chrome's unittest binary, your new
Kuang-che Wu927231f2018-07-24 14:21:56 +080010binary will be persistent across autotest runs. Add --reinstall if you want
Kuang-che Wub9705bd2018-06-28 17:59:18 +080011clean autotest install.
12"""
13from __future__ import print_function
14import argparse
15import json
16import logging
17import os
18import re
19import subprocess
20import sys
21
22from bisect_kit import cli
23from bisect_kit import common
24from bisect_kit import configure
25from bisect_kit import cros_util
26from bisect_kit import util
27
28logger = logging.getLogger(__name__)
29
30OLD = 'old'
31NEW = 'new'
32SKIP = 'skip'
33FATAL = 'fatal'
34
35EXIT_CODE_MAP = {
36 OLD: 0,
37 NEW: 1,
38 SKIP: 125,
39 FATAL: 126,
40}
41
42
43def create_argument_parser():
44 parser = argparse.ArgumentParser(description=__doc__)
45 common.add_common_arguments(parser)
46 parser.add_argument(
47 'dut',
48 nargs='?',
49 type=cli.argtype_notempty,
50 metavar='DUT',
51 default=configure.get('DUT', ''))
52 parser.add_argument(
53 '--chromeos_root',
54 type=cli.argtype_dir_path,
55 metavar='CHROMEOS_ROOT',
56 default=configure.get('CHROMEOS_ROOT', ''),
57 help='ChromeOS tree root')
58 parser.add_argument(
59 '--test_name',
60 required=True,
61 help='Test name, like "video_VideoDecodeAccelerator.h264"')
62 parser.add_argument(
63 '--metric',
64 help=
65 'Metric name of performance test; example: "cheets_SystemRawImageSize"')
66 parser.add_argument(
67 '--old_value',
68 type=float,
69 help='For performance test, old value of given metric')
70 parser.add_argument(
71 '--new_value',
72 type=float,
73 help='For performance test, new value of given metric')
74 parser.add_argument(
75 '--prebuilt',
76 action='store_true',
77 help='Run autotest using existing prebuilt package if specified; '
78 'otherwise use the default one')
79 parser.add_argument(
80 '--reinstall',
81 action='store_true',
82 help='Remove existing autotest folder on the DUT first')
83 parser.add_argument(
84 '--args',
85 help='Extra args passed to "test_that --args"; Overrides the default')
86
87 return parser
88
89
90def parse_test_report_log(result_log, metric):
91 """Parses autotest result log.
92
93 Args:
94 result_log: content of test_report.log
95 metric: what metric to capture if not None
96
97 Returns:
98 passed, values:
99 passed: True if test run successfully
100 values: captured metric values; None if test failed or metric is None
101 """
102 m = re.search(r'Total PASS: (\d+)/(\d+)', result_log)
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800103 passed = (m and m.group(1) == m.group(2))
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800104
105 if not metric:
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800106 return passed, None
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800107
108 values = []
109 for line in result_log.splitlines():
110 m = re.match(r'^(\S+)\s+(\w+)(?:\{\d+\})?\s+(\d+\.\d+)$', line)
111 if not m:
112 continue
113 if m.group(2) == metric:
114 values.append(float(m.group(3)))
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800115 return passed, values
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800116
117
118def parse_test_result_chart(json_path, metric):
119 data = json.load(open(json_path))
Kuang-che Wu3331caf2018-09-06 19:47:02 +0800120
121 # format 1, telemetry
122 if 'charts' in data:
123 summary = data['charts'][metric]['summary']
124
125 # format 2, autotest without graph
126 elif metric in data:
127 summary = data[metric]['summary']
128
129 # format 3, autotest with graph
130 elif metric.count('.') == 1:
131 name, subname = metric.split('.')
132 summary = data[name][subname]
133
134 else:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800135 logger.error('metric "%s" not in %s', metric, json_path)
Kuang-che Wudd802672018-08-10 19:40:14 +0800136 return []
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800137
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800138 if 'values' in summary:
139 return summary['values']
140 return [summary['value']]
141
142
143def get_additional_test_args(test_name):
144 """Gets extra arguments to specific test.
145
146 Some tests may require special arguments to run.
147
148 Args:
149 test_name: test name
150
151 Returns:
152 arguments (str)
153 """
154 if test_name.startswith('telemetry_'):
155 return 'local=True'
156 return ''
157
158
159def run_test(opts):
160 """Runs an autotest test.
161
162 Args:
163 opts: An argparse.Namespace to hold command line arguments.
164
165 Returns:
166 path of test result (outside chroot)
167 """
168 if opts.reinstall:
169 util.check_call('ssh', opts.dut, 'rm', '-rf', '/usr/local/autotest')
170
171 prebuilt_autotest_dir = os.path.join(cros_util.chromeos_root_inside_chroot,
172 cros_util.prebuilt_autotest_dir)
173 # Set results dir inside source tree, so it's easier to access them outside
174 # chroot.
175 results_dir = os.path.join(cros_util.chromeos_root_inside_chroot,
176 'tmp/autotest_results_tmp')
177 if opts.prebuilt:
178 test_that_bin = os.path.join(prebuilt_autotest_dir,
179 'site_utils/test_that.py')
180 else:
181 test_that_bin = '/usr/bin/test_that'
182 cmd = [test_that_bin, opts.dut, opts.test_name, '--results_dir', results_dir]
183 if opts.prebuilt:
184 cmd += ['--autotest_dir', prebuilt_autotest_dir]
185
186 args = get_additional_test_args(opts.test_name)
187 if opts.args:
188 if args:
Kuang-che Wu74768d32018-09-07 12:03:24 +0800189 logger.info(
190 'default test_that args `%s` is overridden by '
191 'command line option `%s`', args, opts.args)
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800192 cmd += ['--args', opts.args]
193 elif args:
194 cmd += ['--args', args]
195
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800196 try:
197 output = cros_util.cros_sdk(opts.chromeos_root, *cmd)
198 except subprocess.CalledProcessError as e:
199 output = e.output
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800200
201 m = re.search(r'Finished running tests. Results can be found in (\S+)',
202 output)
203 if not m:
204 logger.error('result dir is unknown')
205 return None
206 assert m.group(1) == results_dir
207 return results_dir.replace(cros_util.chromeos_root_inside_chroot,
208 opts.chromeos_root)
209
210
211def gather_test_result(opts, result_dir):
212 result_log_path = os.path.join(result_dir, 'test_report.log')
213 result_log = open(result_log_path).read()
214
215 passed, values = parse_test_report_log(result_log, opts.metric)
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800216 if opts.metric and not values:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800217 values = []
218 for root, _, files in os.walk(result_dir):
219 for filename in files:
220 if filename != 'results-chart.json':
221 continue
222 full_path = os.path.join(root, filename)
223 values += parse_test_result_chart(full_path, opts.metric)
224
225 return passed, values
226
227
228def main(args=None):
229 common.init()
230 parser = create_argument_parser()
231 opts = parser.parse_args(args)
232 common.config_logging(opts)
233
234 if not cros_util.is_dut(opts.dut):
235 return FATAL
236
237 # Verify command line options.
238 if opts.metric:
239 if opts.old_value is None:
240 logger.error('--old_value is not provided')
241 return FATAL
242 if opts.new_value is None:
243 logger.error('--new_value is not provided')
244 return FATAL
245 else:
246 if opts.old_value is not None:
247 logger.error('--old_value is provided but --metric is not')
248 return FATAL
249 if opts.new_value is not None:
250 logger.error('--new_value is provided but --metric is not')
251 return FATAL
252
Kuang-che Wue47162d2018-10-29 17:24:04 +0800253 # Some versions of ChromeOS SDK is broken and ship bad 'ssh' executable. This
254 # works around the issue before we fixed the issue.
255 # TODO(kcwu): fix crbug/899490
256 cros_util.cros_sdk(opts.chromeos_root, 'sudo', 'emerge', 'net-misc/openssh')
257
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800258 result_dir = run_test(opts)
259 if not result_dir:
Kuang-che Wudd802672018-08-10 19:40:14 +0800260 return FATAL
261
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800262 passed, values = gather_test_result(opts, result_dir)
263
264 if opts.metric:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800265 if not values:
266 logger.warning('no values found; SKIP')
267 return SKIP
268
269 print('BISECT_RESULT_VALUES=', ' '.join(map(str, values)))
270 average = float(sum(values)) / len(values)
Kuang-che Wu689f1542018-08-20 17:45:58 +0800271 if abs(average - opts.old_value) < abs(average - opts.new_value):
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800272 logger.info('values=%s, average=%s; OLD', values, average)
273 return OLD
274 logger.info('values=%s, average=%s; NEW', values, average)
275 return NEW
276 else:
277 if passed:
278 logger.info('passed')
279 return OLD
280 logger.info('failed')
281 return NEW
282
283
284if __name__ == '__main__':
285 sys.exit(EXIT_CODE_MAP[main()])