1 # Copyright (c) 2015 Stephen Warren
2 # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
4 # SPDX-License-Identifier: GPL-2.0
6 # Generate an HTML-formatted log file containing multiple streams of data,
7 # each represented in a well-delineated/-structured fashion.
14 mod_dir = os.path.dirname(os.path.abspath(__file__))
16 class LogfileStream(object):
17 """A file-like object used to write a single logical stream of data into
18 a multiplexed log file. Objects of this type should be created by factory
19 functions in the Logfile class rather than directly."""
21 def __init__(self, logfile, name, chained_file):
22 """Initialize a new object.
25 logfile: The Logfile object to log to.
26 name: The name of this log stream.
27 chained_file: The file-like object to which all stream data should be
28 logged to in addition to logfile. Can be None.
34 self.logfile = logfile
36 self.chained_file = chained_file
39 """Dummy function so that this class is "file-like".
50 def write(self, data, implicit=False):
51 """Write data to the log stream.
54 data: The data to write tot he file.
55 implicit: Boolean indicating whether data actually appeared in the
56 stream, or was implicitly generated. A valid use-case is to
57 repeat a shell prompt at the start of each separate log
58 section, which makes the log sections more readable in
65 self.logfile.write(self, data, implicit)
67 self.chained_file.write(data)
70 """Flush the log stream, to ensure correct log interleaving.
81 self.chained_file.flush()
83 class RunAndLog(object):
84 """A utility object used to execute sub-processes and log their output to
85 a multiplexed log file. Objects of this type should be created by factory
86 functions in the Logfile class rather than directly."""
88 def __init__(self, logfile, name, chained_file):
89 """Initialize a new object.
92 logfile: The Logfile object to log to.
93 name: The name of this log stream or sub-process.
94 chained_file: The file-like object to which all stream data should
95 be logged to in addition to logfile. Can be None.
101 self.logfile = logfile
103 self.chained_file = chained_file
105 self.exit_status = None
108 """Clean up any resources managed by this object."""
111 def run(self, cmd, cwd=None, ignore_errors=False):
112 """Run a command as a sub-process, and log the results.
114 The output is available at self.output which can be useful if there is
118 cmd: The command to execute.
119 cwd: The directory to run the command in. Can be None to use the
121 ignore_errors: Indicate whether to ignore errors. If True, the
122 function will simply return if the command cannot be executed
123 or exits with an error code, otherwise an exception will be
124 raised if such problems occur.
127 The output as a string.
130 msg = '+' + ' '.join(cmd) + '\n'
131 if self.chained_file:
132 self.chained_file.write(msg)
133 self.logfile.write(self, msg)
136 p = subprocess.Popen(cmd, cwd=cwd,
137 stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
138 (stdout, stderr) = p.communicate()
142 output += 'stdout:\n'
146 output += 'stderr:\n'
148 exit_status = p.returncode
150 except subprocess.CalledProcessError as cpe:
152 exit_status = cpe.returncode
154 except Exception as e:
158 if output and not output.endswith('\n'):
160 if exit_status and not exception and not ignore_errors:
161 exception = Exception('Exit code: ' + str(exit_status))
163 output += str(exception) + '\n'
164 self.logfile.write(self, output)
165 if self.chained_file:
166 self.chained_file.write(output)
168 # Store the output so it can be accessed if we raise an exception.
170 self.exit_status = exit_status
175 class SectionCtxMgr(object):
176 """A context manager for Python's "with" statement, which allows a certain
177 portion of test code to be logged to a separate section of the log file.
178 Objects of this type should be created by factory functions in the Logfile
179 class rather than directly."""
181 def __init__(self, log, marker, anchor):
182 """Initialize a new object.
185 log: The Logfile object to log to.
186 marker: The name of the nested log section.
187 anchor: The anchor value to pass to start_section().
198 self.anchor = self.log.start_section(self.marker, self.anchor)
200 def __exit__(self, extype, value, traceback):
201 self.log.end_section(self.marker)
203 class Logfile(object):
204 """Generates an HTML-formatted log file containing multiple streams of
205 data, each represented in a well-delineated/-structured fashion."""
207 def __init__(self, fn):
208 """Initialize a new object.
211 fn: The filename to write to.
217 self.f = open(fn, 'wt')
218 self.last_stream = None
223 shutil.copy(mod_dir + '/multiplexed_log.css', os.path.dirname(fn))
227 <link rel="stylesheet" type="text/css" href="multiplexed_log.css">
228 <script src="http://code.jquery.com/jquery.min.js"></script>
230 $(document).ready(function () {
231 // Copy status report HTML to start of log for easy access
232 sts = $(".block#status_report")[0].outerHTML;
233 $("tt").prepend(sts);
235 // Add expand/contract buttons to all block headers
236 btns = "<span class=\\\"block-expand hidden\\\">[+] </span>" +
237 "<span class=\\\"block-contract\\\">[-] </span>";
238 $(".block-header").prepend(btns);
240 // Pre-contract all blocks which passed, leaving only problem cases
241 // expanded, to highlight issues the user should look at.
242 // Only top-level blocks (sections) should have any status
243 passed_bcs = $(".block-content:has(.status-pass)");
244 // Some blocks might have multiple status entries (e.g. the status
245 // report), so take care not to hide blocks with partial success.
246 passed_bcs = passed_bcs.not(":has(.status-fail)");
247 passed_bcs = passed_bcs.not(":has(.status-xfail)");
248 passed_bcs = passed_bcs.not(":has(.status-xpass)");
249 passed_bcs = passed_bcs.not(":has(.status-skipped)");
250 // Hide the passed blocks
251 passed_bcs.addClass("hidden");
252 // Flip the expand/contract button hiding for those blocks.
253 bhs = passed_bcs.parent().children(".block-header")
254 bhs.children(".block-expand").removeClass("hidden");
255 bhs.children(".block-contract").addClass("hidden");
257 // Add click handler to block headers.
258 // The handler expands/contracts the block.
259 $(".block-header").on("click", function (e) {
260 var header = $(this);
261 var content = header.next(".block-content");
262 var expanded = !content.hasClass("hidden");
264 content.addClass("hidden");
265 header.children(".block-expand").first().removeClass("hidden");
266 header.children(".block-contract").first().addClass("hidden");
268 header.children(".block-contract").first().removeClass("hidden");
269 header.children(".block-expand").first().addClass("hidden");
270 content.removeClass("hidden");
274 // When clicking on a link, expand the target block
275 $("a").on("click", function (e) {
276 var block = $($(this).attr("href"));
277 var header = block.children(".block-header");
278 var content = block.children(".block-content").first();
279 header.children(".block-contract").first().removeClass("hidden");
280 header.children(".block-expand").first().addClass("hidden");
281 content.removeClass("hidden");
291 """Close the log file.
293 After calling this function, no more data may be written to the log.
309 # The set of characters that should be represented as hexadecimal codes in
311 _nonprint = ('%' + ''.join(chr(c) for c in range(0, 32) if c not in (9, 10)) +
312 ''.join(chr(c) for c in range(127, 256)))
314 def _escape(self, data):
315 """Render data format suitable for inclusion in an HTML document.
317 This includes HTML-escaping certain characters, and translating
318 control characters to a hexadecimal representation.
321 data: The raw string data to be escaped.
324 An escaped version of the data.
327 data = data.replace(chr(13), '')
328 data = ''.join((c in self._nonprint) and ('%%%02x' % ord(c)) or
330 data = cgi.escape(data)
333 def _terminate_stream(self):
334 """Write HTML to the log file to terminate the current stream's data.
344 if not self.last_stream:
346 self.f.write('</pre>\n')
347 self.f.write('<div class="stream-trailer block-trailer">End stream: ' +
348 self.last_stream.name + '</div>\n')
349 self.f.write('</div>\n')
350 self.f.write('</div>\n')
351 self.last_stream = None
353 def _note(self, note_type, msg, anchor=None):
354 """Write a note or one-off message to the log file.
357 note_type: The type of note. This must be a value supported by the
358 accompanying multiplexed_log.css.
359 msg: The note/message to log.
360 anchor: Optional internal link target.
366 self._terminate_stream()
367 self.f.write('<div class="' + note_type + '">\n')
369 self.f.write('<a href="#%s">\n' % anchor)
370 self.f.write('<pre>')
371 self.f.write(self._escape(msg))
372 self.f.write('\n</pre>\n')
374 self.f.write('</a>\n')
375 self.f.write('</div>\n')
377 def start_section(self, marker, anchor=None):
378 """Begin a new nested section in the log file.
381 marker: The name of the section that is starting.
382 anchor: The value to use for the anchor. If None, a unique value
383 will be calculated and used
386 Name of the HTML anchor emitted before section.
389 self._terminate_stream()
390 self.blocks.append(marker)
393 anchor = str(self.anchor)
394 blk_path = '/'.join(self.blocks)
395 self.f.write('<div class="section block" id="' + anchor + '">\n')
396 self.f.write('<div class="section-header block-header">Section: ' +
397 blk_path + '</div>\n')
398 self.f.write('<div class="section-content block-content">\n')
402 def end_section(self, marker):
403 """Terminate the current nested section in the log file.
405 This function validates proper nesting of start_section() and
406 end_section() calls. If a mismatch is found, an exception is raised.
409 marker: The name of the section that is ending.
415 if (not self.blocks) or (marker != self.blocks[-1]):
416 raise Exception('Block nesting mismatch: "%s" "%s"' %
417 (marker, '/'.join(self.blocks)))
418 self._terminate_stream()
419 blk_path = '/'.join(self.blocks)
420 self.f.write('<div class="section-trailer block-trailer">' +
421 'End section: ' + blk_path + '</div>\n')
422 self.f.write('</div>\n')
423 self.f.write('</div>\n')
426 def section(self, marker, anchor=None):
427 """Create a temporary section in the log file.
429 This function creates a context manager for Python's "with" statement,
430 which allows a certain portion of test code to be logged to a separate
431 section of the log file.
434 with log.section("somename"):
438 marker: The name of the nested section.
439 anchor: The anchor value to pass to start_section().
442 A context manager object.
445 return SectionCtxMgr(self, marker, anchor)
447 def error(self, msg):
448 """Write an error note to the log file.
451 msg: A message describing the error.
457 self._note("error", msg)
459 def warning(self, msg):
460 """Write an warning note to the log file.
463 msg: A message describing the warning.
469 self._note("warning", msg)
472 """Write an informational note to the log file.
475 msg: An informational message.
481 self._note("info", msg)
483 def action(self, msg):
484 """Write an action note to the log file.
487 msg: A message describing the action that is being logged.
493 self._note("action", msg)
495 def status_pass(self, msg, anchor=None):
496 """Write a note to the log file describing test(s) which passed.
499 msg: A message describing the passed test(s).
500 anchor: Optional internal link target.
506 self._note("status-pass", msg, anchor)
508 def status_skipped(self, msg, anchor=None):
509 """Write a note to the log file describing skipped test(s).
512 msg: A message describing the skipped test(s).
513 anchor: Optional internal link target.
519 self._note("status-skipped", msg, anchor)
521 def status_xfail(self, msg, anchor=None):
522 """Write a note to the log file describing xfailed test(s).
525 msg: A message describing the xfailed test(s).
526 anchor: Optional internal link target.
532 self._note("status-xfail", msg, anchor)
534 def status_xpass(self, msg, anchor=None):
535 """Write a note to the log file describing xpassed test(s).
538 msg: A message describing the xpassed test(s).
539 anchor: Optional internal link target.
545 self._note("status-xpass", msg, anchor)
547 def status_fail(self, msg, anchor=None):
548 """Write a note to the log file describing failed test(s).
551 msg: A message describing the failed test(s).
552 anchor: Optional internal link target.
558 self._note("status-fail", msg, anchor)
560 def get_stream(self, name, chained_file=None):
561 """Create an object to log a single stream's data into the log file.
563 This creates a "file-like" object that can be written to in order to
564 write a single stream's data to the log file. The implementation will
565 handle any required interleaving of data (from multiple streams) in
566 the log, in a way that makes it obvious which stream each bit of data
570 name: The name of the stream.
571 chained_file: The file-like object to which all stream data should
572 be logged to in addition to this log. Can be None.
578 return LogfileStream(self, name, chained_file)
580 def get_runner(self, name, chained_file=None):
581 """Create an object that executes processes and logs their output.
584 name: The name of this sub-process.
585 chained_file: The file-like object to which all stream data should
586 be logged to in addition to logfile. Can be None.
592 return RunAndLog(self, name, chained_file)
594 def write(self, stream, data, implicit=False):
595 """Write stream data into the log file.
597 This function should only be used by instances of LogfileStream or
601 stream: The stream whose data is being logged.
602 data: The data to log.
603 implicit: Boolean indicating whether data actually appeared in the
604 stream, or was implicitly generated. A valid use-case is to
605 repeat a shell prompt at the start of each separate log
606 section, which makes the log sections more readable in
613 if stream != self.last_stream:
614 self._terminate_stream()
615 self.f.write('<div class="stream block">\n')
616 self.f.write('<div class="stream-header block-header">Stream: ' +
617 stream.name + '</div>\n')
618 self.f.write('<div class="stream-content block-content">\n')
619 self.f.write('<pre>')
621 self.f.write('<span class="implicit">')
622 self.f.write(self._escape(data))
624 self.f.write('</span>')
625 self.last_stream = stream
628 """Flush the log stream, to ensure correct log interleaving.