blob: 669470fa978b38802288bf28393dfa2b0fbffc20 [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/python3
2#
3# Build performance test script
4#
5# Copyright (c) 2016, Intel Corporation.
6#
7# This program is free software; you can redistribute it and/or modify it
8# under the terms and conditions of the GNU General Public License,
9# version 2, as published by the Free Software Foundation.
10#
11# This program is distributed in the hope it will be useful, but WITHOUT
12# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14# more details.
15#
16"""Build performance test script"""
17import argparse
18import errno
19import fcntl
Brad Bishop6e60e8b2018-02-01 10:27:11 -050020import json
Patrick Williamsc0f7c042017-02-23 20:41:17 -060021import logging
22import os
Brad Bishop6e60e8b2018-02-01 10:27:11 -050023import re
Patrick Williamsc0f7c042017-02-23 20:41:17 -060024import shutil
25import sys
Patrick Williamsc0f7c042017-02-23 20:41:17 -060026from datetime import datetime
27
28sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/lib')
29import scriptpath
30scriptpath.add_oe_lib_path()
Brad Bishop6e60e8b2018-02-01 10:27:11 -050031scriptpath.add_bitbake_lib_path()
Patrick Williamsc0f7c042017-02-23 20:41:17 -060032import oeqa.buildperf
33from oeqa.buildperf import (BuildPerfTestLoader, BuildPerfTestResult,
34 BuildPerfTestRunner, KernelDropCaches)
35from oeqa.utils.commands import runCmd
Brad Bishop6e60e8b2018-02-01 10:27:11 -050036from oeqa.utils.metadata import metadata_from_bb, write_metadata_file
Patrick Williamsc0f7c042017-02-23 20:41:17 -060037
38
39# Set-up logging
40LOG_FORMAT = '[%(asctime)s] %(levelname)s: %(message)s'
41logging.basicConfig(level=logging.INFO, format=LOG_FORMAT,
42 datefmt='%Y-%m-%d %H:%M:%S')
43log = logging.getLogger()
44
45
46def acquire_lock(lock_f):
47 """Acquire flock on file"""
48 log.debug("Acquiring lock %s", os.path.abspath(lock_f.name))
49 try:
50 fcntl.flock(lock_f, fcntl.LOCK_EX | fcntl.LOCK_NB)
51 except IOError as err:
52 if err.errno == errno.EAGAIN:
53 return False
54 raise
55 log.debug("Lock acquired")
56 return True
57
58
59def pre_run_sanity_check():
60 """Sanity check of build environment"""
61 build_dir = os.environ.get("BUILDDIR")
62 if not build_dir:
63 log.error("BUILDDIR not set. Please run the build environmnent setup "
64 "script.")
65 return False
66 if os.getcwd() != build_dir:
67 log.error("Please run this script under BUILDDIR (%s)", build_dir)
68 return False
69
70 ret = runCmd('which bitbake', ignore_status=True)
71 if ret.status:
72 log.error("bitbake command not found")
73 return False
74 return True
75
Patrick Williamsc0f7c042017-02-23 20:41:17 -060076def setup_file_logging(log_file):
77 """Setup loggin to file"""
78 log_dir = os.path.dirname(log_file)
79 if not os.path.exists(log_dir):
80 os.makedirs(log_dir)
81 formatter = logging.Formatter(LOG_FORMAT)
82 handler = logging.FileHandler(log_file)
83 handler.setFormatter(formatter)
84 log.addHandler(handler)
85
86
87def archive_build_conf(out_dir):
88 """Archive build/conf to test results"""
89 src_dir = os.path.join(os.environ['BUILDDIR'], 'conf')
90 tgt_dir = os.path.join(out_dir, 'build', 'conf')
91 os.makedirs(os.path.dirname(tgt_dir))
92 shutil.copytree(src_dir, tgt_dir)
93
94
Brad Bishop6e60e8b2018-02-01 10:27:11 -050095def update_globalres_file(result_obj, filename, metadata):
96 """Write results to globalres csv file"""
97 # Map test names to time and size columns in globalres
98 # The tuples represent index and length of times and sizes
99 # respectively
100 gr_map = {'test1': ((0, 1), (8, 1)),
101 'test12': ((1, 1), (None, None)),
102 'test13': ((2, 1), (9, 1)),
103 'test2': ((3, 1), (None, None)),
104 'test3': ((4, 3), (None, None)),
105 'test4': ((7, 1), (10, 2))}
106
107 values = ['0'] * 12
108 for status, test, _ in result_obj.all_results():
109 if status in ['ERROR', 'SKIPPED']:
110 continue
111 (t_ind, t_len), (s_ind, s_len) = gr_map[test.name]
112 if t_ind is not None:
113 values[t_ind:t_ind + t_len] = test.times
114 if s_ind is not None:
115 values[s_ind:s_ind + s_len] = test.sizes
116
117 log.debug("Writing globalres log to %s", filename)
118 rev_info = metadata['layers']['meta']
119 with open(filename, 'a') as fobj:
120 fobj.write('{},{}:{},{},'.format(metadata['hostname'],
121 rev_info['branch'],
122 rev_info['commit'],
123 rev_info['commit']))
124 fobj.write(','.join(values) + '\n')
125
126
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600127def parse_args(argv):
128 """Parse command line arguments"""
129 parser = argparse.ArgumentParser(
130 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
131
132 parser.add_argument('-D', '--debug', action='store_true',
133 help='Enable debug level logging')
134 parser.add_argument('--globalres-file',
135 type=os.path.abspath,
136 help="Append results to 'globalres' csv file")
137 parser.add_argument('--lock-file', default='./oe-build-perf.lock',
138 metavar='FILENAME', type=os.path.abspath,
139 help="Lock file to use")
140 parser.add_argument('-o', '--out-dir', default='results-{date}',
141 type=os.path.abspath,
142 help="Output directory for test results")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500143 parser.add_argument('-x', '--xml', action='store_true',
144 help='Enable JUnit xml output')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600145 parser.add_argument('--log-file',
146 default='{out_dir}/oe-build-perf-test.log',
147 help="Log file of this script")
148 parser.add_argument('--run-tests', nargs='+', metavar='TEST',
149 help="List of tests to run")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600150
151 return parser.parse_args(argv)
152
153
154def main(argv=None):
155 """Script entry point"""
156 args = parse_args(argv)
157
158 # Set-up log file
159 out_dir = args.out_dir.format(date=datetime.now().strftime('%Y%m%d%H%M%S'))
160 setup_file_logging(args.log_file.format(out_dir=out_dir))
161
162 if args.debug:
163 log.setLevel(logging.DEBUG)
164
165 lock_f = open(args.lock_file, 'w')
166 if not acquire_lock(lock_f):
167 log.error("Another instance of this script is running, exiting...")
168 return 1
169
170 if not pre_run_sanity_check():
171 return 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600172
173 # Check our capability to drop caches and ask pass if needed
174 KernelDropCaches.check()
175
176 # Load build perf tests
177 loader = BuildPerfTestLoader()
178 if args.run_tests:
179 suite = loader.loadTestsFromNames(args.run_tests, oeqa.buildperf)
180 else:
181 suite = loader.loadTestsFromModule(oeqa.buildperf)
182
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500183 # Save test metadata
184 metadata = metadata_from_bb()
185 log.info("Testing Git revision branch:commit %s:%s (%s)",
186 metadata['layers']['meta']['branch'],
187 metadata['layers']['meta']['commit'],
188 metadata['layers']['meta']['commit_count'])
189 if args.xml:
190 write_metadata_file(os.path.join(out_dir, 'metadata.xml'), metadata)
191 else:
192 with open(os.path.join(out_dir, 'metadata.json'), 'w') as fobj:
193 json.dump(metadata, fobj, indent=2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600194 archive_build_conf(out_dir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500195
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600196 runner = BuildPerfTestRunner(out_dir, verbosity=2)
197
198 # Suppress logger output to stderr so that the output from unittest
199 # is not mixed with occasional logger output
200 log.handlers[0].setLevel(logging.CRITICAL)
201
202 # Run actual tests
203 result = runner.run(suite)
204
205 # Restore logger output to stderr
206 log.handlers[0].setLevel(log.level)
207
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500208 if args.xml:
209 result.write_results_xml()
210 else:
211 result.write_results_json()
212 result.write_buildstats_json()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600213 if args.globalres_file:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500214 update_globalres_file(result, args.globalres_file, metadata)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600215 if result.wasSuccessful():
216 return 0
217
218 return 2
219
220
221if __name__ == '__main__':
222 sys.exit(main())
223