blob: 4192cef16c6fb83c95a694b7a13672e9cb5f5fa7 [file] [log] [blame]
Andrew Scullbc7189d2018-08-14 09:35:13 +01001#!/usr/bin/env python
Andrew Scull18834872018-10-12 11:48:09 +01002#
Andrew Walbran692b3252019-03-07 15:51:31 +00003# Copyright 2018 The Hafnium Authors.
Andrew Scull18834872018-10-12 11:48:09 +01004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# https://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
David Brazdil2df24082019-09-05 11:55:08 +010017"""Script which drives invocation of tests and parsing their output to produce
18a results report.
Andrew Scullbc7189d2018-08-14 09:35:13 +010019"""
20
21from __future__ import print_function
22
Andrew Scull3b62f2b2018-08-21 14:26:12 +010023import xml.etree.ElementTree as ET
24
Andrew Scullbc7189d2018-08-14 09:35:13 +010025import argparse
David Brazdil2df24082019-09-05 11:55:08 +010026import collections
Andrew Scull04502e42018-09-03 14:54:52 +010027import datetime
Andrew Scullbc7189d2018-08-14 09:35:13 +010028import json
29import os
30import re
31import subprocess
32import sys
33
Andrew Scull845fc9b2019-04-03 12:44:26 +010034HFTEST_LOG_PREFIX = "[hftest] "
35HFTEST_LOG_FAILURE_PREFIX = "Failure:"
36HFTEST_LOG_FINISHED = "FINISHED"
37
David Brazdil2df24082019-09-05 11:55:08 +010038HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
39 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010040DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010041FVP_BINARY = os.path.join(
42 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMv8A_pkg", "models",
43 "Linux64_GCC-4.9", "FVP_Base_RevC-2xAEMv8A")
44FVP_PREBUILT_DTS = os.path.join(
45 HF_ROOT, "prebuilts", "linux-aarch64", "arm-trusted-firmware",
46 "fvp-base-gicv3-psci-1t.dts")
Andrew Scull845fc9b2019-04-03 12:44:26 +010047
David Brazdil2df24082019-09-05 11:55:08 +010048def read_file(path):
49 with open(path, "r") as f:
50 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010051
David Brazdil2df24082019-09-05 11:55:08 +010052def write_file(path, to_write, append=False):
53 with open(path, "a" if append else "w") as f:
54 f.write(to_write)
55
56def append_file(path, to_write):
57 write_file(path, to_write, append=True)
58
59def join_if_not_None(*args):
60 return " ".join(filter(lambda x: x, args))
61
62class ArtifactsManager:
63 """Class which manages folder with test artifacts."""
64
65 def __init__(self, log_dir):
66 self.created_files = []
67 self.log_dir = log_dir
68
69 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +010070 try:
David Brazdil2df24082019-09-05 11:55:08 +010071 os.makedirs(self.log_dir)
72 except OSError:
73 if not os.path.isdir(self.log_dir):
74 raise
75 print("Logs saved under", log_dir)
76
77 # Create files expected by the Sponge test result parser.
78 self.sponge_log_path = self.create_file("sponge_log", ".log")
79 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
80
David Brazdil623b6812019-09-09 11:41:08 +010081 def gen_file_path(self, basename, extension):
82 """Generate path to a file in the log directory."""
83 return os.path.join(self.log_dir, basename + extension)
84
David Brazdil2df24082019-09-05 11:55:08 +010085 def create_file(self, basename, extension):
86 """Create and touch a new file in the log folder. Ensure that no other
87 file of the same name was created by this instance of ArtifactsManager.
88 """
89 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +010090 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +010091
92 # Check that the path is unique.
93 assert(path not in self.created_files)
94 self.created_files += [ path ]
95
96 # Touch file.
97 with open(path, "w") as f:
98 pass
99
100 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100101
David Brazdil623b6812019-09-09 11:41:08 +0100102 def get_file(self, basename, extension):
103 """Return path to a file in the log folder. Assert that it was created
104 by this instance of ArtifactsManager."""
105 path = self.gen_file_path(basename, extension)
106 assert(path in self.created_files)
107 return path
108
Andrew Scullbc7189d2018-08-14 09:35:13 +0100109
David Brazdil2df24082019-09-05 11:55:08 +0100110# Tuple holding the arguments common to all driver constructors.
111# This is to avoid having to pass arguments from subclasses to superclasses.
112DriverArgs = collections.namedtuple("DriverArgs", [
113 "artifacts",
114 "kernel",
115 "initrd",
116 "vm_args",
117 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100118
Andrew Walbran98656252019-03-14 14:52:29 +0000119
David Brazdil2df24082019-09-05 11:55:08 +0100120# State shared between the common Driver class and its subclasses during
121# a single invocation of the target platform.
122DriverRunState = collections.namedtuple("DriverRunState", [
123 "log_path",
124 ])
Andrew Walbran98656252019-03-14 14:52:29 +0000125
126
David Brazdil2df24082019-09-05 11:55:08 +0100127class Driver:
128 """Parent class of drivers for all testable platforms."""
129
130 def __init__(self, args):
131 self.args = args
132
David Brazdil623b6812019-09-09 11:41:08 +0100133 def get_run_log(self, run_name):
134 """Return path to the main log of a given test run."""
135 return self.args.artifacts.get_file(run_name, ".log")
136
David Brazdil2df24082019-09-05 11:55:08 +0100137 def start_run(self, run_name):
138 """Hook called by Driver subclasses before they invoke the target
139 platform."""
140 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
141
142 def exec_logged(self, run_state, exec_args):
143 """Run a subprocess on behalf of a Driver subclass and append its
144 stdout and stderr to the main log."""
145 with open(run_state.log_path, "a") as f:
146 f.write("$ {}\r\n".format(" ".join(exec_args)))
147 f.flush()
148 return subprocess.call(exec_args, stdout=f, stderr=f)
149
150 def finish_run(self, run_state, ret_code):
151 """Hook called by Driver subclasses after they finished running the
152 target platform. `ret_code` argument is the return code of the main
153 command run by the driver. A corresponding log message is printed."""
154 # Decode return code and add a message to the log.
155 with open(run_state.log_path, "a") as f:
156 if ret_code == 124:
157 f.write("\r\n{}{} timed out\r\n".format(
158 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
159 elif ret_code != 0:
160 f.write("\r\n{}{} process return code {}\r\n".format(
161 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX, ret_code))
162
163 # Append log of this run to full test log.
164 log_content = read_file(run_state.log_path)
165 append_file(
166 self.args.artifacts.sponge_log_path,
167 log_content + "\r\n\r\n")
168 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000169
170
David Brazdil2df24082019-09-05 11:55:08 +0100171class QemuDriver(Driver):
172 """Driver which runs tests in QEMU."""
173
174 def __init__(self, args):
175 Driver.__init__(self, args)
176
177 def gen_exec_args(self, test_args):
178 """Generate command line arguments for QEMU."""
179 exec_args = [
180 "timeout", "--foreground", "10s",
181 "./prebuilts/linux-x64/qemu/qemu-system-aarch64",
182 "-M", "virt,gic_version=3",
183 "-cpu", "cortex-a57", "-smp", "4", "-m", "64M",
184 "-machine", "virtualization=true",
185 "-nographic", "-nodefaults", "-serial", "stdio",
186 "-kernel", self.args.kernel,
187 ]
188
189 if self.args.initrd:
190 exec_args += ["-initrd", self.args.initrd]
191
192 vm_args = join_if_not_None(self.args.vm_args, test_args)
193 if vm_args:
194 exec_args += ["-append", vm_args]
195
196 return exec_args
197
198 def run(self, run_name, test_args):
199 """Run test given by `test_args` in QEMU."""
200 run_state = self.start_run(run_name)
201 ret_code = self.exec_logged(run_state, self.gen_exec_args(test_args))
202 return self.finish_run(run_state, ret_code)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100203
204
David Brazdil2df24082019-09-05 11:55:08 +0100205class FvpDriver(Driver):
206 """Driver which runs tests in ARM FVP emulator."""
207
208 def __init__(self, args):
209 Driver.__init__(self, args)
210
211 def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
212 """Create a DeviceTree source which will be compiled into a DTB and
213 passed to FVP for a test run."""
214 vm_args = join_if_not_None(self.args.vm_args, test_args)
215 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
216 append_file(dts_path, """
217 / {{
218 chosen {{
219 bootargs = "{}";
220 stdout-path = "serial0:115200n8";
221 linux,initrd-start = <{}>;
222 linux,initrd-end = <{}>;
223 }};
224 }};
225 """.format(vm_args, initrd_start, initrd_end))
226
227 def gen_fvp_args(
228 self, initrd_start, uart0_log_path, uart1_log_path, dtb_path):
229 """Generate command line arguments for FVP."""
230 fvp_args = [
231 "timeout", "--foreground", "40s",
232 FVP_BINARY,
233 "-C", "pctl.startup=0.0.0.0",
234 "-C", "bp.secure_memory=0",
235 "-C", "cluster0.NUM_CORES=4",
236 "-C", "cluster1.NUM_CORES=4",
237 "-C", "cache_state_modelled=0",
238 "-C", "bp.vis.disable_visualisation=true",
239 "-C", "bp.vis.rate_limit-enable=false",
240 "-C", "bp.terminal_0.start_telnet=false",
241 "-C", "bp.terminal_1.start_telnet=false",
242 "-C", "bp.terminal_2.start_telnet=false",
243 "-C", "bp.terminal_3.start_telnet=false",
244 "-C", "bp.pl011_uart0.untimed_fifos=1",
245 "-C", "bp.pl011_uart0.unbuffered_output=1",
246 "-C", "bp.pl011_uart0.out_file=" + uart0_log_path,
247 "-C", "bp.pl011_uart1.out_file=" + uart1_log_path,
248 "-C", "cluster0.cpu0.RVBAR=0x04020000",
249 "-C", "cluster0.cpu1.RVBAR=0x04020000",
250 "-C", "cluster0.cpu2.RVBAR=0x04020000",
251 "-C", "cluster0.cpu3.RVBAR=0x04020000",
252 "-C", "cluster1.cpu0.RVBAR=0x04020000",
253 "-C", "cluster1.cpu1.RVBAR=0x04020000",
254 "-C", "cluster1.cpu2.RVBAR=0x04020000",
255 "-C", "cluster1.cpu3.RVBAR=0x04020000",
256 "--data", "cluster0.cpu0=prebuilts/linux-aarch64/arm-trusted-firmware/bl31.bin@0x04020000",
257 "--data", "cluster0.cpu0=" + dtb_path + "@0x82000000",
258 "--data", "cluster0.cpu0=" + self.args.kernel + "@0x80000000",
259 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
260 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
261 ]
262
263 if self.args.initrd:
264 fvp_args += [
265 "--data",
266 "cluster0.cpu0={}@{}".format(
267 self.args.initrd, hex(initrd_start))
268 ]
269
270 return fvp_args
271
272 def run(self, run_name, test_args):
273 run_state = self.start_run(run_name)
274
275 dts_path = self.args.artifacts.create_file(run_name, ".dts")
276 dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
277 uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
278 uart1_log_path = self.args.artifacts.create_file(run_name, ".uart1.log")
279
280 initrd_start = 0x84000000
281 if self.args.initrd:
282 initrd_end = initrd_start + os.path.getsize(self.args.initrd)
283 else:
284 initrd_end = 0x85000000 # Default value
285
286 # Create a FDT to pass to FVP.
287 self.gen_dts(dts_path, test_args, initrd_start, initrd_end)
288 dtc_args = [ DTC_SCRIPT, "-i", dts_path, "-o", dtb_path ]
289 self.exec_logged(run_state, dtc_args)
290
291 # Run FVP.
292 fvp_args = self.gen_fvp_args(
293 initrd_start, uart0_log_path, uart1_log_path, dtb_path)
294 ret_code = self.exec_logged(run_state, fvp_args)
295
296 # Append UART0 output to main log.
297 append_file(run_state.log_path, read_file(uart0_log_path))
298
299 return self.finish_run(run_state, ret_code)
300
301
302# Tuple used to return information about the results of running a set of tests.
303TestRunnerResult = collections.namedtuple("TestRunnerResult", [
304 "tests_run",
305 "tests_failed",
306 ])
307
308
309class TestRunner:
310 """Class which communicates with a test platform to obtain a list of
311 available tests and driving their execution."""
312
313 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex):
314 self.artifacts = artifacts
315 self.driver = driver
316 self.image_name = image_name
317
318 self.suite_re = re.compile(suite_regex or ".*")
319 self.test_re = re.compile(test_regex or ".*")
320
321 def extract_hftest_lines(self, raw):
322 """Extract hftest-specific lines from a raw output from an invocation
323 of the test platform."""
324 lines = []
325 for line in raw.splitlines():
326 if line.startswith("VM "):
327 line = line[len("VM 0: "):]
328 if line.startswith(HFTEST_LOG_PREFIX):
329 lines.append(line[len(HFTEST_LOG_PREFIX):])
330 return lines
331
332 def get_test_json(self):
333 """Invoke the test platform and request a JSON of available test and
334 test suites."""
335 out = self.driver.run("json", "json")
336 hf_out = "\n".join(self.extract_hftest_lines(out))
337 try:
338 return json.loads(hf_out)
339 except ValueError as e:
340 print(out)
341 raise e
342
343 def collect_results(self, fn, it, xml_node):
344 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
345 Insert "tests" and "failures" nodes to `xml_node`."""
346 tests_run = 0
347 tests_failed = 0
348 for i in it:
349 sub_result = fn(i)
350 assert(sub_result.tests_run >= sub_result.tests_failed)
351 tests_run += sub_result.tests_run
352 tests_failed += sub_result.tests_failed
353
354 xml_node.set("tests", str(tests_run))
355 xml_node.set("failures", str(tests_failed))
356 return TestRunnerResult(tests_run, tests_failed)
357
358 def is_passed_test(self, test_out):
359 """Parse the output of a test and return True if it passed."""
360 return \
361 len(test_out) > 0 and \
362 test_out[-1] == HFTEST_LOG_FINISHED and \
363 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
364
365 def run_test(self, suite, test, suite_xml):
366 """Invoke the test platform and request to run a given `test` in given
367 `suite`. Create a new XML node with results under `suite_xml`.
368 Test only invoked if it matches the regex given to constructor."""
369 if not self.test_re.match(test):
370 return TestRunnerResult(tests_run=0, tests_failed=0)
371
372 print(" RUN", test)
373 log_name = suite["name"] + "." + test
374
375 test_xml = ET.SubElement(suite_xml, "testcase")
376 test_xml.set("name", test)
377 test_xml.set("classname", suite['name'])
378 test_xml.set("status", "run")
379
380 out = self.extract_hftest_lines(self.driver.run(
381 log_name, "run {} {}".format(suite["name"], test)))
382
383 if self.is_passed_test(out):
384 print(" PASS")
385 return TestRunnerResult(tests_run=1, tests_failed=0)
386 else:
David Brazdil623b6812019-09-09 11:41:08 +0100387 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100388 failure_xml = ET.SubElement(test_xml, "failure")
389 # TODO: set a meaningful message and put log in CDATA
390 failure_xml.set("message", "Test failed")
391 return TestRunnerResult(tests_run=1, tests_failed=1)
392
393 def run_suite(self, suite, xml):
394 """Invoke the test platform and request to run all matching tests in
395 `suite`. Create new XML nodes with results under `xml`.
396 Suite skipped if it does not match the regex given to constructor."""
397 if not self.suite_re.match(suite["name"]):
398 return TestRunnerResult(tests_run=0, tests_failed=0)
399
400 print(" SUITE", suite["name"])
401 suite_xml = ET.SubElement(xml, "testsuite")
402 suite_xml.set("name", suite["name"])
403
404 return self.collect_results(
405 lambda test: self.run_test(suite, test, suite_xml),
406 suite["tests"],
407 suite_xml)
408
409 def run_tests(self):
410 """Run all suites and tests matching regexes given to constructor.
411 Write results to sponge log XML. Return the number of run and failed
412 tests."""
413
414 test_spec = self.get_test_json()
415 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
416
417 xml = ET.Element("testsuites")
418 xml.set("name", self.image_name)
419 xml.set("timestamp", timestamp)
420
421 result = self.collect_results(
422 lambda suite: self.run_suite(suite, xml),
423 test_spec["suites"],
424 xml)
425
426 # Write XML to file.
427 with open(self.artifacts.sponge_xml_path, "w") as f:
428 ET.ElementTree(xml).write(f, encoding='utf-8', xml_declaration=True)
429
430 if result.tests_failed > 0:
431 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
432 "tests failed")
433 elif result.tests_run > 0:
434 print(" PASS: all", result.tests_run, "tests passed")
435
436 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100437
438
439def Main():
440 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000441 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100442 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100443 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100444 parser.add_argument("--out_initrd")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000445 parser.add_argument("--initrd")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100446 parser.add_argument("--suite")
447 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000448 parser.add_argument("--vm_args")
Andrew Walbran98656252019-03-14 14:52:29 +0000449 parser.add_argument("--fvp", type=bool)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100450 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100451
Andrew Scullbc7189d2018-08-14 09:35:13 +0100452 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000453 image = os.path.join(args.out, args.image + ".bin")
454 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100455 image_name = args.image
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000456 if args.initrd:
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100457 initrd = os.path.join(args.out_initrd, "obj", args.initrd, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100458 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000459 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100460
461 # Create class which will manage all test artifacts.
462 artifacts = ArtifactsManager(os.path.join(args.log, image_name))
463
464 # Create a driver for the platform we want to test on.
465 driver_args = DriverArgs(artifacts, image, initrd, vm_args)
466 if args.fvp:
467 driver = FvpDriver(driver_args)
468 else:
469 driver = QemuDriver(driver_args)
470
471 # Create class which will drive test execution.
472 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test)
473
474 # Run tests.
475 runner_result = runner.run_tests()
476
477 # Print error message if no tests were run as this is probably unexpected.
478 # Return suitable error code.
479 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100480 print("Error: no tests match")
481 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100482 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100483 return 1
484 else:
David Brazdil2df24082019-09-05 11:55:08 +0100485 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100486
487if __name__ == "__main__":
488 sys.exit(Main())