blob: 364274405b1bf6f17cfc9ae885deca6c60042a8e [file] [log] [blame]
Minos Galanakisea421232019-06-20 17:11:28 +01001#!/usr/bin/env python3
2
3""" report_parser.py:
4
5 Report parser parses openci json reports and conveys the invormation in a
6 one or more standard formats (To be implememented)
7
8 After all information is captured it validates the success/failure status
9 and can change the script exit code for intergration with standard CI
10 executors.
11 """
12
13from __future__ import print_function
14
15__copyright__ = """
16/*
17 * Copyright (c) 2018-2019, Arm Limited. All rights reserved.
18 *
19 * SPDX-License-Identifier: BSD-3-Clause
20 *
21 */
22 """
23__author__ = "Minos Galanakis"
24__email__ = "minos.galanakis@linaro.org"
25__project__ = "Trusted Firmware-M Open CI"
26__status__ = "stable"
27__version__ = "1.1"
28
29
30import os
31import re
32import sys
33import json
34import argparse
35from pprint import pprint
36
37try:
38 from tfm_ci_pylib.utils import load_json, get_local_git_info, \
39 save_json, list_subdirs, get_remote_git_info, \
40 convert_git_ref_path, xml_read
41except ImportError:
42 dir_path = os.path.dirname(os.path.realpath(__file__))
43 sys.path.append(os.path.join(dir_path, "../"))
44
45 from tfm_ci_pylib.utils import load_json, get_local_git_info, \
46 save_json, list_subdirs, get_remote_git_info, \
47 convert_git_ref_path, xml_read
48
49
50def split_keys(joint_arg, sep="="):
51 """ Split two keys spread by a separator, and return them as a tuple
52 with whitespace removed """
53
54 keys = joint_arg.split(sep)
55
56 # Remove whitespace
57 keys = map(str.strip, list(keys))
58 # If key contains the word True/False convert it.
59 keys = list(map(lambda x:
60 eval(x.title()) if x.lower() in ["true", "false"] else x,
61 keys))
62 return keys
63
64
65def dependencies_mdt_collect(path_list,
66 out_f=None,
Tamas Ban681834a2019-12-02 11:05:03 +000067 expected_paths=["mbedcrypto",
Minos Galanakisea421232019-06-20 17:11:28 +010068 "cmsis",
69 "checkpatch"]):
70 """ Collect dependencies checkout metadata. It creates a json report which
71 can be optionally exported to a file """
72
73 cpaths = {k: v for k, v in [n.split("=") for n in path_list]}
74 cwd = os.path.abspath(os.getcwd())
75
76 # Create an empty dataset
77 data = {n: {} for n in set(expected_paths).union(set(cpaths.keys()))}
78
79 # Perform basic sanity check
80 if not set(data.keys()).issubset(set(cpaths.keys())):
81 err_msg = "Error locating required paths.\nNeeded: %s\nHas: %s" % (
82 ",".join(data.keys()), ",".join(cpaths.keys())
83 )
84 print(err_msg)
85 raise Exception(err_msg)
86
Minos Galanakisea421232019-06-20 17:11:28 +010087 for d in list_subdirs(cpaths["mbedcrypto"]):
88 print("mbed-crypto dir: ", d)
89 # if checkout directory name contains a git reference convert to short
90 d = convert_git_ref_path(d)
91
92 git_info = get_local_git_info(d)
93 tag = os.path.split(git_info["dir"])[-1].split("-")[-1]
94
95 # Absolute paths will not work in jenkins since it will change the
96 # workspaace directory between stages convert to relative path
97 git_info["dir"] = os.path.relpath(git_info["dir"], cwd)
98 data["mbedcrypto"][tag] = git_info
99
100 for d in list_subdirs(cpaths["cmsis"]):
101 print("CMS subdir: ", d)
102 d = convert_git_ref_path(d)
103 git_info = get_local_git_info(d)
104 tag = os.path.split(git_info["dir"])[-1]
105
106 # Absolute paths will not work in jenkins since it will change the
107 # workspaace directory between stages convert to relative path
108 git_info["dir"] = os.path.relpath(git_info["dir"], cwd)
109 data["cmsis"][tag] = git_info
110
111 if "fastmodel" in cpaths:
112 for d in list_subdirs(cpaths["fastmodel"]):
113 print("Fastmodel subdir:", d)
114 json_info = load_json(os.path.join(d, "version.info"))
115 json_info["dir"] = os.path.relpath(d, cwd)
116
117 tag = json_info["version"]
118 # Absolute paths will not work in jenkins since it will change the
119 # workspaace directory between stages convert to relative path
120 data["fastmodel"][tag] = json_info
121
122 for d in list_subdirs(cpaths["checkpatch"]):
123 print("Checkpatch subdir:", d)
124
125 with open(os.path.join(d, "version.info"), "r") as F:
126 url = F.readline().strip()
127
128 git_info = get_remote_git_info(url)
129 d = convert_git_ref_path(d)
130 git_info['dir'] = d
131 tag = os.path.split(git_info["dir"])[-1].split("_")[-1]
132
133 # Absolute paths will not work in jenkins since it will change the
134 # workspaace directory between stages convert to relative path
135 git_info["dir"] = os.path.relpath(git_info["dir"], cwd)
136 data["checkpatch"][tag] = git_info
137 if "fpga" in cpaths:
138 for d in os.listdir(cpaths["fpga"]):
139 print("FPGA imagefile:", d)
140 if ".tar.gz" in d:
141 name = d.split(".tar.gz")[0]
142 platform, subsys, ver = name.split("_")
143 data["fpga"][name] = {"platform": platform,
144 "subsys": subsys,
145 "version": ver,
146 "recovery": os.path.join(cpaths["fpga"],
147 d)}
148 if out_f:
149 print("Exporting metadata to", out_f)
150 save_json(out_f, data)
151 else:
152 pprint(data)
153
154
155def cppcheck_mdt_collect(file_list, out_f=None):
156 """ XML parse multiple cppcheck output files and create a json report """
157
158 xml_files = list(map(os.path.abspath, file_list))
159
160 dict_data = []
161 version = None
162 for xf in xml_files:
163 data = xml_read(xf)
164
165 version = data["results"]["cppcheck"]["@version"]
166 # If nothing is found the errors dictionary will be a Nonetype object
167 if data["results"]["errors"] is not None:
168 # Use json to flatten ordered dict
169 str_data = json.dumps(data["results"]["errors"]["error"])
170 # Remove @ prefix on first char of files that cppcheck adds
171 str_data = str_data.replace("@", '')
172
173 # Convert to dict again(xml to json will have added an array)
174 _dt = json.loads(str_data)
175
176 if isinstance(_dt, list):
177 dict_data += _dt
178 # If only one error is foud it will give it as a single item
179 elif isinstance(_dt, dict):
180 dict_data += [_dt]
181 else:
182 print("Ignoring cpp entry %s of type %s" % (_dt, type(_dt)))
183
184 out_data = {"_metadata_": {"cppcheck-version": version},
185 "report": {}}
186
187 for E in dict_data:
188
189 sever = E.pop("severity")
190
191 # Sort it based on serverity
192 try:
193 out_data["report"][sever].append(E)
194 except KeyError:
195 out_data["report"][sever] = [E]
196
197 _errors = 0
198 for msg_sever, msg_sever_entries in out_data["report"].items():
199 out_data["_metadata_"][msg_sever] = str(len(msg_sever_entries))
200 if msg_sever == "error":
201 _errors = len(msg_sever_entries)
202
203 out_data["_metadata_"]["success"] = True if not int(_errors) else False
204
205 if out_f:
206 save_json(out_f, out_data)
207 else:
208 pprint(out_data)
209
210
211def checkpatch_mdt_collect(file_name, out_f=None):
212 """ Regex parse a checpatch output file and create a report """
213
214 out_data = {"_metadata_": {"errors": 0,
215 "warnings": 0,
216 "lines": 0,
217 "success": True},
218 "report": {}
219 }
220 with open(file_name, "r") as F:
221 cpatch_data = F.read().strip()
222
223 # checkpatch will not report anything when no issues are found
224 if len(cpatch_data):
225 stat_rex = re.compile(r'^total: (\d+) errors, '
226 r'(\d+) warnings, (\d+) lines',
227 re.MULTILINE)
228 line_rex = re.compile(r'([\S]+:)\s([\S]+:)\s([\S ]+)\n', re.MULTILINE)
229 ewl = stat_rex.search(cpatch_data)
230 try:
231 _errors, _warnings, _lines = ewl.groups()
232 except Exception as E:
233 print("Exception parsing checkpatch file.", E)
234 # If there is text but not in know format return -1 and fail job
235 _errors = _warnings = _lines = "-1"
236 checkpath_entries = line_rex.findall(cpatch_data)
237
238 for en in checkpath_entries:
239 _file, _line, _ = en[0].split(":")
240 _type, _subtype, _ = en[1].split(":")
241 _msg = en[2]
242
243 out_data["_metadata_"] = {"errors": _errors,
244 "warnings": _warnings,
245 "lines": _lines,
246 "success": True if not int(_errors)
247 else False}
248
249 E = {"id": _subtype,
250 "verbose": _subtype,
251 "msg": _msg,
252 "location": {"file": _file, "line": _line}
253 }
254 try:
255 out_data["report"][_type.lower()].append(E)
256 except KeyError:
257 out_data["report"][_type.lower()] = [E]
258
259 if out_f:
260 save_json(out_f, out_data)
261 else:
262 pprint(out_data)
263
264
265def jenkins_mdt_collect(out_f):
266 """ Collects Jenkins enviroment information and stores
267 it in a key value list """
268
269 # Jenkins environment parameters are always valid
270 jenkins_env_keys = ["BUILD_ID",
271 "BUILD_URL",
272 "JOB_BASE_NAME",
273 "GERRIT_URL",
274 "GERRIT_PROJECT"]
275 # The following Gerrit parameters only exist when
276 # a job is triggered by a web hook
277 gerrit_trigger_keys = ["GERRIT_CHANGE_NUMBER",
278 "GERRIT_CHANGE_SUBJECT",
279 "GERRIT_CHANGE_ID",
280 "GERRIT_PATCHSET_REVISION",
281 "GERRIT_PATCHSET_NUMBER",
282 "GERRIT_REFSPEC",
283 "GERRIT_CHANGE_URL",
284 "GERRIT_BRANCH",
285 "GERRIT_CHANGE_OWNER_EMAIL",
286 "GERRIT_PATCHSET_UPLOADER_EMAIL"]
287
288 # Find as mamny of the variables in environent
289 el = set(os.environ).intersection(set(jenkins_env_keys +
290 gerrit_trigger_keys))
291 # Format it in key:value pairs
292 out_data = {n: os.environ[n] for n in el}
293 if out_f:
294 save_json(out_f, out_data)
295 else:
296 pprint(out_data)
297
298
299def metadata_collect(user_args):
300 """ Logic for information collection during different stages of
301 the build """
302
303 if user_args.dependencies_checkout and user_args.content_paths:
304 dependencies_mdt_collect(user_args.content_paths,
305 user_args.out_f)
306 elif user_args.git_info:
307 git_info = get_local_git_info(os.path.abspath(user_args.git_info))
308
309 if user_args.out_f:
310 save_json(user_args.out_f, git_info)
311 else:
312 pprint(git_info)
313 elif user_args.cppcheck_files:
314 cppcheck_mdt_collect(user_args.cppcheck_files, user_args.out_f)
315 elif user_args.checkpatch_file:
316 checkpatch_mdt_collect(user_args.checkpatch_file, user_args.out_f)
317 elif user_args.jenkins_info:
318 jenkins_mdt_collect(user_args.out_f)
319 else:
320 print("Invalid Metadata collection arguments")
321 print(user_args)
322 sys.exit(1)
323
324
325def collate_report(key_file_list, ouput_f=None, stdout=True):
326 """ Join different types of json formatted reports into one """
327
328 out_data = {"_metadata_": {}, "report": {}}
329 for kf in key_file_list:
330 try:
331 key, fl = kf.split("=")
332 data = load_json(fl)
333 # If data is a standard reprort (metdata-report parse it)
334 if ("_metadata_" in data.keys() and "report" in data.keys()):
335 out_data["_metadata_"][key] = data["_metadata_"]
336 out_data["report"][key] = data["report"]
337 # Else treat it as a raw information passing dataset
338 else:
339 try:
340 out_data["info"][key] = data
341 except KeyError as E:
342 out_data["info"] = {key: data}
343 except Exception as E:
344 print("Exception parsing argument", kf, E)
345 continue
346 if ouput_f:
347 save_json(ouput_f, out_data)
348 elif stdout:
349 pprint(out_data)
350 return out_data
351
352
353def filter_report(key_value_list, input_f, ouput_f):
354 """ Generates a subset of the data contained in
355 input_f, by selecting only the values defined in key_value list """
356
357 try:
358 rep_data = load_json(input_f)
359 except Exception as E:
360 print("Exception parsing ", input_f, E)
361 sys.exit(1)
362
363 out_data = {}
364 for kf in key_value_list:
365 try:
366 tag, value = kf.split("=")
367 # if multiple selection
368 if(",") in value:
369 out_data[tag] = {}
370 for v in value.split(","):
371 data = rep_data[tag][v]
372 out_data[tag][v] = data
373 else:
374 data = rep_data[tag][value]
375 out_data[tag] = {value: data}
376 except Exception as E:
377 print("Could not extract data-set for k: %s v: %s" % (tag, value))
378 print(E)
379 continue
380 if ouput_f:
381 save_json(ouput_f, out_data)
382 else:
383 pprint(out_data)
384
385
386def parse_report(user_args):
387 """ Parse a report and attempt to determine if it is overall successful or
388 not. It will set the script's exit code accordingly """
389
390 # Parse Mode
391 in_rep = load_json(user_args.report)
392 report_eval = None
393
394 # Extract the required condition for evalutation to pass
395 pass_key, pass_val = split_keys(user_args.set_pass)
396
397 print("Evaluation will succeed if \"%s\" is \"%s\"" % (pass_key,
398 pass_val))
399 try:
400 report_eval = in_rep["_metadata_"][pass_key] == pass_val
401 print("Evaluating detected '%s' field in _metaddata_. " % pass_key)
402 except Exception as E:
403 pass
404
405 if report_eval is None:
406 if isinstance(in_rep, dict):
407 # If report contains an overall success field in metadata do not
408 # parse the items
409 in_rep = in_rep["report"]
410 ev_list = in_rep.values()
411 elif isinstance(in_rep, list):
412 ev_list = in_rep
413 else:
414 print("Invalid data type: %s" % type(in_rep))
415 return
416
417 if user_args.onepass:
418 try:
419 report_eval = in_rep[user_args.onepass][pass_key] == pass_val
420 except Exception as e:
421 report_eval = False
422
423 # If every singel field need to be succesfful, invert the check and
424 # look for those who are not
425 elif user_args.allpass:
426 try:
427 if list(filter(lambda x: x[pass_key] != pass_val, ev_list)):
428 pass
429 else:
430 report_eval = True
431 except Exception as e:
432 print(e)
433 report_eval = False
434 else:
435 print("Evaluation condition not set. Please use -a or -o. Launch"
436 "help (-h) for more information")
437
438 print("Evaluation %s" % ("passed" if report_eval else "failed"))
439 if user_args.eif:
440 print("Setting script exit status")
441 sys.exit(0 if report_eval else 1)
442
443
444def main(user_args):
445 """ Main logic """
446
447 # Metadat Collect Mode
448 if user_args.collect:
449 metadata_collect(user_args)
450 return
451 elif user_args.filter_report:
452 filter_report(user_args.filter_report,
453 user_args.report,
454 user_args.out_f)
455 elif user_args.collate_report:
456 collate_report(user_args.collate_report, user_args.out_f)
457 else:
458 parse_report(user_args)
459
460
461def get_cmd_args():
462 """ Parse command line arguments """
463
464 # Parse command line arguments to override config
465 parser = argparse.ArgumentParser(description="TFM Report Parser.")
466 parser.add_argument("-e", "--error_if_failed",
467 dest="eif",
468 action="store_true",
469 help="If set will change the script exit code")
470 parser.add_argument("-s", "--set-success-field",
471 dest="set_pass",
472 default="status = Success",
473 action="store",
474 help="Set the key which the script will use to"
475 "assert success/failure")
476 parser.add_argument("-a", "--all-fields-must-pass",
477 dest="allpass",
478 action="store_true",
479 help="When set and a list is provided, all entries"
480 "must be succefull for evaluation to pass")
481 parser.add_argument("-o", "--one-field-must-pass",
482 dest="onepass",
483 action="store",
484 help="Only the user defined field must pass")
485 parser.add_argument("-r", "--report",
486 dest="report",
487 action="store",
488 help="JSON file containing input report")
489 parser.add_argument("-c", "--collect",
490 dest="collect",
491 action="store_true",
492 help="When set, the parser will attempt to collect"
493 "information and produce a report")
494 parser.add_argument("-d", "--dependencies-checkout",
495 dest="dependencies_checkout",
496 action="store_true",
497 help="Collect information from a dependencies "
498 "checkout job")
499 parser.add_argument("-f", "--output-file",
500 dest="out_f",
501 action="store",
502 help="Output file to store captured information")
503 parser.add_argument('-p', '--content-paths',
504 dest="content_paths",
505 nargs='*',
506 help=("Pass a space separated list of paths in the"
507 "following format: -p mbedtls=/yourpath/"
508 "fpv=/another/path .Used in conjuction with -n"))
509 parser.add_argument("-g", "--git-info",
510 dest="git_info",
511 action="store",
512 help="Extract git information from given path. "
513 "Requires --colect directive. Optional parameter"
514 "--output-file ")
515 parser.add_argument("-x", "--cpp-check-xml",
516 dest="cppcheck_files",
517 nargs='*',
518 action="store",
519 help="Extract cppcheck static analysis information "
520 " output files, provided as a space separated "
521 "list. Requires --colect directive."
522 " Optional parameter --output-file ")
523 parser.add_argument("-z", "--checkpatch-parse-f",
524 dest="checkpatch_file",
525 action="store",
526 help="Extract checkpatch static analysis information "
527 " output file. Requires --colect directive."
528 " Optional parameter --output-file ")
529 parser.add_argument("-j", "--jenkins-info",
530 dest="jenkins_info",
531 action="store_true",
532 help="Extract jenkings and gerrit trigger enviroment "
533 "information fr. Requires --colect directive."
534 " Optional parameter --output-file ")
535 parser.add_argument("-l", "--collate-report",
536 dest="collate_report",
537 action="store",
538 nargs='*',
539 help="Pass a space separated list of key-value pairs"
540 "following format: -l report_key_0=report_file_0"
541 " report_key_1=report_file_1. Collate will "
542 "generate a joint dataset and print it to stdout."
543 "Optional parameter --output-file ")
544 parser.add_argument("-t", "--filter-report",
545 dest="filter_report",
546 action="store",
547 nargs='*',
548 help="Requires --report parameter for input file."
549 "Pass a space separated list of key-value pairs"
550 "following format: -l report_key_0=value_0"
551 " report_key_1=value_0. Filter will remote all"
552 "entries of the original report but the ones"
553 "mathing the key:value pairs defined and print it"
554 "to stdout.Optional parameter --output-file")
555 return parser.parse_args()
556
557
558if __name__ == "__main__":
559 main(get_cmd_args())