xref: /openbmc/linux/tools/testing/kunit/kunit.py (revision a2cab953)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3#
4# A thin wrapper on top of the KUnit Kernel
5#
6# Copyright (C) 2019, Google LLC.
7# Author: Felix Guo <felixguoxiuping@gmail.com>
8# Author: Brendan Higgins <brendanhiggins@google.com>
9
10import argparse
11import os
12import re
13import shlex
14import sys
15import time
16
17assert sys.version_info >= (3, 7), "Python version is too old"
18
19from dataclasses import dataclass
20from enum import Enum, auto
21from typing import Iterable, List, Optional, Sequence, Tuple
22
23import kunit_json
24import kunit_kernel
25import kunit_parser
26from kunit_printer import stdout
27
28class KunitStatus(Enum):
29	SUCCESS = auto()
30	CONFIG_FAILURE = auto()
31	BUILD_FAILURE = auto()
32	TEST_FAILURE = auto()
33
34@dataclass
35class KunitResult:
36	status: KunitStatus
37	elapsed_time: float
38
39@dataclass
40class KunitConfigRequest:
41	build_dir: str
42	make_options: Optional[List[str]]
43
44@dataclass
45class KunitBuildRequest(KunitConfigRequest):
46	jobs: int
47
48@dataclass
49class KunitParseRequest:
50	raw_output: Optional[str]
51	json: Optional[str]
52
53@dataclass
54class KunitExecRequest(KunitParseRequest):
55	build_dir: str
56	timeout: int
57	filter_glob: str
58	kernel_args: Optional[List[str]]
59	run_isolated: Optional[str]
60
61@dataclass
62class KunitRequest(KunitExecRequest, KunitBuildRequest):
63	pass
64
65
66def get_kernel_root_path() -> str:
67	path = sys.argv[0] if not __file__ else __file__
68	parts = os.path.realpath(path).split('tools/testing/kunit')
69	if len(parts) != 2:
70		sys.exit(1)
71	return parts[0]
72
73def config_tests(linux: kunit_kernel.LinuxSourceTree,
74		 request: KunitConfigRequest) -> KunitResult:
75	stdout.print_with_timestamp('Configuring KUnit Kernel ...')
76
77	config_start = time.time()
78	success = linux.build_reconfig(request.build_dir, request.make_options)
79	config_end = time.time()
80	if not success:
81		return KunitResult(KunitStatus.CONFIG_FAILURE,
82				   config_end - config_start)
83	return KunitResult(KunitStatus.SUCCESS,
84			   config_end - config_start)
85
86def build_tests(linux: kunit_kernel.LinuxSourceTree,
87		request: KunitBuildRequest) -> KunitResult:
88	stdout.print_with_timestamp('Building KUnit Kernel ...')
89
90	build_start = time.time()
91	success = linux.build_kernel(request.jobs,
92				     request.build_dir,
93				     request.make_options)
94	build_end = time.time()
95	if not success:
96		return KunitResult(KunitStatus.BUILD_FAILURE,
97				   build_end - build_start)
98	if not success:
99		return KunitResult(KunitStatus.BUILD_FAILURE,
100				   build_end - build_start)
101	return KunitResult(KunitStatus.SUCCESS,
102			   build_end - build_start)
103
104def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
105			   request: KunitBuildRequest) -> KunitResult:
106	config_result = config_tests(linux, request)
107	if config_result.status != KunitStatus.SUCCESS:
108		return config_result
109
110	return build_tests(linux, request)
111
112def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
113	args = ['kunit.action=list']
114	if request.kernel_args:
115		args.extend(request.kernel_args)
116
117	output = linux.run_kernel(args=args,
118			   timeout=request.timeout,
119			   filter_glob=request.filter_glob,
120			   build_dir=request.build_dir)
121	lines = kunit_parser.extract_tap_lines(output)
122	# Hack! Drop the dummy TAP version header that the executor prints out.
123	lines.pop()
124
125	# Filter out any extraneous non-test output that might have gotten mixed in.
126	return [l for l in lines if re.match(r'^[^\s.]+\.[^\s.]+$', l)]
127
128def _suites_from_test_list(tests: List[str]) -> List[str]:
129	"""Extracts all the suites from an ordered list of tests."""
130	suites = []  # type: List[str]
131	for t in tests:
132		parts = t.split('.', maxsplit=2)
133		if len(parts) != 2:
134			raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
135		suite, case = parts
136		if not suites or suites[-1] != suite:
137			suites.append(suite)
138	return suites
139
140
141
142def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
143	filter_globs = [request.filter_glob]
144	if request.run_isolated:
145		tests = _list_tests(linux, request)
146		if request.run_isolated == 'test':
147			filter_globs = tests
148		if request.run_isolated == 'suite':
149			filter_globs = _suites_from_test_list(tests)
150			# Apply the test-part of the user's glob, if present.
151			if '.' in request.filter_glob:
152				test_glob = request.filter_glob.split('.', maxsplit=2)[1]
153				filter_globs = [g + '.'+ test_glob for g in filter_globs]
154
155	metadata = kunit_json.Metadata(arch=linux.arch(), build_dir=request.build_dir, def_config='kunit_defconfig')
156
157	test_counts = kunit_parser.TestCounts()
158	exec_time = 0.0
159	for i, filter_glob in enumerate(filter_globs):
160		stdout.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
161
162		test_start = time.time()
163		run_result = linux.run_kernel(
164			args=request.kernel_args,
165			timeout=request.timeout,
166			filter_glob=filter_glob,
167			build_dir=request.build_dir)
168
169		_, test_result = parse_tests(request, metadata, run_result)
170		# run_kernel() doesn't block on the kernel exiting.
171		# That only happens after we get the last line of output from `run_result`.
172		# So exec_time here actually contains parsing + execution time, which is fine.
173		test_end = time.time()
174		exec_time += test_end - test_start
175
176		test_counts.add_subtest_counts(test_result.counts)
177
178	if len(filter_globs) == 1 and test_counts.crashed > 0:
179		bd = request.build_dir
180		print('The kernel seems to have crashed; you can decode the stack traces with:')
181		print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
182				bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
183
184	kunit_status = _map_to_overall_status(test_counts.get_status())
185	return KunitResult(status=kunit_status, elapsed_time=exec_time)
186
187def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
188	if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
189		return KunitStatus.SUCCESS
190	return KunitStatus.TEST_FAILURE
191
192def parse_tests(request: KunitParseRequest, metadata: kunit_json.Metadata, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
193	parse_start = time.time()
194
195	test_result = kunit_parser.Test()
196
197	if request.raw_output:
198		# Treat unparsed results as one passing test.
199		test_result.status = kunit_parser.TestStatus.SUCCESS
200		test_result.counts.passed = 1
201
202		output: Iterable[str] = input_data
203		if request.raw_output == 'all':
204			pass
205		elif request.raw_output == 'kunit':
206			output = kunit_parser.extract_tap_lines(output, lstrip=False)
207		for line in output:
208			print(line.rstrip())
209
210	else:
211		test_result = kunit_parser.parse_run_tests(input_data)
212	parse_end = time.time()
213
214	if request.json:
215		json_str = kunit_json.get_json_result(
216					test=test_result,
217					metadata=metadata)
218		if request.json == 'stdout':
219			print(json_str)
220		else:
221			with open(request.json, 'w') as f:
222				f.write(json_str)
223			stdout.print_with_timestamp("Test results stored in %s" %
224				os.path.abspath(request.json))
225
226	if test_result.status != kunit_parser.TestStatus.SUCCESS:
227		return KunitResult(KunitStatus.TEST_FAILURE, parse_end - parse_start), test_result
228
229	return KunitResult(KunitStatus.SUCCESS, parse_end - parse_start), test_result
230
231def run_tests(linux: kunit_kernel.LinuxSourceTree,
232	      request: KunitRequest) -> KunitResult:
233	run_start = time.time()
234
235	config_result = config_tests(linux, request)
236	if config_result.status != KunitStatus.SUCCESS:
237		return config_result
238
239	build_result = build_tests(linux, request)
240	if build_result.status != KunitStatus.SUCCESS:
241		return build_result
242
243	exec_result = exec_tests(linux, request)
244
245	run_end = time.time()
246
247	stdout.print_with_timestamp((
248		'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
249		'building, %.3fs running\n') % (
250				run_end - run_start,
251				config_result.elapsed_time,
252				build_result.elapsed_time,
253				exec_result.elapsed_time))
254	return exec_result
255
256# Problem:
257# $ kunit.py run --json
258# works as one would expect and prints the parsed test results as JSON.
259# $ kunit.py run --json suite_name
260# would *not* pass suite_name as the filter_glob and print as json.
261# argparse will consider it to be another way of writing
262# $ kunit.py run --json=suite_name
263# i.e. it would run all tests, and dump the json to a `suite_name` file.
264# So we hackily automatically rewrite --json => --json=stdout
265pseudo_bool_flag_defaults = {
266		'--json': 'stdout',
267		'--raw_output': 'kunit',
268}
269def massage_argv(argv: Sequence[str]) -> Sequence[str]:
270	def massage_arg(arg: str) -> str:
271		if arg not in pseudo_bool_flag_defaults:
272			return arg
273		return  f'{arg}={pseudo_bool_flag_defaults[arg]}'
274	return list(map(massage_arg, argv))
275
276def get_default_jobs() -> int:
277	return len(os.sched_getaffinity(0))
278
279def add_common_opts(parser) -> None:
280	parser.add_argument('--build_dir',
281			    help='As in the make command, it specifies the build '
282			    'directory.',
283			    type=str, default='.kunit', metavar='DIR')
284	parser.add_argument('--make_options',
285			    help='X=Y make option, can be repeated.',
286			    action='append', metavar='X=Y')
287	parser.add_argument('--alltests',
288			    help='Run all KUnit tests via tools/testing/kunit/configs/all_tests.config',
289			    action='store_true')
290	parser.add_argument('--kunitconfig',
291			     help='Path to Kconfig fragment that enables KUnit tests.'
292			     ' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
293			     'will get  automatically appended. If repeated, the files '
294			     'blindly concatenated, which might not work in all cases.',
295			     action='append', metavar='PATHS')
296	parser.add_argument('--kconfig_add',
297			     help='Additional Kconfig options to append to the '
298			     '.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
299			    action='append', metavar='CONFIG_X=Y')
300
301	parser.add_argument('--arch',
302			    help=('Specifies the architecture to run tests under. '
303				  'The architecture specified here must match the '
304				  'string passed to the ARCH make param, '
305				  'e.g. i386, x86_64, arm, um, etc. Non-UML '
306				  'architectures run on QEMU.'),
307			    type=str, default='um', metavar='ARCH')
308
309	parser.add_argument('--cross_compile',
310			    help=('Sets make\'s CROSS_COMPILE variable; it should '
311				  'be set to a toolchain path prefix (the prefix '
312				  'of gcc and other tools in your toolchain, for '
313				  'example `sparc64-linux-gnu-` if you have the '
314				  'sparc toolchain installed on your system, or '
315				  '`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
316				  'if you have downloaded the microblaze toolchain '
317				  'from the 0-day website to a directory in your '
318				  'home directory called `toolchains`).'),
319			    metavar='PREFIX')
320
321	parser.add_argument('--qemu_config',
322			    help=('Takes a path to a path to a file containing '
323				  'a QemuArchParams object.'),
324			    type=str, metavar='FILE')
325
326	parser.add_argument('--qemu_args',
327			    help='Additional QEMU arguments, e.g. "-smp 8"',
328			    action='append', metavar='')
329
330def add_build_opts(parser) -> None:
331	parser.add_argument('--jobs',
332			    help='As in the make command, "Specifies  the number of '
333			    'jobs (commands) to run simultaneously."',
334			    type=int, default=get_default_jobs(), metavar='N')
335
336def add_exec_opts(parser) -> None:
337	parser.add_argument('--timeout',
338			    help='maximum number of seconds to allow for all tests '
339			    'to run. This does not include time taken to build the '
340			    'tests.',
341			    type=int,
342			    default=300,
343			    metavar='SECONDS')
344	parser.add_argument('filter_glob',
345			    help='Filter which KUnit test suites/tests run at '
346			    'boot-time, e.g. list* or list*.*del_test',
347			    type=str,
348			    nargs='?',
349			    default='',
350			    metavar='filter_glob')
351	parser.add_argument('--kernel_args',
352			    help='Kernel command-line parameters. Maybe be repeated',
353			     action='append', metavar='')
354	parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
355			    'individual suite/test. This is can be useful for debugging '
356			    'a non-hermetic test, one that might pass/fail based on '
357			    'what ran before it.',
358			    type=str,
359			    choices=['suite', 'test'])
360
361def add_parse_opts(parser) -> None:
362	parser.add_argument('--raw_output', help='If set don\'t format output from kernel. '
363			    'If set to --raw_output=kunit, filters to just KUnit output.',
364			     type=str, nargs='?', const='all', default=None, choices=['all', 'kunit'])
365	parser.add_argument('--json',
366			    nargs='?',
367			    help='Stores test results in a JSON, and either '
368			    'prints to stdout or saves to file if a '
369			    'filename is specified',
370			    type=str, const='stdout', default=None, metavar='FILE')
371
372
373def tree_from_args(cli_args: argparse.Namespace) -> kunit_kernel.LinuxSourceTree:
374	"""Returns a LinuxSourceTree based on the user's arguments."""
375	# Allow users to specify multiple arguments in one string, e.g. '-smp 8'
376	qemu_args: List[str] = []
377	if cli_args.qemu_args:
378		for arg in cli_args.qemu_args:
379			qemu_args.extend(shlex.split(arg))
380
381	kunitconfigs = cli_args.kunitconfig if cli_args.kunitconfig else []
382	if cli_args.alltests:
383		# Prepend so user-specified options take prio if we ever allow
384		# --kunitconfig options to have differing options.
385		kunitconfigs = [kunit_kernel.ALL_TESTS_CONFIG_PATH] + kunitconfigs
386
387	return kunit_kernel.LinuxSourceTree(cli_args.build_dir,
388			kunitconfig_paths=kunitconfigs,
389			kconfig_add=cli_args.kconfig_add,
390			arch=cli_args.arch,
391			cross_compile=cli_args.cross_compile,
392			qemu_config_path=cli_args.qemu_config,
393			extra_qemu_args=qemu_args)
394
395
396def main(argv):
397	parser = argparse.ArgumentParser(
398			description='Helps writing and running KUnit tests.')
399	subparser = parser.add_subparsers(dest='subcommand')
400
401	# The 'run' command will config, build, exec, and parse in one go.
402	run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
403	add_common_opts(run_parser)
404	add_build_opts(run_parser)
405	add_exec_opts(run_parser)
406	add_parse_opts(run_parser)
407
408	config_parser = subparser.add_parser('config',
409						help='Ensures that .config contains all of '
410						'the options in .kunitconfig')
411	add_common_opts(config_parser)
412
413	build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
414	add_common_opts(build_parser)
415	add_build_opts(build_parser)
416
417	exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
418	add_common_opts(exec_parser)
419	add_exec_opts(exec_parser)
420	add_parse_opts(exec_parser)
421
422	# The 'parse' option is special, as it doesn't need the kernel source
423	# (therefore there is no need for a build_dir, hence no add_common_opts)
424	# and the '--file' argument is not relevant to 'run', so isn't in
425	# add_parse_opts()
426	parse_parser = subparser.add_parser('parse',
427					    help='Parses KUnit results from a file, '
428					    'and parses formatted results.')
429	add_parse_opts(parse_parser)
430	parse_parser.add_argument('file',
431				  help='Specifies the file to read results from.',
432				  type=str, nargs='?', metavar='input_file')
433
434	cli_args = parser.parse_args(massage_argv(argv))
435
436	if get_kernel_root_path():
437		os.chdir(get_kernel_root_path())
438
439	if cli_args.subcommand == 'run':
440		if not os.path.exists(cli_args.build_dir):
441			os.mkdir(cli_args.build_dir)
442
443		linux = tree_from_args(cli_args)
444		request = KunitRequest(build_dir=cli_args.build_dir,
445				       make_options=cli_args.make_options,
446				       jobs=cli_args.jobs,
447				       raw_output=cli_args.raw_output,
448				       json=cli_args.json,
449				       timeout=cli_args.timeout,
450				       filter_glob=cli_args.filter_glob,
451				       kernel_args=cli_args.kernel_args,
452				       run_isolated=cli_args.run_isolated)
453		result = run_tests(linux, request)
454		if result.status != KunitStatus.SUCCESS:
455			sys.exit(1)
456	elif cli_args.subcommand == 'config':
457		if cli_args.build_dir and (
458				not os.path.exists(cli_args.build_dir)):
459			os.mkdir(cli_args.build_dir)
460
461		linux = tree_from_args(cli_args)
462		request = KunitConfigRequest(build_dir=cli_args.build_dir,
463					     make_options=cli_args.make_options)
464		result = config_tests(linux, request)
465		stdout.print_with_timestamp((
466			'Elapsed time: %.3fs\n') % (
467				result.elapsed_time))
468		if result.status != KunitStatus.SUCCESS:
469			sys.exit(1)
470	elif cli_args.subcommand == 'build':
471		linux = tree_from_args(cli_args)
472		request = KunitBuildRequest(build_dir=cli_args.build_dir,
473					    make_options=cli_args.make_options,
474					    jobs=cli_args.jobs)
475		result = config_and_build_tests(linux, request)
476		stdout.print_with_timestamp((
477			'Elapsed time: %.3fs\n') % (
478				result.elapsed_time))
479		if result.status != KunitStatus.SUCCESS:
480			sys.exit(1)
481	elif cli_args.subcommand == 'exec':
482		linux = tree_from_args(cli_args)
483		exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
484						build_dir=cli_args.build_dir,
485						json=cli_args.json,
486						timeout=cli_args.timeout,
487						filter_glob=cli_args.filter_glob,
488						kernel_args=cli_args.kernel_args,
489						run_isolated=cli_args.run_isolated)
490		result = exec_tests(linux, exec_request)
491		stdout.print_with_timestamp((
492			'Elapsed time: %.3fs\n') % (result.elapsed_time))
493		if result.status != KunitStatus.SUCCESS:
494			sys.exit(1)
495	elif cli_args.subcommand == 'parse':
496		if cli_args.file is None:
497			sys.stdin.reconfigure(errors='backslashreplace')  # pytype: disable=attribute-error
498			kunit_output = sys.stdin
499		else:
500			with open(cli_args.file, 'r', errors='backslashreplace') as f:
501				kunit_output = f.read().splitlines()
502		# We know nothing about how the result was created!
503		metadata = kunit_json.Metadata()
504		request = KunitParseRequest(raw_output=cli_args.raw_output,
505					    json=cli_args.json)
506		result, _ = parse_tests(request, metadata, kunit_output)
507		if result.status != KunitStatus.SUCCESS:
508			sys.exit(1)
509	else:
510		parser.print_help()
511
512if __name__ == '__main__':
513	main(sys.argv[1:])
514