blob: d61cb213cdb2bf41ee1b934d8177f9f4fe9c2ed1 [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
72MAX_RESULTS_DEPTH = 5
73
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",
84 "SCP Build Config",
85 "Run Config",
86 "Status"
87]
88
89Jenkins = None
90Dimmed_hypen = None
91Build_job = None
92Job = None
93
94# Indicates whether a level of table has no entries. Assume all levels are empty
95# to start; and flip that around as and when we see otherwise.
96Level_empty = [True] * MAX_RESULTS_DEPTH
97assert len(LEVEL_HEADERS) == (MAX_RESULTS_DEPTH + 1)
98
99# A column is deemed empty if it's content is empty or is the string "nil"
100is_empty = lambda key: key in ("", "nil")
101
102# A tree of ResultNodes are used to group test results by config. The tree is
103# MAX_RESULTS_DEPTH levels deep. Levels above MAX_RESULTS_DEPTH groups results,
104# where as those at MAX_RESULTS_DEPTH (leaves) hold test result and other meta
105# data.
106class ResultNode:
107 def __init__(self, depth=0):
108 self.depth = depth
109 self.printed = False
110 if depth == MAX_RESULTS_DEPTH:
111 self.result = None
112 self.build_number = None
113 self.desc = None
114 else:
115 self.num_children = 0
116 self.children = collections.OrderedDict()
117
118 # For a grouping node, set child by key.
119 def set_child(self, key):
120 assert self.depth < MAX_RESULTS_DEPTH
121
122 self.num_children += 1
123 if not is_empty(key):
124 Level_empty[self.depth] = False
125 return self.children.setdefault(key, ResultNode(self.depth + 1))
126
127 # For a leaf node, set result and other meta data.
128 def set_result(self, result, build_number):
129 assert self.depth == MAX_RESULTS_DEPTH
130
131 self.result = result
132 self.build_number = build_number
133
134 def set_desc(self, desc):
135 self.desc = desc
136
137 def get_desc(self):
138 return self.desc
139
140 # For a grouping node, return dictionary iterator.
141 def items(self):
142 assert self.depth < MAX_RESULTS_DEPTH
143
144 return self.children.items()
145
146 # Generator function that walks through test results. The output of
147 # iteration is reflected in the stack argument, which ought to be a deque.
148 def iterator(self, key, stack):
149 stack.append((key, self))
150 if self.depth < MAX_RESULTS_DEPTH:
151 for child_key, child in self.items():
152 yield from child.iterator(child_key, stack)
153 else:
154 yield
155 stack.pop()
156
157 # Convenient child access during debugging.
158 def __getitem__(self, key):
159 assert self.depth < MAX_RESULTS_DEPTH
160
161 return self.children[key]
162
163 # Print convenient representation for debugging.
164 def __repr__(self):
165 if self.depth < MAX_RESULTS_DEPTH:
166 return "node(depth={}, nc={}, {})".format(self.depth,
167 self.num_children,
168 ("None" if self.children is None else
169 list(self.children.keys())))
170 else:
171 return ("result(" +
172 ("None" if self.result is None else str(self.result)) + ")")
173
174
175# Open an HTML element, given its name, content, and a dictionary of attributes:
176# <name foo="bar"...>
177def open_element(name, attrs=None):
178 # If there are no attributes, return the element right away
179 if attrs is None:
180 return "<" + name + ">"
181
182 el_list = ["<" + name]
183
184 # 'class', being a Python keyword, can't be passed as a keyword argument, so
185 # is passed as 'class_' instead.
186 if "class_" in attrs:
187 attrs["class"] = attrs["class_"]
188 del attrs["class_"]
189
190 for key, val in attrs.items():
191 if val is not None:
192 el_list.append(' {}="{}"'.format(key, val))
193
194 el_list.append(">")
195
196 return "".join(el_list)
197
198
199# Close an HTML element
200def close_element(name):
201 return "</" + name + ">"
202
203
204# Make an HTML element, given its name, content, and a dictionary of attributes:
205# <name foo="bar"...>content</name>
206def make_element(name, content="", **attrs):
207 assert type(content) is str
208
209 return "".join([open_element(name, attrs), content, close_element(name)])
210
211
212# Wrap link in a hyperlink:
213# <a href="link" foo="bar"... target="_blank">content</a>
214def wrap_link(content, link, **attrs):
215 return make_element("a", content, href=link, target="_blank", **attrs)
216
217
218def jenkins_job_link(job, build_number):
219 return "/".join([Jenkins, "job", job, build_number, ""])
220
221
222# Begin table by emitting table headers for all levels that aren't empty, and
223# results column. Finish by opening a tbody element for rest of the table
224# content.
225def begin_table(results, fd):
226 # Iterate and filter out empty levels
227 table_headers = []
228 for level, empty in enumerate(Level_empty):
229 if empty:
230 continue
231 table_headers.append(make_element("th", LEVEL_HEADERS[level]))
232
233 # Result
234 table_headers.append(make_element("th", LEVEL_HEADERS[level + 1]))
235
236 row = make_element("tr", "\n".join(table_headers))
237 print(make_element("thead", row), file=fd)
238 print(open_element("tbody"), file=fd)
239
240
241# Parse the console output of the sub job to identify the build job number. Once
242# build job number is identified, return the link to job console. Upon error,
243# return None.
244def get_build_job_console_link(job_link):
245 job_console_text_link = job_link + "consoleText"
246 try:
247 with urllib.request.urlopen(job_console_text_link) as console_fd:
248 for line in console_fd:
249 # Look for lines like:
250 # tf-build #1356 completed. Result was SUCCESS
251 line = line.decode()
252 if line.find("completed. Result was") < 0:
253 continue
254
255 build_job, build_job_number, *_ = line.split()
256 if build_job != Build_job:
257 continue
258
259 build_job_number = build_job_number.replace("#", "")
260 return (jenkins_job_link(Build_job, build_job_number) +
261 "console")
262 except:
263 pass
264
265 return None
266
267
268# Given the node stack, reconstruct the original config name
269def reconstruct_config(node_stack):
270 group = node_stack[0][0]
271 run_config, run_node = node_stack[-1]
272
273 desc = run_node.get_desc()
274 try:
275 with open(desc) as fd:
276 test_config = fd.read().strip()
277 except FileNotFoundError:
278 print("warning: descriptor {} couldn't be opened.".format(desc),
279 file=sys.stderr);
280 return ""
281
282 if group != "GENERATED":
283 return os.path.join(group, test_config)
284 else:
285 return test_config
286
287
288# While iterating results, obtain a trail to the current result. node_stack is
289# iterated to identify the nodes contributing to one result.
290def result_to_html(node_stack):
291 global Dimmed_hypen
292
293 crumbs = []
294 for key, child_node in node_stack:
295 if child_node.printed:
296 continue
297
298 child_node.printed = True
299
300 # If the level is empty, skip emitting this column
301 if not Level_empty[child_node.depth - 1]:
302 # - TF config might be "nil" for TFTF-only build configs;
303 # - TFTF config might not be present for non-TFTF runs;
304 # - SCP config might not be present for non-SCP builds;
305 # - All build-only configs have runconfig as "nil";
306 #
307 # Make nil cells empty, and grey empty cells out.
308 if is_empty(key):
309 key = ""
310 td_class = "emptycell"
311 else:
312 td_class = None
313
314 rowspan = None
315 if (child_node.depth < MAX_RESULTS_DEPTH
316 and child_node.num_children > 1):
317 rowspan = child_node.num_children
318
319 # Keys are hyphen-separated strings. For better readability, dim
320 # hyphens so that text around the hyphens stand out.
321 if not Dimmed_hypen:
322 Dimmed_hypen = make_element("span", "-", class_="dim")
323 dimmed_key = Dimmed_hypen.join(key.split("-"))
324
325 crumbs.append(make_element("td", dimmed_key, rowspan=rowspan,
326 class_=td_class))
327
328 # For the last node, print result as well.
329 if child_node.depth == MAX_RESULTS_DEPTH:
330 # Make test result as a link to the job console
331 result_class = child_node.result.lower()
332 job_link = jenkins_job_link(Job, child_node.build_number)
333 result_link = wrap_link(child_node.result, job_link,
334 class_="result")
335 build_job_console_link = get_build_job_console_link(job_link)
336
337 # Add selection checkbox
338 selection = make_element("input", type="checkbox")
339
340 # Add link to build console if applicable
341 if build_job_console_link:
342 build_console = wrap_link("", build_job_console_link,
343 class_="buildlink", title="Click to visit build job console")
344 else:
345 build_console = ""
346
347 config_name = reconstruct_config(node_stack)
348
349 crumbs.append(make_element("td", (result_link + selection +
350 build_console), class_=result_class, title=config_name))
351
352 # Return result as string
353 return "".join(crumbs)
354
355
356def main(fd):
357 global Build_job, Jenkins, Job
358
359 parser = argparse.ArgumentParser()
360
361 # Add arguments
362 parser.add_argument("--build-job", default=None, help="Name of build job")
363 parser.add_argument("--from-json", "-j", default=None,
364 help="Generate results from JSON input rather than from Jenkins run")
365 parser.add_argument("--job", default=None, help="Name of immediate child job")
366 parser.add_argument("--meta-data", action="append", default=[],
367 help=("Meta data to read from file and include in report "
368 "(file allowed be absent). "
369 "Optionally prefix with 'text:' (default) or "
370 "'html:' to indicate type."))
371
372 opts = parser.parse_args()
373
374 workspace = os.environ["WORKSPACE"]
375 if not opts.from_json:
376 json_obj = {}
377
378 if not opts.job:
379 raise Exception("Must specify the name of Jenkins job with --job")
380 else:
381 Job = opts.job
382 json_obj["job"] = Job
383
384 if not opts.build_job:
385 raise Exception("Must specify the name of Jenkins build job with --build-job")
386 else:
387 Build_job = opts.build_job
388 json_obj["build_job"] = Build_job
389
390 Jenkins = os.environ["JENKINS_URL"].strip().rstrip("/")
391
392 # Replace non-alphabetical characters in the job name with underscores. This is
393 # how Jenkins does it too.
394 job_var = re.sub(r"[^a-zA-Z0-9]", "_", opts.job)
395
396 # Build numbers are comma-separated list
397 child_build_numbers = (os.environ["TRIGGERED_BUILD_NUMBERS_" +
398 job_var]).split(",")
399
400 # Walk the $WORKSPACE directory, and fetch file names that ends with
401 # TEST_SUFFIX
402 _, _, files = next(os.walk(workspace))
403 test_files = sorted(filter(lambda f: f.endswith(TEST_SUFFIX), files))
404
405 # Store information in JSON object
406 json_obj["job"] = Job
407 json_obj["build_job"] = Build_job
408 json_obj["jenkins_url"] = Jenkins
409
410 json_obj["child_build_numbers"] = child_build_numbers
411 json_obj["test_files"] = test_files
412 json_obj["test_results"] = {}
413 else:
414 # Load JSON
415 with open(opts.from_json) as json_fd:
416 json_obj = json.load(json_fd)
417
418 Job = json_obj["job"]
419 Build_job = json_obj["build_job"]
420 Jenkins = json_obj["jenkins_url"]
421
422 child_build_numbers = json_obj["child_build_numbers"]
423 test_files = json_obj["test_files"]
424
425 # This iteration is in the assumption that Jenkins visits the files in the same
426 # order and spawns children, which is ture as of this writing. The test files
427 # are named in sequence, so it's reasonable to expect that'll remain the case.
428 # Just sayin...
429 results = ResultNode(0)
430 for i, f in enumerate(test_files):
431 # Test description is generated in the following format:
432 # seq%group%build_config:run_config.test
433 _, group, desc = f.split("%")
434 test_config = desc[:-len(TEST_SUFFIX)]
435 build_config, run_config = test_config.split(":")
436 spare_commas = "," * (MAX_RESULTS_DEPTH - MIN_RESULTS_DEPTH)
437 tf_config, tftf_config, scp_config, *_ = (build_config +
438 spare_commas).split(",")
439
440 build_number = child_build_numbers[i]
441 if not opts.from_json:
442 var_name = "TRIGGERED_BUILD_RESULT_" + job_var + "_RUN_" + build_number
443 test_result = os.environ[var_name]
444 json_obj["test_results"][build_number] = test_result
445 else:
446 test_result = json_obj["test_results"][build_number]
447
448 # Build result tree
449 group_node = results.set_child(group)
450 tf_node = group_node.set_child(tf_config)
451 tftf_node = tf_node.set_child(tftf_config)
452 scp_node = tftf_node.set_child(scp_config)
453 run_node = scp_node.set_child(run_config)
454 run_node.set_result(test_result, build_number)
455 run_node.set_desc(os.path.join(workspace, f))
456
457 # Emit style sheet, script, and page header elements
458 stem = os.path.splitext(os.path.abspath(__file__))[0]
459 for tag, ext in [("style", "css"), ("script", "js")]:
460 print(open_element(tag), file=fd)
461 with open(os.extsep.join([stem, ext])) as ext_fd:
462 shutil.copyfileobj(ext_fd, fd)
463 print(close_element(tag), file=fd)
464 print(PAGE_HEADER, file=fd)
465 begin_table(results, fd)
466
467 # Generate HTML results for each group
468 node_stack = collections.deque()
469 for group, group_results in results.items():
470 node_stack.clear()
471
472 # For each result, make a table row
473 for _ in group_results.iterator(group, node_stack):
474 result_html = result_to_html(node_stack)
475 row = make_element("tr", result_html)
476 print(row, file=fd)
477
478 print(PAGE_FOOTER, file=fd)
479
480 # Insert meta data into report. Since meta data files aren't critical for
481 # the test report, and that other scripts may not generate all the time,
482 # ignore if the specified file doesn't exist.
483 type_to_el = dict(text="pre", html="div")
484 for data_file in opts.meta_data:
485 *prefix, filename = data_file.split(":")
486 file_type = prefix[0] if prefix else "text"
487 assert file_type in type_to_el.keys()
488
489 # Ignore if file doens't exist, or it's empty.
490 if not os.path.isfile(filename) or os.stat(filename).st_size == 0:
491 continue
492
493 with open(filename) as md_fd:
494 md_name = make_element("div", "&nbsp;" + filename + ":&nbsp;",
495 class_="tf-label-label")
496 md_content = make_element(type_to_el[file_type],
497 md_fd.read().strip("\n"), class_="tf-label-content")
498 md_container = make_element("div", md_name + md_content,
499 class_="tf-label-container")
500 print(md_container, file=fd)
501
502 # Dump JSON file unless we're reading from it.
503 if not opts.from_json:
504 with open(REPORT_JSON, "wt") as json_fd:
505 json.dump(json_obj, json_fd, indent=2)
506
507
508with open(REPORT, "wt") as fd:
509 try:
510 main(fd)
511 except:
512 # Upon error, create a static HTML reporting the error, and then raise
513 # the latent exception again.
514 fd.seek(0, io.SEEK_SET)
515
516 # Provide inline style as there won't be a page header for us.
517 err_style = (
518 "border: 1px solid red;",
519 "color: red;",
520 "font-size: 30px;",
521 "padding: 15px;"
522 )
523
524 print(make_element("div",
525 "HTML report couldn't be prepared! Check job console.",
526 style=" ".join(err_style)), file=fd)
527
528 # Truncate file as we're disarding whatever there generated before.
529 fd.truncate()
530 raise