blob: 99699b7434882c5420c457714d9de655dcaabbff [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
81 def create_file(self, basename, extension):
82 """Create and touch a new file in the log folder. Ensure that no other
83 file of the same name was created by this instance of ArtifactsManager.
84 """
85 # Determine the path of the file.
86 path = os.path.join(self.log_dir, basename + extension)
87
88 # Check that the path is unique.
89 assert(path not in self.created_files)
90 self.created_files += [ path ]
91
92 # Touch file.
93 with open(path, "w") as f:
94 pass
95
96 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +010097
98
David Brazdil2df24082019-09-05 11:55:08 +010099# Tuple holding the arguments common to all driver constructors.
100# This is to avoid having to pass arguments from subclasses to superclasses.
101DriverArgs = collections.namedtuple("DriverArgs", [
102 "artifacts",
103 "kernel",
104 "initrd",
105 "vm_args",
106 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100107
Andrew Walbran98656252019-03-14 14:52:29 +0000108
David Brazdil2df24082019-09-05 11:55:08 +0100109# State shared between the common Driver class and its subclasses during
110# a single invocation of the target platform.
111DriverRunState = collections.namedtuple("DriverRunState", [
112 "log_path",
113 ])
Andrew Walbran98656252019-03-14 14:52:29 +0000114
115
David Brazdil2df24082019-09-05 11:55:08 +0100116class Driver:
117 """Parent class of drivers for all testable platforms."""
118
119 def __init__(self, args):
120 self.args = args
121
122 def start_run(self, run_name):
123 """Hook called by Driver subclasses before they invoke the target
124 platform."""
125 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
126
127 def exec_logged(self, run_state, exec_args):
128 """Run a subprocess on behalf of a Driver subclass and append its
129 stdout and stderr to the main log."""
130 with open(run_state.log_path, "a") as f:
131 f.write("$ {}\r\n".format(" ".join(exec_args)))
132 f.flush()
133 return subprocess.call(exec_args, stdout=f, stderr=f)
134
135 def finish_run(self, run_state, ret_code):
136 """Hook called by Driver subclasses after they finished running the
137 target platform. `ret_code` argument is the return code of the main
138 command run by the driver. A corresponding log message is printed."""
139 # Decode return code and add a message to the log.
140 with open(run_state.log_path, "a") as f:
141 if ret_code == 124:
142 f.write("\r\n{}{} timed out\r\n".format(
143 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
144 elif ret_code != 0:
145 f.write("\r\n{}{} process return code {}\r\n".format(
146 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX, ret_code))
147
148 # Append log of this run to full test log.
149 log_content = read_file(run_state.log_path)
150 append_file(
151 self.args.artifacts.sponge_log_path,
152 log_content + "\r\n\r\n")
153 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000154
155
David Brazdil2df24082019-09-05 11:55:08 +0100156class QemuDriver(Driver):
157 """Driver which runs tests in QEMU."""
158
159 def __init__(self, args):
160 Driver.__init__(self, args)
161
162 def gen_exec_args(self, test_args):
163 """Generate command line arguments for QEMU."""
164 exec_args = [
165 "timeout", "--foreground", "10s",
166 "./prebuilts/linux-x64/qemu/qemu-system-aarch64",
167 "-M", "virt,gic_version=3",
168 "-cpu", "cortex-a57", "-smp", "4", "-m", "64M",
169 "-machine", "virtualization=true",
170 "-nographic", "-nodefaults", "-serial", "stdio",
171 "-kernel", self.args.kernel,
172 ]
173
174 if self.args.initrd:
175 exec_args += ["-initrd", self.args.initrd]
176
177 vm_args = join_if_not_None(self.args.vm_args, test_args)
178 if vm_args:
179 exec_args += ["-append", vm_args]
180
181 return exec_args
182
183 def run(self, run_name, test_args):
184 """Run test given by `test_args` in QEMU."""
185 run_state = self.start_run(run_name)
186 ret_code = self.exec_logged(run_state, self.gen_exec_args(test_args))
187 return self.finish_run(run_state, ret_code)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100188
189
David Brazdil2df24082019-09-05 11:55:08 +0100190class FvpDriver(Driver):
191 """Driver which runs tests in ARM FVP emulator."""
192
193 def __init__(self, args):
194 Driver.__init__(self, args)
195
196 def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
197 """Create a DeviceTree source which will be compiled into a DTB and
198 passed to FVP for a test run."""
199 vm_args = join_if_not_None(self.args.vm_args, test_args)
200 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
201 append_file(dts_path, """
202 / {{
203 chosen {{
204 bootargs = "{}";
205 stdout-path = "serial0:115200n8";
206 linux,initrd-start = <{}>;
207 linux,initrd-end = <{}>;
208 }};
209 }};
210 """.format(vm_args, initrd_start, initrd_end))
211
212 def gen_fvp_args(
213 self, initrd_start, uart0_log_path, uart1_log_path, dtb_path):
214 """Generate command line arguments for FVP."""
215 fvp_args = [
216 "timeout", "--foreground", "40s",
217 FVP_BINARY,
218 "-C", "pctl.startup=0.0.0.0",
219 "-C", "bp.secure_memory=0",
220 "-C", "cluster0.NUM_CORES=4",
221 "-C", "cluster1.NUM_CORES=4",
222 "-C", "cache_state_modelled=0",
223 "-C", "bp.vis.disable_visualisation=true",
224 "-C", "bp.vis.rate_limit-enable=false",
225 "-C", "bp.terminal_0.start_telnet=false",
226 "-C", "bp.terminal_1.start_telnet=false",
227 "-C", "bp.terminal_2.start_telnet=false",
228 "-C", "bp.terminal_3.start_telnet=false",
229 "-C", "bp.pl011_uart0.untimed_fifos=1",
230 "-C", "bp.pl011_uart0.unbuffered_output=1",
231 "-C", "bp.pl011_uart0.out_file=" + uart0_log_path,
232 "-C", "bp.pl011_uart1.out_file=" + uart1_log_path,
233 "-C", "cluster0.cpu0.RVBAR=0x04020000",
234 "-C", "cluster0.cpu1.RVBAR=0x04020000",
235 "-C", "cluster0.cpu2.RVBAR=0x04020000",
236 "-C", "cluster0.cpu3.RVBAR=0x04020000",
237 "-C", "cluster1.cpu0.RVBAR=0x04020000",
238 "-C", "cluster1.cpu1.RVBAR=0x04020000",
239 "-C", "cluster1.cpu2.RVBAR=0x04020000",
240 "-C", "cluster1.cpu3.RVBAR=0x04020000",
241 "--data", "cluster0.cpu0=prebuilts/linux-aarch64/arm-trusted-firmware/bl31.bin@0x04020000",
242 "--data", "cluster0.cpu0=" + dtb_path + "@0x82000000",
243 "--data", "cluster0.cpu0=" + self.args.kernel + "@0x80000000",
244 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
245 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
246 ]
247
248 if self.args.initrd:
249 fvp_args += [
250 "--data",
251 "cluster0.cpu0={}@{}".format(
252 self.args.initrd, hex(initrd_start))
253 ]
254
255 return fvp_args
256
257 def run(self, run_name, test_args):
258 run_state = self.start_run(run_name)
259
260 dts_path = self.args.artifacts.create_file(run_name, ".dts")
261 dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
262 uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
263 uart1_log_path = self.args.artifacts.create_file(run_name, ".uart1.log")
264
265 initrd_start = 0x84000000
266 if self.args.initrd:
267 initrd_end = initrd_start + os.path.getsize(self.args.initrd)
268 else:
269 initrd_end = 0x85000000 # Default value
270
271 # Create a FDT to pass to FVP.
272 self.gen_dts(dts_path, test_args, initrd_start, initrd_end)
273 dtc_args = [ DTC_SCRIPT, "-i", dts_path, "-o", dtb_path ]
274 self.exec_logged(run_state, dtc_args)
275
276 # Run FVP.
277 fvp_args = self.gen_fvp_args(
278 initrd_start, uart0_log_path, uart1_log_path, dtb_path)
279 ret_code = self.exec_logged(run_state, fvp_args)
280
281 # Append UART0 output to main log.
282 append_file(run_state.log_path, read_file(uart0_log_path))
283
284 return self.finish_run(run_state, ret_code)
285
286
287# Tuple used to return information about the results of running a set of tests.
288TestRunnerResult = collections.namedtuple("TestRunnerResult", [
289 "tests_run",
290 "tests_failed",
291 ])
292
293
294class TestRunner:
295 """Class which communicates with a test platform to obtain a list of
296 available tests and driving their execution."""
297
298 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex):
299 self.artifacts = artifacts
300 self.driver = driver
301 self.image_name = image_name
302
303 self.suite_re = re.compile(suite_regex or ".*")
304 self.test_re = re.compile(test_regex or ".*")
305
306 def extract_hftest_lines(self, raw):
307 """Extract hftest-specific lines from a raw output from an invocation
308 of the test platform."""
309 lines = []
310 for line in raw.splitlines():
311 if line.startswith("VM "):
312 line = line[len("VM 0: "):]
313 if line.startswith(HFTEST_LOG_PREFIX):
314 lines.append(line[len(HFTEST_LOG_PREFIX):])
315 return lines
316
317 def get_test_json(self):
318 """Invoke the test platform and request a JSON of available test and
319 test suites."""
320 out = self.driver.run("json", "json")
321 hf_out = "\n".join(self.extract_hftest_lines(out))
322 try:
323 return json.loads(hf_out)
324 except ValueError as e:
325 print(out)
326 raise e
327
328 def collect_results(self, fn, it, xml_node):
329 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
330 Insert "tests" and "failures" nodes to `xml_node`."""
331 tests_run = 0
332 tests_failed = 0
333 for i in it:
334 sub_result = fn(i)
335 assert(sub_result.tests_run >= sub_result.tests_failed)
336 tests_run += sub_result.tests_run
337 tests_failed += sub_result.tests_failed
338
339 xml_node.set("tests", str(tests_run))
340 xml_node.set("failures", str(tests_failed))
341 return TestRunnerResult(tests_run, tests_failed)
342
343 def is_passed_test(self, test_out):
344 """Parse the output of a test and return True if it passed."""
345 return \
346 len(test_out) > 0 and \
347 test_out[-1] == HFTEST_LOG_FINISHED and \
348 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
349
350 def run_test(self, suite, test, suite_xml):
351 """Invoke the test platform and request to run a given `test` in given
352 `suite`. Create a new XML node with results under `suite_xml`.
353 Test only invoked if it matches the regex given to constructor."""
354 if not self.test_re.match(test):
355 return TestRunnerResult(tests_run=0, tests_failed=0)
356
357 print(" RUN", test)
358 log_name = suite["name"] + "." + test
359
360 test_xml = ET.SubElement(suite_xml, "testcase")
361 test_xml.set("name", test)
362 test_xml.set("classname", suite['name'])
363 test_xml.set("status", "run")
364
365 out = self.extract_hftest_lines(self.driver.run(
366 log_name, "run {} {}".format(suite["name"], test)))
367
368 if self.is_passed_test(out):
369 print(" PASS")
370 return TestRunnerResult(tests_run=1, tests_failed=0)
371 else:
372 print("[x] FAIL --", self.driver.file_path(log_name))
373 failure_xml = ET.SubElement(test_xml, "failure")
374 # TODO: set a meaningful message and put log in CDATA
375 failure_xml.set("message", "Test failed")
376 return TestRunnerResult(tests_run=1, tests_failed=1)
377
378 def run_suite(self, suite, xml):
379 """Invoke the test platform and request to run all matching tests in
380 `suite`. Create new XML nodes with results under `xml`.
381 Suite skipped if it does not match the regex given to constructor."""
382 if not self.suite_re.match(suite["name"]):
383 return TestRunnerResult(tests_run=0, tests_failed=0)
384
385 print(" SUITE", suite["name"])
386 suite_xml = ET.SubElement(xml, "testsuite")
387 suite_xml.set("name", suite["name"])
388
389 return self.collect_results(
390 lambda test: self.run_test(suite, test, suite_xml),
391 suite["tests"],
392 suite_xml)
393
394 def run_tests(self):
395 """Run all suites and tests matching regexes given to constructor.
396 Write results to sponge log XML. Return the number of run and failed
397 tests."""
398
399 test_spec = self.get_test_json()
400 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
401
402 xml = ET.Element("testsuites")
403 xml.set("name", self.image_name)
404 xml.set("timestamp", timestamp)
405
406 result = self.collect_results(
407 lambda suite: self.run_suite(suite, xml),
408 test_spec["suites"],
409 xml)
410
411 # Write XML to file.
412 with open(self.artifacts.sponge_xml_path, "w") as f:
413 ET.ElementTree(xml).write(f, encoding='utf-8', xml_declaration=True)
414
415 if result.tests_failed > 0:
416 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
417 "tests failed")
418 elif result.tests_run > 0:
419 print(" PASS: all", result.tests_run, "tests passed")
420
421 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100422
423
424def Main():
425 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000426 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100427 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100428 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100429 parser.add_argument("--out_initrd")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000430 parser.add_argument("--initrd")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100431 parser.add_argument("--suite")
432 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000433 parser.add_argument("--vm_args")
Andrew Walbran98656252019-03-14 14:52:29 +0000434 parser.add_argument("--fvp", type=bool)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100435 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100436
Andrew Scullbc7189d2018-08-14 09:35:13 +0100437 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000438 image = os.path.join(args.out, args.image + ".bin")
439 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100440 image_name = args.image
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000441 if args.initrd:
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100442 initrd = os.path.join(args.out_initrd, "obj", args.initrd, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100443 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000444 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100445
446 # Create class which will manage all test artifacts.
447 artifacts = ArtifactsManager(os.path.join(args.log, image_name))
448
449 # Create a driver for the platform we want to test on.
450 driver_args = DriverArgs(artifacts, image, initrd, vm_args)
451 if args.fvp:
452 driver = FvpDriver(driver_args)
453 else:
454 driver = QemuDriver(driver_args)
455
456 # Create class which will drive test execution.
457 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test)
458
459 # Run tests.
460 runner_result = runner.run_tests()
461
462 # Print error message if no tests were run as this is probably unexpected.
463 # Return suitable error code.
464 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100465 print("Error: no tests match")
466 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100467 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100468 return 1
469 else:
David Brazdil2df24082019-09-05 11:55:08 +0100470 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100471
472if __name__ == "__main__":
473 sys.exit(Main())