blob: 53087c10ea3644f8bf967de2f6219dc99d8cfe76 [file] [log] [blame]
saul-romero-arm1c97ecc2021-04-08 12:09:19 +00001##############################################################################
2
3# Copyright (c) 2021, ARM Limited and Contributors. All rights reserved.
4
5#
6
7# SPDX-License-Identifier: BSD-3-Clause
8
9##############################################################################
10import re
11import yaml
12import argparse
13import os
14import logging
saul-romero-armce968d62021-05-18 15:01:12 +000015import subprocess
16import sys
17import json
18from adaptors.sql.yaml_parser import YAMLParser
19import glob
20
21HTML_TEMPLATE = "html.tar.gz"
saul-romero-arm1c97ecc2021-04-08 12:09:19 +000022
23
24class TCReport(object):
25 """
26 Class definition for objects to build report files in a
27 pipeline stage
28 """
29 STATUS_VALUES = ["PASS", "FAIL", "SKIP"]
30
31 def __init__(self, metadata=None, test_environments=None,
32 test_configuration=None, target=None,
33 test_suites=None, report_file=None):
34 """
35 Constructor for the class. Initialise the report object and loads
36 an existing report(yaml) if defined.
37
38 :param metadata: Initial metadata report object
39 :param test_environments: Initial test environment object
40 :param test_configuration: Initial test configuration object
41 :param target: Initial target object
42 :param test_suites: Initial test suites object
43 :param report_file: If defined then an existing yaml report is loaded
44 as the initial report object
45 """
46 if test_suites is None:
47 test_suites = {}
48 if target is None:
49 target = {}
50 if test_configuration is None:
51 test_configuration = {'test-assets': {}}
52 if test_environments is None:
53 test_environments = {}
54 if metadata is None:
55 metadata = {}
56 self._report_name = "Not-defined"
57 # Define if is a new report or an existing report
58 if report_file:
59 # The structure of the report must follow:
60 # - report name:
61 # {report properties}
62 try:
63 with open(report_file) as f:
saul-romero-armce968d62021-05-18 15:01:12 +000064 full_report = yaml.load(f)
saul-romero-arm1c97ecc2021-04-08 12:09:19 +000065 self._report_name, \
66 self.report = list(full_report.items())[0]
saul-romero-armce968d62021-05-18 15:01:12 +000067 except Exception as ex:
saul-romero-arm1c97ecc2021-04-08 12:09:19 +000068 logging.exception(
69 f"Exception loading existing report '{report_file}'")
saul-romero-armce968d62021-05-18 15:01:12 +000070 raise ex
saul-romero-arm1c97ecc2021-04-08 12:09:19 +000071 else:
72 self.report = {'metadata': metadata,
73 'test-environments': test_environments,
74 'test-config': test_configuration,
75 'target': target,
76 'test-suites': test_suites
77 }
saul-romero-armce968d62021-05-18 15:01:12 +000078 self.report_file = report_file
saul-romero-arm1c97ecc2021-04-08 12:09:19 +000079
80 def dump(self, file_name):
81 """
82 Method that dumps the report object with the report name as key in
83 a yaml format in a given file.
84
85 :param file_name: File name to dump the yaml report
86 :return: Nothing
87 """
88 with open(file_name, 'w') as f:
89 yaml.dump({self._report_name: self.report}, f)
90
91 @property
92 def test_suites(self):
93 return self.report['test-suites']
94
95 @test_suites.setter
96 def test_suites(self, value):
97 self.test_suites = value
98
99 @property
100 def test_environments(self):
101 return self.report['test-environments']
102
103 @test_environments.setter
104 def test_environments(self, value):
105 self.test_environments = value
106
107 @property
108 def test_config(self):
109 return self.report['test-config']
110
111 @test_config.setter
112 def test_config(self, value):
113 self.test_config = value
114
115 def add_test_suite(self, name: str, test_results, metadata=None):
116 """
117 Public method to add a test suite object to a report object.
118
119 :param name: Unique test suite name
120 :param test_results: Object with the tests results
121 :param metadata: Metadata object for the test suite
122 """
123 if metadata is None:
124 metadata = {}
125 if name in self.test_suites:
126 logging.error("Duplicated test suite:{}".format(name))
127 else:
128 self.test_suites[name] = {'test-results': test_results,
129 'metadata': metadata}
130
131 def add_test_environment(self, name: str, values=None):
132 """
133 Public method to add a test environment object to a report object.
134
135 :param name: Name (key) of the test environment object
136 :param values: Object assigned to the test environment object
137 :return: Nothing
138 """
139 if values is None:
140 values = {}
141 self.test_environments[name] = values
142
143 def add_test_asset(self, name: str, values=None):
144 """
145 Public method to add a test asset object to a report object.
146
147 :param name: Name (key) of the test asset object
148 :param values: Object assigned to the test asset object
149 :return: Nothing
150 """
151 if values is None:
152 values = {}
153 if 'test-assets' not in self.test_config:
154 self.test_config['test-assets'] = {}
155 self.test_config['test-assets'][name] = values
156
157 @staticmethod
158 def process_ptest_results(lava_log_string="",
159 results_pattern=r"(?P<status>("
160 r"PASS|FAIL|SKIP)): ("
161 r"?P<id>.+)"):
162 """
163 Method that process ptest-runner results from a lava log string and
164 converts them to a test results object.
165
166 :param lava_log_string: Lava log string
167 :param results_pattern: Regex used to capture the test results
168 :return: Test results object
169 """
170 pattern = re.compile(results_pattern)
171 if 'status' not in pattern.groupindex or \
172 'id' not in pattern.groupindex:
173 raise Exception(
174 "Status and/or id must be defined in the results pattern")
175 results = {}
176 lines = lava_log_string.split("\n")
177 it = iter(lines)
178 stop_found = False
179 for line in it:
180 fields = line.split(" ", 1)
181 if len(fields) > 1 and fields[1] == "START: ptest-runner":
182 for report_line in it:
183 timestamp, *rest = report_line.split(" ", 1)
184 if not rest:
185 continue
186 if rest[0] == "STOP: ptest-runner":
187 stop_found = True
188 break
189 p = pattern.match(rest[0])
190 if p:
saul-romero-armce968d62021-05-18 15:01:12 +0000191 id = re.sub("[ :]+", "_", p.groupdict()['id'])
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000192 status = p.groupdict()['status']
193 if not id:
194 print("Warning: missing 'id'")
195 elif status not in TCReport.STATUS_VALUES:
196 print("Warning: Status unknown")
197 elif id in results:
198 print("Warning: duplicated id")
199 else:
200 metadata = {k: p.groupdict()[k]
201 for k in p.groupdict().keys()
202 if k not in ('id', 'status')}
203 results[id] = {'status': status,
204 'metadata': metadata}
205 break
206 if not stop_found:
207 logger.warning("End of ptest-runner not found")
208 return results
209
210 def parse_fvp_model_version(self, lava_log_string):
211 """
212 Obtains the FVP model and version from a lava log string.
213
214 :param lava_log_string: Lava log string
215 :return: Tuple with FVP model and version
216 """
217 result = re.findall(r"opt/model/(.+) --version", lava_log_string)
218 model = "" if not result else result[0]
219 result = re.findall(r"Fast Models \[(.+?)\]\n", lava_log_string)
220 version = "" if not result else result[0]
221 self.report['target'] = {'platform': model, 'version': version}
222 return model, version
223
224 @property
225 def report_name(self):
226 return self._report_name
227
228 @report_name.setter
229 def report_name(self, value):
230 self._report_name = value
231
232 @property
233 def metadata(self):
234 return self.report['metadata']
235
236 @metadata.setter
237 def metadata(self, metadata):
238 self.report['metadata'] = metadata
239
saul-romero-armce968d62021-05-18 15:01:12 +0000240 @property
241 def target(self):
242 return self.report['target']
243
244 @target.setter
245 def target(self, target):
246 self.report['target'] = target
247
248 def merge_into(self, other):
249 """
250 Merge one report object with this.
251
252 :param other: Report object to be merged to this
253 :return:
254 """
255 try:
256 if not self.report_name or self.report_name == "Not-defined":
257 self.report_name = other.report_name
258 if self.report_name != other.report_name:
259 logging.warning(
260 f'Report name \'{other.report_name}\' does not match '
261 f'original report name')
262 # Merge metadata where 'other' report will overwrite common key
263 # values
264 self.metadata.update(other.metadata)
265 self.target.update(other.target)
266 self.test_config['test-assets'].update(other.test_config['test'
267 '-assets'])
268 self.test_environments.update(other.test_environments)
269 self.test_suites.update(other.test_suites)
270 except Exception as ex:
271 logging.exception("Failed to merge reports")
272 raise ex
273
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000274
275class KvDictAppendAction(argparse.Action):
276 """
277 argparse action to split an argument into KEY=VALUE form
278 on the first = and append to a dictionary.
279 """
280
281 def __call__(self, parser, args, values, option_string=None):
282 d = getattr(args, self.dest) or {}
283 for value in values:
284 try:
285 (k, v) = value.split("=", 2)
286 except ValueError as ex:
287 raise \
saul-romero-armce968d62021-05-18 15:01:12 +0000288 argparse.ArgumentError(self,
289 f"Could not parse argument '{values[0]}' as k=v format")
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000290 d[k] = v
291 setattr(args, self.dest, d)
292
293
294def read_metadata(metadata_file):
295 """
296 Function that returns a dictionary object from a KEY=VALUE lines file.
297
298 :param metadata_file: Filename with the KEY=VALUE pairs
299 :return: Dictionary object with key and value pairs
300 """
301 if not metadata_file:
302 return {}
303 with open(metadata_file) as f:
304 d = dict([line.strip().split("=", 1) for line in f])
305 return d
306
307
308def import_env(env_names):
309 """
310 Function that matches a list of regex expressions against all the
311 environment variables keys and returns an object with the matched key
312 and the value of the environment variable.
313
314 :param env_names: List of regex expressions to match env keys
315 :return: Object with the matched env variables
316 """
317 env_list = list(os.environ.keys())
318 keys = []
319 for expression in env_names:
320 r = re.compile(expression)
321 keys = keys + list(filter(r.match, env_list))
322 d = {key: os.environ[key] for key in keys}
323 return d
324
325
326def merge_dicts(*dicts):
327 """
328 Function to merge a list of dictionaries.
329
330 :param dicts: List of dictionaries
331 :return: A merged dictionary
332 """
333 merged = {}
334 for d in dicts:
335 merged.update(d)
336 return merged
337
338
339def process_lava_log(_report, _args):
340 """
341 Function to adapt user arguments to process test results and add properties
342 to the report object.
343
344 :param _report: Report object
345 :param _args: User arguments
346 :return: Nothing
347 """
348 with open(_args.lava_log, "r") as f:
349 lava_log = f.read()
350 # Get the test results
351 results = {}
352 if _args.type == 'ptest-report':
saul-romero-armce968d62021-05-18 15:01:12 +0000353 results_pattern = None
354 suite = _args.suite or _args.test_suite_name
355 if suite == "optee-test":
356 results_pattern = r"(?P<status>(PASS|FAIL|SKIP)): (?P<id>.+ .+) " \
357 r"- (?P<description>.+)"
358 elif suite == "kernel-selftest":
359 results_pattern = r"(?P<status>(PASS|FAIL|SKIP)): (" \
360 r"?P<description>selftests): (?P<id>.+: .+)"
361 else:
362 logging.error(f"Suite type uknown or not defined:'{suite}'")
363 sys.exit(-1)
364
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000365 results = TCReport.process_ptest_results(lava_log,
saul-romero-armce968d62021-05-18 15:01:12 +0000366 results_pattern=results_pattern)
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000367 if _args.report_name:
368 _report.report_name = _args.report_name
369 _report.parse_fvp_model_version(lava_log)
370 metadata = {}
371 if _args.metadata_pairs or _args.metadata_env or _args.metadata_file:
372 metadata = _args.metadata_pairs or import_env(
373 _args.metadata_env) or read_metadata(_args.metadata_file)
374 _report.add_test_suite(_args.test_suite_name, test_results=results,
375 metadata=metadata)
376
377
saul-romero-armce968d62021-05-18 15:01:12 +0000378def merge_reports(reportObj, list_reports):
379 """
380 Function to merge a list of yaml report files into a report object
381
382 :param reportObj: Instance of an initial report object to merge the reports
383 :param list_reports: List of yaml report files or file patterns
384 :return: Updated report object
385 """
386 for report_pattern in list_reports:
387 for report_file in glob.glob(report_pattern):
388 to_merge = TCReport(report_file=report_file)
389 reportObj.merge_into(to_merge)
390 return reportObj
391
392
393def generate_html(report_obj, user_args):
394 """
395 Generate html output for the given report_file
396
397 :param report_obj: report object
398 :param user_args: Arguments from user
399 :return: Nothing
400 """
401 script_path = os.path.dirname(sys.argv[0])
402 report_file = user_args.report
403 try:
404 with open(script_path + "/html/js/reporter.js", "a") as write_file:
405 for key in args.html_output:
406 print(f'\nSetting html var "{key}"...')
407 write_file.write(f"\nlet {key}='{args.html_output[key]}'")
408 j = json.dumps({report_obj.report_name: report_obj.report},
409 indent=4)
410 write_file.write(f"\nlet textReport=`\n{j}\n`")
411 subprocess.run(f'cp -f {report_file} {script_path}/html/report.yaml',
412 shell=True)
413 except subprocess.CalledProcessError as ex:
414 logging.exception("Error at generating html")
415 raise ex
416
417
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000418if __name__ == '__main__':
419 # Defining logger
420 logging.basicConfig(
421 level=logging.INFO,
422 format="%(asctime)s [%(levelname)s] %(message)s",
423 handlers=[
saul-romero-armce968d62021-05-18 15:01:12 +0000424 logging.FileHandler("debug.log"),
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000425 logging.StreamHandler()
426 ])
427 """
428 The main aim of this script is to be called with different options to build
429 a report object that can be dumped into a yaml format
430 """
431 parser = argparse.ArgumentParser(description='Generic yaml report for TC')
432 parser.add_argument("--report", "-r", help="Report filename")
433 parser.add_argument("-f", help="Force new report", action='store_true',
434 dest='new_report')
435 parser.add_argument("command", help="Command: process-results")
436 group_results = parser.add_argument_group("Process results")
437 group_results.add_argument('--test-suite-name', type=str,
438 help='Test suite name')
439 group_results.add_argument('--lava-log', type=str, help='Lava log file')
440 group_results.add_argument('--type', type=str, help='Type of report log',
441 default='ptest-report')
442 group_results.add_argument('--report-name', type=str, help='Report name',
443 default="")
saul-romero-armce968d62021-05-18 15:01:12 +0000444 group_results.add_argument("--suite", required=False,
445 default=None,
446 help="Suite type. If not defined takes the "
447 "suite name value")
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000448 test_env = parser.add_argument_group("Test environments")
449 test_env.add_argument('--test-env-name', type=str,
450 help='Test environment type')
451 test_env.add_argument("--test-env-values",
452 nargs="+",
453 action=KvDictAppendAction,
454 default={},
455 metavar="KEY=VALUE",
456 help="Set a number of key-value pairs "
457 "(do not put spaces before or after the = "
458 "sign). "
459 "If a value contains spaces, you should define "
460 "it with double quotes: "
461 'key="Value with spaces". Note that '
462 "values are always treated as strings.")
463 test_env.add_argument("--test-env-env",
464 nargs="+",
465 default={},
466 help="Import environment variables values with the "
467 "given name.")
468 parser.add_argument("--metadata-pairs",
469 nargs="+",
470 action=KvDictAppendAction,
471 default={},
472 metavar="KEY=VALUE",
473 help="Set a number of key-value pairs "
474 "(do not put spaces before or after the = sign). "
475 "If a value contains spaces, you should define "
476 "it with double quotes: "
477 'key="Value with spaces". Note that '
478 "values are always treated as strings.")
479
480 test_config = parser.add_argument_group("Test config")
481 test_config.add_argument('--test-asset-name', type=str,
482 help='Test asset type')
483 test_config.add_argument("--test-asset-values",
484 nargs="+",
485 action=KvDictAppendAction,
486 default={},
487 metavar="KEY=VALUE",
488 help="Set a number of key-value pairs "
489 "(do not put spaces before or after the = "
490 "sign). "
491 "If a value contains spaces, you should "
492 "define "
493 "it with double quotes: "
494 'key="Value with spaces". Note that '
495 "values are always treated as strings.")
496 test_config.add_argument("--test-asset-env",
497 nargs="+",
498 default=None,
499 help="Import environment variables values with "
500 "the given name.")
501
502 parser.add_argument("--metadata-env",
503 nargs="+",
504 default=None,
505 help="Import environment variables values with the "
506 "given name.")
507 parser.add_argument("--metadata-file",
508 type=str,
509 default=None,
510 help="File with key-value pairs lines i.e"
511 "key1=value1\nkey2=value2")
saul-romero-armce968d62021-05-18 15:01:12 +0000512
513 parser.add_argument("--list",
514 nargs="+",
515 default={},
516 help="List of report files.")
517 parser.add_argument("--html-output",
518 required=False,
519 nargs="*",
520 action=KvDictAppendAction,
521 default={},
522 metavar="KEY=VALUE",
523 help="Set a number of key-value pairs i.e. key=value"
524 "(do not put spaces before or after the = "
525 "sign). "
526 "If a value contains spaces, you should define "
527 "it with double quotes: "
528 "Valid keys: title, logo_img, logo_href.")
529 parser.add_argument("--sql-output",
530 required=False,
531 action="store_true",
532 help='Sql output produced from the report file')
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000533
534 args = parser.parse_args()
535 report = None
saul-romero-armce968d62021-05-18 15:01:12 +0000536
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000537 # Check if report exists (that can be overwritten) or is a new report
538 if os.path.exists(args.report) and not args.new_report:
539 report = TCReport(report_file=args.report) # load existing report
540 else:
541 report = TCReport()
542
543 # Possible list of commands:
544 # process-results: To parse test results from stream into a test suite obj
545 if args.command == "process-results":
546 # Requires the test suite name and the log file, lava by the time being
547 if not args.test_suite_name:
548 parser.error("Test suite name required")
549 elif not args.lava_log:
550 parser.error("Lava log file required")
551 process_lava_log(report, args)
552 # set-report-metadata: Set the report's metadata
553 elif args.command == "set-report-metadata":
554 # Various options to load metadata into the report object
555 report.metadata = merge_dicts(args.metadata_pairs,
556 read_metadata(args.metadata_file),
557 import_env(args.metadata_env))
558 # add-test-environment: Add a test environment to the report's object
559 elif args.command == "add-test-environment":
560 # Various options to load environment data into the report object
561 report.add_test_environment(args.test_env_name,
562 merge_dicts(args.test_env_values,
563 import_env(args.test_env_env)))
564 # add-test-asset: Add a test asset into the report's object (test-config)
565 elif args.command == "add-test-asset":
566 report.add_test_asset(args.test_asset_name,
567 merge_dicts(args.test_asset_values,
568 import_env(args.test_asset_env)))
saul-romero-armce968d62021-05-18 15:01:12 +0000569 elif args.command == "merge-reports":
570 report = merge_reports(report, args.list)
saul-romero-arm1c97ecc2021-04-08 12:09:19 +0000571 report.dump(args.report)
saul-romero-armce968d62021-05-18 15:01:12 +0000572 if args.html_output:
573 generate_html(report, args)
574
575 if args.sql_output:
576 yaml_obj = YAMLParser(args.report)
577 yaml_obj.create_table()
578 yaml_obj.parse_file()
579 yaml_obj.update_test_config_table()