blob: da010f32cee14ecc9dfbf738206ab0893411c1ab [file] [log] [blame]
Fathi Boudra422bf772019-12-02 11:10:16 +02001#!/usr/bin/env python3
2#
Leonardo Sandoval579c7372020-10-23 15:23:32 -05003# Copyright (c) 2019-2020 Arm Limited. All rights reserved.
Fathi Boudra422bf772019-12-02 11:10:16 +02004#
5# SPDX-License-Identifier: BSD-3-Clause
6#
7
8# Generate a test report from data inferred from Jenkins environment. The
9# generated HTML file is meant for inclusion in the report status page,
10# therefore isn't standalone, fully-formed, HTML.
11
12import argparse
13import collections
14import json
15import io
16import os
17import re
18import shutil
19import sys
20import urllib.request
21
22PAGE_HEADER = """\
23<div id="tf-report-main">
24<table>
25"""
26
27PAGE_FOOTER = """\
28</tbody>
29</table>
30</div> <!-- tf-report-main -->
31
32<table id="tf-rebuild-table"><tbody>
33<tr><td colspan="2" class="select-row">
34 Select tests by result:
35 <span class="select-all">None</span>
36 &nbsp;|&nbsp;
37 <span class="select-all success">SUCCESS</span>
38 &nbsp;|&nbsp;
39 <span class="select-all unstable">UNSTABLE</span>
40 &nbsp;|&nbsp;
41 <span class="select-all failure">FAILURE</span>
42</td></tr>
43<tr>
44 <td class="desc-col">
45 Select build configurations, and click the button to re-trigger builds.
46 <br />
47 Use <b>Shift+Click</b> to alter parameters when re-triggering.
48 </td>
49 <td class="button-col">
50 <input id="tf-rebuild-button" type="button" value="Rebuild selected configs"
51 disabled count="0"/>
52 <input id="tf-rebuild-all-button" type="button" value="Rebuild this job"/>
53 </td>
54</tr>
55</tbody></table>
56
57<div class="tf-label-container">
58<div class="tf-label-label">&nbsp;Local commands&nbsp;</div>
59<pre class="tf-label-cotent" id="tf-selected-commands">
60<i>Hover over test results to display equivalent local commands.</i>
61</pre>
62</div> <!-- tf-label-container -->
63
64<iframe id="tf-rebuild-frame" style="display: none"></iframe>
65"""
66
67TEST_SUFFIX = ".test"
68REPORT = "report.html"
69REPORT_JSON = "report.json"
70
71# Maximum depth for the tree of results, excluding status
Edward Potapova8a32cd2025-06-25 10:42:35 -050072MAX_RESULTS_DEPTH = 8
Fathi Boudra422bf772019-12-02 11:10:16 +020073
74# We'd have a minimum of 3: group, a build config, a run config.
75MIN_RESULTS_DEPTH = 3
76
77# Table header corresponding to each level, starting from group. Note that
78# the result is held in the leaf node itself, and has to appear in a column of
79# its own.
80LEVEL_HEADERS = [
81 "Test Group",
82 "TF Build Config",
83 "TFTF Build Config",
Manish Pandeyc4a9b4d2021-02-10 18:32:33 +000084 "SPM Build Config",
Manish V Badarkhe3b7722c2025-04-10 15:50:11 +010085 "RMM Build Config",
Edward Potapova8a32cd2025-06-25 10:42:35 -050086 "TFUT Build Config",
Fathi Boudra422bf772019-12-02 11:10:16 +020087 "Run Config",
Edward Potapova8a32cd2025-06-25 10:42:35 -050088 "TFUT Run Config",
Fathi Boudra422bf772019-12-02 11:10:16 +020089 "Status"
90]
91
92Jenkins = None
93Dimmed_hypen = None
94Build_job = None
95Job = None
96
97# Indicates whether a level of table has no entries. Assume all levels are empty
98# to start; and flip that around as and when we see otherwise.
99Level_empty = [True] * MAX_RESULTS_DEPTH
100assert len(LEVEL_HEADERS) == (MAX_RESULTS_DEPTH + 1)
101
102# A column is deemed empty if it's content is empty or is the string "nil"
103is_empty = lambda key: key in ("", "nil")
104
105# A tree of ResultNodes are used to group test results by config. The tree is
106# MAX_RESULTS_DEPTH levels deep. Levels above MAX_RESULTS_DEPTH groups results,
107# where as those at MAX_RESULTS_DEPTH (leaves) hold test result and other meta
108# data.
109class ResultNode:
110 def __init__(self, depth=0):
111 self.depth = depth
112 self.printed = False
113 if depth == MAX_RESULTS_DEPTH:
114 self.result = None
115 self.build_number = None
116 self.desc = None
117 else:
118 self.num_children = 0
119 self.children = collections.OrderedDict()
120
121 # For a grouping node, set child by key.
122 def set_child(self, key):
123 assert self.depth < MAX_RESULTS_DEPTH
124
125 self.num_children += 1
126 if not is_empty(key):
127 Level_empty[self.depth] = False
128 return self.children.setdefault(key, ResultNode(self.depth + 1))
129
130 # For a leaf node, set result and other meta data.
131 def set_result(self, result, build_number):
132 assert self.depth == MAX_RESULTS_DEPTH
133
134 self.result = result
135 self.build_number = build_number
136
137 def set_desc(self, desc):
138 self.desc = desc
139
140 def get_desc(self):
141 return self.desc
142
143 # For a grouping node, return dictionary iterator.
144 def items(self):
145 assert self.depth < MAX_RESULTS_DEPTH
146
147 return self.children.items()
148
149 # Generator function that walks through test results. The output of
150 # iteration is reflected in the stack argument, which ought to be a deque.
151 def iterator(self, key, stack):
152 stack.append((key, self))
153 if self.depth < MAX_RESULTS_DEPTH:
154 for child_key, child in self.items():
155 yield from child.iterator(child_key, stack)
156 else:
157 yield
158 stack.pop()
159
160 # Convenient child access during debugging.
161 def __getitem__(self, key):
162 assert self.depth < MAX_RESULTS_DEPTH
163
164 return self.children[key]
165
166 # Print convenient representation for debugging.
167 def __repr__(self):
168 if self.depth < MAX_RESULTS_DEPTH:
169 return "node(depth={}, nc={}, {})".format(self.depth,
170 self.num_children,
171 ("None" if self.children is None else
172 list(self.children.keys())))
173 else:
174 return ("result(" +
175 ("None" if self.result is None else str(self.result)) + ")")
176
177
178# Open an HTML element, given its name, content, and a dictionary of attributes:
179# <name foo="bar"...>
180def open_element(name, attrs=None):
181 # If there are no attributes, return the element right away
182 if attrs is None:
183 return "<" + name + ">"
184
185 el_list = ["<" + name]
186
187 # 'class', being a Python keyword, can't be passed as a keyword argument, so
188 # is passed as 'class_' instead.
189 if "class_" in attrs:
190 attrs["class"] = attrs["class_"]
191 del attrs["class_"]
192
193 for key, val in attrs.items():
194 if val is not None:
195 el_list.append(' {}="{}"'.format(key, val))
196
197 el_list.append(">")
198
199 return "".join(el_list)
200
201
202# Close an HTML element
203def close_element(name):
204 return "</" + name + ">"
205
206
207# Make an HTML element, given its name, content, and a dictionary of attributes:
208# <name foo="bar"...>content</name>
209def make_element(name, content="", **attrs):
210 assert type(content) is str
211
212 return "".join([open_element(name, attrs), content, close_element(name)])
213
214
215# Wrap link in a hyperlink:
216# <a href="link" foo="bar"... target="_blank">content</a>
217def wrap_link(content, link, **attrs):
218 return make_element("a", content, href=link, target="_blank", **attrs)
219
220
221def jenkins_job_link(job, build_number):
222 return "/".join([Jenkins, "job", job, build_number, ""])
223
224
225# Begin table by emitting table headers for all levels that aren't empty, and
226# results column. Finish by opening a tbody element for rest of the table
227# content.
228def begin_table(results, fd):
229 # Iterate and filter out empty levels
230 table_headers = []
231 for level, empty in enumerate(Level_empty):
232 if empty:
233 continue
234 table_headers.append(make_element("th", LEVEL_HEADERS[level]))
235
236 # Result
237 table_headers.append(make_element("th", LEVEL_HEADERS[level + 1]))
238
239 row = make_element("tr", "\n".join(table_headers))
240 print(make_element("thead", row), file=fd)
241 print(open_element("tbody"), file=fd)
242
243
Fathi Boudra422bf772019-12-02 11:10:16 +0200244# Given the node stack, reconstruct the original config name
245def reconstruct_config(node_stack):
246 group = node_stack[0][0]
247 run_config, run_node = node_stack[-1]
248
249 desc = run_node.get_desc()
250 try:
251 with open(desc) as fd:
252 test_config = fd.read().strip()
253 except FileNotFoundError:
254 print("warning: descriptor {} couldn't be opened.".format(desc),
255 file=sys.stderr);
256 return ""
257
258 if group != "GENERATED":
259 return os.path.join(group, test_config)
260 else:
261 return test_config
262
263
264# While iterating results, obtain a trail to the current result. node_stack is
265# iterated to identify the nodes contributing to one result.
266def result_to_html(node_stack):
267 global Dimmed_hypen
268
269 crumbs = []
270 for key, child_node in node_stack:
271 if child_node.printed:
272 continue
273
274 child_node.printed = True
275
276 # If the level is empty, skip emitting this column
277 if not Level_empty[child_node.depth - 1]:
278 # - TF config might be "nil" for TFTF-only build configs;
279 # - TFTF config might not be present for non-TFTF runs;
Fathi Boudra422bf772019-12-02 11:10:16 +0200280 # - All build-only configs have runconfig as "nil";
281 #
282 # Make nil cells empty, and grey empty cells out.
283 if is_empty(key):
284 key = ""
285 td_class = "emptycell"
286 else:
287 td_class = None
288
289 rowspan = None
290 if (child_node.depth < MAX_RESULTS_DEPTH
291 and child_node.num_children > 1):
292 rowspan = child_node.num_children
293
294 # Keys are hyphen-separated strings. For better readability, dim
295 # hyphens so that text around the hyphens stand out.
296 if not Dimmed_hypen:
297 Dimmed_hypen = make_element("span", "-", class_="dim")
298 dimmed_key = Dimmed_hypen.join(key.split("-"))
299
300 crumbs.append(make_element("td", dimmed_key, rowspan=rowspan,
301 class_=td_class))
302
303 # For the last node, print result as well.
304 if child_node.depth == MAX_RESULTS_DEPTH:
305 # Make test result as a link to the job console
306 result_class = child_node.result.lower()
307 job_link = jenkins_job_link(Job, child_node.build_number)
308 result_link = wrap_link(child_node.result, job_link,
309 class_="result")
Leonardo Sandovald6c19d22021-01-21 14:00:55 -0600310 build_job_console_link = job_link + "console"
Fathi Boudra422bf772019-12-02 11:10:16 +0200311
312 # Add selection checkbox
313 selection = make_element("input", type="checkbox")
314
315 # Add link to build console if applicable
316 if build_job_console_link:
317 build_console = wrap_link("", build_job_console_link,
318 class_="buildlink", title="Click to visit build job console")
319 else:
320 build_console = ""
321
322 config_name = reconstruct_config(node_stack)
323
324 crumbs.append(make_element("td", (result_link + selection +
325 build_console), class_=result_class, title=config_name))
326
327 # Return result as string
328 return "".join(crumbs)
329
Harrison Mutai4126dc72021-11-23 11:34:41 +0000330# Emit style sheet, and script elements.
331def emit_header(fd):
332 stem = os.path.splitext(os.path.abspath(__file__))[0]
333 for tag, ext in [("style", "css"), ("script", "js")]:
334 print(open_element(tag), file=fd)
335 with open(os.extsep.join([stem, ext])) as ext_fd:
336 shutil.copyfileobj(ext_fd, fd)
337 print(close_element(tag), file=fd)
338
339def print_error_message(fd):
340 # Upon error, create a static HTML reporting the error, and then raise
341 # the latent exception again.
342 fd.seek(0, io.SEEK_SET)
343
344 # Provide inline style as there won't be a page header for us.
345 err_style = (
346 "border: 1px solid red;",
347 "color: red;",
348 "font-size: 30px;",
349 "padding: 15px;"
350 )
351
352 print(make_element("div",
353 "HTML report couldn't be prepared! Check job console.",
354 style=" ".join(err_style)), file=fd)
355
356 # Truncate file as we're disarding whatever there generated before.
357 fd.truncate()
Fathi Boudra422bf772019-12-02 11:10:16 +0200358
359def main(fd):
360 global Build_job, Jenkins, Job
361
362 parser = argparse.ArgumentParser()
363
364 # Add arguments
365 parser.add_argument("--build-job", default=None, help="Name of build job")
366 parser.add_argument("--from-json", "-j", default=None,
367 help="Generate results from JSON input rather than from Jenkins run")
368 parser.add_argument("--job", default=None, help="Name of immediate child job")
369 parser.add_argument("--meta-data", action="append", default=[],
370 help=("Meta data to read from file and include in report "
371 "(file allowed be absent). "
372 "Optionally prefix with 'text:' (default) or "
373 "'html:' to indicate type."))
374
375 opts = parser.parse_args()
376
377 workspace = os.environ["WORKSPACE"]
Harrison Mutai4126dc72021-11-23 11:34:41 +0000378
379 emit_header(fd)
380
Fathi Boudra422bf772019-12-02 11:10:16 +0200381 if not opts.from_json:
382 json_obj = {}
383
384 if not opts.job:
385 raise Exception("Must specify the name of Jenkins job with --job")
386 else:
387 Job = opts.job
388 json_obj["job"] = Job
389
390 if not opts.build_job:
391 raise Exception("Must specify the name of Jenkins build job with --build-job")
392 else:
393 Build_job = opts.build_job
394 json_obj["build_job"] = Build_job
395
Arthur Shea813bdf2025-02-03 21:39:57 -0800396 Jenkins = os.environ["JENKINS_PUBLIC_URL"].strip().rstrip("/")
Fathi Boudra422bf772019-12-02 11:10:16 +0200397
398 # Replace non-alphabetical characters in the job name with underscores. This is
399 # how Jenkins does it too.
400 job_var = re.sub(r"[^a-zA-Z0-9]", "_", opts.job)
401
402 # Build numbers are comma-separated list
403 child_build_numbers = (os.environ["TRIGGERED_BUILD_NUMBERS_" +
404 job_var]).split(",")
405
406 # Walk the $WORKSPACE directory, and fetch file names that ends with
407 # TEST_SUFFIX
408 _, _, files = next(os.walk(workspace))
409 test_files = sorted(filter(lambda f: f.endswith(TEST_SUFFIX), files))
410
411 # Store information in JSON object
412 json_obj["job"] = Job
413 json_obj["build_job"] = Build_job
414 json_obj["jenkins_url"] = Jenkins
415
416 json_obj["child_build_numbers"] = child_build_numbers
417 json_obj["test_files"] = test_files
418 json_obj["test_results"] = {}
419 else:
420 # Load JSON
421 with open(opts.from_json) as json_fd:
422 json_obj = json.load(json_fd)
423
424 Job = json_obj["job"]
425 Build_job = json_obj["build_job"]
426 Jenkins = json_obj["jenkins_url"]
427
428 child_build_numbers = json_obj["child_build_numbers"]
429 test_files = json_obj["test_files"]
430
431 # This iteration is in the assumption that Jenkins visits the files in the same
432 # order and spawns children, which is ture as of this writing. The test files
433 # are named in sequence, so it's reasonable to expect that'll remain the case.
434 # Just sayin...
435 results = ResultNode(0)
436 for i, f in enumerate(test_files):
437 # Test description is generated in the following format:
Edward Potapova8a32cd2025-06-25 10:42:35 -0500438 # seq%group%build_config:tf_run_config,tfut_run_config.test
Fathi Boudra422bf772019-12-02 11:10:16 +0200439 _, group, desc = f.split("%")
440 test_config = desc[:-len(TEST_SUFFIX)]
441 build_config, run_config = test_config.split(":")
442 spare_commas = "," * (MAX_RESULTS_DEPTH - MIN_RESULTS_DEPTH)
Edward Potapova8a32cd2025-06-25 10:42:35 -0500443 tf_config, tftf_config, spm_config, rmm_config, tfut_config, *_ = (build_config +
Fathi Boudra422bf772019-12-02 11:10:16 +0200444 spare_commas).split(",")
Edward Potapova8a32cd2025-06-25 10:42:35 -0500445 run_configs = (run_config + ",").split(",")
446 tf_run_config, tfut_run = (run_configs + [""])[:2]
Fathi Boudra422bf772019-12-02 11:10:16 +0200447
448 build_number = child_build_numbers[i]
449 if not opts.from_json:
450 var_name = "TRIGGERED_BUILD_RESULT_" + job_var + "_RUN_" + build_number
451 test_result = os.environ[var_name]
452 json_obj["test_results"][build_number] = test_result
453 else:
454 test_result = json_obj["test_results"][build_number]
455
456 # Build result tree
457 group_node = results.set_child(group)
458 tf_node = group_node.set_child(tf_config)
459 tftf_node = tf_node.set_child(tftf_config)
Chris Kay4f7846a2025-08-04 19:56:35 +0100460 spm_node = tftf_node.set_child(spm_config)
Manish V Badarkhe3b7722c2025-04-10 15:50:11 +0100461 rmm_node = spm_node.set_child(rmm_config)
Edward Potapova8a32cd2025-06-25 10:42:35 -0500462 tfut_node = rmm_node.set_child(tfut_config)
463 run_node = tfut_node.set_child(tf_run_config)
464 tfut_run_node = run_node.set_child(tfut_run)
465 tfut_run_node.set_result(test_result, build_number)
466 tfut_run_node.set_desc(os.path.join(workspace, f))
Fathi Boudra422bf772019-12-02 11:10:16 +0200467
Harrison Mutai4126dc72021-11-23 11:34:41 +0000468 # Emit page header element
Fathi Boudra422bf772019-12-02 11:10:16 +0200469 print(PAGE_HEADER, file=fd)
470 begin_table(results, fd)
471
472 # Generate HTML results for each group
473 node_stack = collections.deque()
474 for group, group_results in results.items():
475 node_stack.clear()
476
477 # For each result, make a table row
478 for _ in group_results.iterator(group, node_stack):
479 result_html = result_to_html(node_stack)
480 row = make_element("tr", result_html)
481 print(row, file=fd)
482
483 print(PAGE_FOOTER, file=fd)
484
485 # Insert meta data into report. Since meta data files aren't critical for
486 # the test report, and that other scripts may not generate all the time,
487 # ignore if the specified file doesn't exist.
488 type_to_el = dict(text="pre", html="div")
489 for data_file in opts.meta_data:
490 *prefix, filename = data_file.split(":")
491 file_type = prefix[0] if prefix else "text"
492 assert file_type in type_to_el.keys()
493
494 # Ignore if file doens't exist, or it's empty.
495 if not os.path.isfile(filename) or os.stat(filename).st_size == 0:
496 continue
497
498 with open(filename) as md_fd:
499 md_name = make_element("div", "&nbsp;" + filename + ":&nbsp;",
500 class_="tf-label-label")
501 md_content = make_element(type_to_el[file_type],
502 md_fd.read().strip("\n"), class_="tf-label-content")
503 md_container = make_element("div", md_name + md_content,
504 class_="tf-label-container")
505 print(md_container, file=fd)
506
507 # Dump JSON file unless we're reading from it.
508 if not opts.from_json:
509 with open(REPORT_JSON, "wt") as json_fd:
510 json.dump(json_obj, json_fd, indent=2)
511
Harrison Mutai4126dc72021-11-23 11:34:41 +0000512if __name__ == "__main__":
513 with open(REPORT, "wt") as fd:
514 try:
515 main(fd)
516 except:
517 print_error_message(fd)
518 raise