multiplexed_log.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. # SPDX-License-Identifier: GPL-2.0
  2. # Copyright (c) 2015 Stephen Warren
  3. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  4. # Generate an HTML-formatted log file containing multiple streams of data,
  5. # each represented in a well-delineated/-structured fashion.
  6. import datetime
  7. import html
  8. import os.path
  9. import shutil
  10. import subprocess
  11. mod_dir = os.path.dirname(os.path.abspath(__file__))
  12. class LogfileStream(object):
  13. """A file-like object used to write a single logical stream of data into
  14. a multiplexed log file. Objects of this type should be created by factory
  15. functions in the Logfile class rather than directly."""
  16. def __init__(self, logfile, name, chained_file):
  17. """Initialize a new object.
  18. Args:
  19. logfile: The Logfile object to log to.
  20. name: The name of this log stream.
  21. chained_file: The file-like object to which all stream data should be
  22. logged to in addition to logfile. Can be None.
  23. Returns:
  24. Nothing.
  25. """
  26. self.logfile = logfile
  27. self.name = name
  28. self.chained_file = chained_file
  29. def close(self):
  30. """Dummy function so that this class is "file-like".
  31. Args:
  32. None.
  33. Returns:
  34. Nothing.
  35. """
  36. pass
  37. def write(self, data, implicit=False):
  38. """Write data to the log stream.
  39. Args:
  40. data: The data to write to the file.
  41. implicit: Boolean indicating whether data actually appeared in the
  42. stream, or was implicitly generated. A valid use-case is to
  43. repeat a shell prompt at the start of each separate log
  44. section, which makes the log sections more readable in
  45. isolation.
  46. Returns:
  47. Nothing.
  48. """
  49. self.logfile.write(self, data, implicit)
  50. if self.chained_file:
  51. # Chained file is console, convert things a little
  52. self.chained_file.write((data.encode('ascii', 'replace')).decode())
  53. def flush(self):
  54. """Flush the log stream, to ensure correct log interleaving.
  55. Args:
  56. None.
  57. Returns:
  58. Nothing.
  59. """
  60. self.logfile.flush()
  61. if self.chained_file:
  62. self.chained_file.flush()
  63. class RunAndLog(object):
  64. """A utility object used to execute sub-processes and log their output to
  65. a multiplexed log file. Objects of this type should be created by factory
  66. functions in the Logfile class rather than directly."""
  67. def __init__(self, logfile, name, chained_file):
  68. """Initialize a new object.
  69. Args:
  70. logfile: The Logfile object to log to.
  71. name: The name of this log stream or sub-process.
  72. chained_file: The file-like object to which all stream data should
  73. be logged to in addition to logfile. Can be None.
  74. Returns:
  75. Nothing.
  76. """
  77. self.logfile = logfile
  78. self.name = name
  79. self.chained_file = chained_file
  80. self.output = None
  81. self.exit_status = None
  82. def close(self):
  83. """Clean up any resources managed by this object."""
  84. pass
  85. def run(self, cmd, cwd=None, ignore_errors=False):
  86. """Run a command as a sub-process, and log the results.
  87. The output is available at self.output which can be useful if there is
  88. an exception.
  89. Args:
  90. cmd: The command to execute.
  91. cwd: The directory to run the command in. Can be None to use the
  92. current directory.
  93. ignore_errors: Indicate whether to ignore errors. If True, the
  94. function will simply return if the command cannot be executed
  95. or exits with an error code, otherwise an exception will be
  96. raised if such problems occur.
  97. Returns:
  98. The output as a string.
  99. """
  100. msg = '+' + ' '.join(cmd) + '\n'
  101. if self.chained_file:
  102. self.chained_file.write(msg)
  103. self.logfile.write(self, msg)
  104. try:
  105. p = subprocess.Popen(cmd, cwd=cwd,
  106. stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  107. (stdout, stderr) = p.communicate()
  108. if stdout is not None:
  109. stdout = stdout.decode('utf-8')
  110. if stderr is not None:
  111. stderr = stderr.decode('utf-8')
  112. output = ''
  113. if stdout:
  114. if stderr:
  115. output += 'stdout:\n'
  116. output += stdout
  117. if stderr:
  118. if stdout:
  119. output += 'stderr:\n'
  120. output += stderr
  121. exit_status = p.returncode
  122. exception = None
  123. except subprocess.CalledProcessError as cpe:
  124. output = cpe.output
  125. exit_status = cpe.returncode
  126. exception = cpe
  127. except Exception as e:
  128. output = ''
  129. exit_status = 0
  130. exception = e
  131. if output and not output.endswith('\n'):
  132. output += '\n'
  133. if exit_status and not exception and not ignore_errors:
  134. exception = Exception('Exit code: ' + str(exit_status))
  135. if exception:
  136. output += str(exception) + '\n'
  137. self.logfile.write(self, output)
  138. if self.chained_file:
  139. self.chained_file.write(output)
  140. self.logfile.timestamp()
  141. # Store the output so it can be accessed if we raise an exception.
  142. self.output = output
  143. self.exit_status = exit_status
  144. if exception:
  145. raise exception
  146. return output
  147. class SectionCtxMgr(object):
  148. """A context manager for Python's "with" statement, which allows a certain
  149. portion of test code to be logged to a separate section of the log file.
  150. Objects of this type should be created by factory functions in the Logfile
  151. class rather than directly."""
  152. def __init__(self, log, marker, anchor):
  153. """Initialize a new object.
  154. Args:
  155. log: The Logfile object to log to.
  156. marker: The name of the nested log section.
  157. anchor: The anchor value to pass to start_section().
  158. Returns:
  159. Nothing.
  160. """
  161. self.log = log
  162. self.marker = marker
  163. self.anchor = anchor
  164. def __enter__(self):
  165. self.anchor = self.log.start_section(self.marker, self.anchor)
  166. def __exit__(self, extype, value, traceback):
  167. self.log.end_section(self.marker)
  168. class Logfile(object):
  169. """Generates an HTML-formatted log file containing multiple streams of
  170. data, each represented in a well-delineated/-structured fashion."""
  171. def __init__(self, fn):
  172. """Initialize a new object.
  173. Args:
  174. fn: The filename to write to.
  175. Returns:
  176. Nothing.
  177. """
  178. self.f = open(fn, 'wt', encoding='utf-8')
  179. self.last_stream = None
  180. self.blocks = []
  181. self.cur_evt = 1
  182. self.anchor = 0
  183. self.timestamp_start = self._get_time()
  184. self.timestamp_prev = self.timestamp_start
  185. self.timestamp_blocks = []
  186. self.seen_warning = False
  187. shutil.copy(mod_dir + '/multiplexed_log.css', os.path.dirname(fn))
  188. self.f.write('''\
  189. <html>
  190. <head>
  191. <link rel="stylesheet" type="text/css" href="multiplexed_log.css">
  192. <script src="http://code.jquery.com/jquery.min.js"></script>
  193. <script>
  194. $(document).ready(function () {
  195. // Copy status report HTML to start of log for easy access
  196. sts = $(".block#status_report")[0].outerHTML;
  197. $("tt").prepend(sts);
  198. // Add expand/contract buttons to all block headers
  199. btns = "<span class=\\\"block-expand hidden\\\">[+] </span>" +
  200. "<span class=\\\"block-contract\\\">[-] </span>";
  201. $(".block-header").prepend(btns);
  202. // Pre-contract all blocks which passed, leaving only problem cases
  203. // expanded, to highlight issues the user should look at.
  204. // Only top-level blocks (sections) should have any status
  205. passed_bcs = $(".block-content:has(.status-pass)");
  206. // Some blocks might have multiple status entries (e.g. the status
  207. // report), so take care not to hide blocks with partial success.
  208. passed_bcs = passed_bcs.not(":has(.status-fail)");
  209. passed_bcs = passed_bcs.not(":has(.status-xfail)");
  210. passed_bcs = passed_bcs.not(":has(.status-xpass)");
  211. passed_bcs = passed_bcs.not(":has(.status-skipped)");
  212. passed_bcs = passed_bcs.not(":has(.status-warning)");
  213. // Hide the passed blocks
  214. passed_bcs.addClass("hidden");
  215. // Flip the expand/contract button hiding for those blocks.
  216. bhs = passed_bcs.parent().children(".block-header")
  217. bhs.children(".block-expand").removeClass("hidden");
  218. bhs.children(".block-contract").addClass("hidden");
  219. // Add click handler to block headers.
  220. // The handler expands/contracts the block.
  221. $(".block-header").on("click", function (e) {
  222. var header = $(this);
  223. var content = header.next(".block-content");
  224. var expanded = !content.hasClass("hidden");
  225. if (expanded) {
  226. content.addClass("hidden");
  227. header.children(".block-expand").first().removeClass("hidden");
  228. header.children(".block-contract").first().addClass("hidden");
  229. } else {
  230. header.children(".block-contract").first().removeClass("hidden");
  231. header.children(".block-expand").first().addClass("hidden");
  232. content.removeClass("hidden");
  233. }
  234. });
  235. // When clicking on a link, expand the target block
  236. $("a").on("click", function (e) {
  237. var block = $($(this).attr("href"));
  238. var header = block.children(".block-header");
  239. var content = block.children(".block-content").first();
  240. header.children(".block-contract").first().removeClass("hidden");
  241. header.children(".block-expand").first().addClass("hidden");
  242. content.removeClass("hidden");
  243. });
  244. });
  245. </script>
  246. </head>
  247. <body>
  248. <tt>
  249. ''')
  250. def close(self):
  251. """Close the log file.
  252. After calling this function, no more data may be written to the log.
  253. Args:
  254. None.
  255. Returns:
  256. Nothing.
  257. """
  258. self.f.write('''\
  259. </tt>
  260. </body>
  261. </html>
  262. ''')
  263. self.f.close()
  264. # The set of characters that should be represented as hexadecimal codes in
  265. # the log file.
  266. _nonprint = {ord('%')}
  267. _nonprint.update({c for c in range(0, 32) if c not in (9, 10)})
  268. _nonprint.update({c for c in range(127, 256)})
  269. def _escape(self, data):
  270. """Render data format suitable for inclusion in an HTML document.
  271. This includes HTML-escaping certain characters, and translating
  272. control characters to a hexadecimal representation.
  273. Args:
  274. data: The raw string data to be escaped.
  275. Returns:
  276. An escaped version of the data.
  277. """
  278. data = data.replace(chr(13), '')
  279. data = ''.join((ord(c) in self._nonprint) and ('%%%02x' % ord(c)) or
  280. c for c in data)
  281. data = html.escape(data)
  282. return data
  283. def _terminate_stream(self):
  284. """Write HTML to the log file to terminate the current stream's data.
  285. Args:
  286. None.
  287. Returns:
  288. Nothing.
  289. """
  290. self.cur_evt += 1
  291. if not self.last_stream:
  292. return
  293. self.f.write('</pre>\n')
  294. self.f.write('<div class="stream-trailer block-trailer">End stream: ' +
  295. self.last_stream.name + '</div>\n')
  296. self.f.write('</div>\n')
  297. self.f.write('</div>\n')
  298. self.last_stream = None
  299. def _note(self, note_type, msg, anchor=None):
  300. """Write a note or one-off message to the log file.
  301. Args:
  302. note_type: The type of note. This must be a value supported by the
  303. accompanying multiplexed_log.css.
  304. msg: The note/message to log.
  305. anchor: Optional internal link target.
  306. Returns:
  307. Nothing.
  308. """
  309. self._terminate_stream()
  310. self.f.write('<div class="' + note_type + '">\n')
  311. self.f.write('<pre>')
  312. if anchor:
  313. self.f.write('<a href="#%s">' % anchor)
  314. self.f.write(self._escape(msg))
  315. if anchor:
  316. self.f.write('</a>')
  317. self.f.write('\n</pre>\n')
  318. self.f.write('</div>\n')
  319. def start_section(self, marker, anchor=None):
  320. """Begin a new nested section in the log file.
  321. Args:
  322. marker: The name of the section that is starting.
  323. anchor: The value to use for the anchor. If None, a unique value
  324. will be calculated and used
  325. Returns:
  326. Name of the HTML anchor emitted before section.
  327. """
  328. self._terminate_stream()
  329. self.blocks.append(marker)
  330. self.timestamp_blocks.append(self._get_time())
  331. if not anchor:
  332. self.anchor += 1
  333. anchor = str(self.anchor)
  334. blk_path = '/'.join(self.blocks)
  335. self.f.write('<div class="section block" id="' + anchor + '">\n')
  336. self.f.write('<div class="section-header block-header">Section: ' +
  337. blk_path + '</div>\n')
  338. self.f.write('<div class="section-content block-content">\n')
  339. self.timestamp()
  340. return anchor
  341. def end_section(self, marker):
  342. """Terminate the current nested section in the log file.
  343. This function validates proper nesting of start_section() and
  344. end_section() calls. If a mismatch is found, an exception is raised.
  345. Args:
  346. marker: The name of the section that is ending.
  347. Returns:
  348. Nothing.
  349. """
  350. if (not self.blocks) or (marker != self.blocks[-1]):
  351. raise Exception('Block nesting mismatch: "%s" "%s"' %
  352. (marker, '/'.join(self.blocks)))
  353. self._terminate_stream()
  354. timestamp_now = self._get_time()
  355. timestamp_section_start = self.timestamp_blocks.pop()
  356. delta_section = timestamp_now - timestamp_section_start
  357. self._note("timestamp",
  358. "TIME: SINCE-SECTION: " + str(delta_section))
  359. blk_path = '/'.join(self.blocks)
  360. self.f.write('<div class="section-trailer block-trailer">' +
  361. 'End section: ' + blk_path + '</div>\n')
  362. self.f.write('</div>\n')
  363. self.f.write('</div>\n')
  364. self.blocks.pop()
  365. def section(self, marker, anchor=None):
  366. """Create a temporary section in the log file.
  367. This function creates a context manager for Python's "with" statement,
  368. which allows a certain portion of test code to be logged to a separate
  369. section of the log file.
  370. Usage:
  371. with log.section("somename"):
  372. some test code
  373. Args:
  374. marker: The name of the nested section.
  375. anchor: The anchor value to pass to start_section().
  376. Returns:
  377. A context manager object.
  378. """
  379. return SectionCtxMgr(self, marker, anchor)
  380. def error(self, msg):
  381. """Write an error note to the log file.
  382. Args:
  383. msg: A message describing the error.
  384. Returns:
  385. Nothing.
  386. """
  387. self._note("error", msg)
  388. def warning(self, msg):
  389. """Write an warning note to the log file.
  390. Args:
  391. msg: A message describing the warning.
  392. Returns:
  393. Nothing.
  394. """
  395. self.seen_warning = True
  396. self._note("warning", msg)
  397. def get_and_reset_warning(self):
  398. """Get and reset the log warning flag.
  399. Args:
  400. None
  401. Returns:
  402. Whether a warning was seen since the last call.
  403. """
  404. ret = self.seen_warning
  405. self.seen_warning = False
  406. return ret
  407. def info(self, msg):
  408. """Write an informational note to the log file.
  409. Args:
  410. msg: An informational message.
  411. Returns:
  412. Nothing.
  413. """
  414. self._note("info", msg)
  415. def action(self, msg):
  416. """Write an action note to the log file.
  417. Args:
  418. msg: A message describing the action that is being logged.
  419. Returns:
  420. Nothing.
  421. """
  422. self._note("action", msg)
  423. def _get_time(self):
  424. return datetime.datetime.now()
  425. def timestamp(self):
  426. """Write a timestamp to the log file.
  427. Args:
  428. None
  429. Returns:
  430. Nothing.
  431. """
  432. timestamp_now = self._get_time()
  433. delta_prev = timestamp_now - self.timestamp_prev
  434. delta_start = timestamp_now - self.timestamp_start
  435. self.timestamp_prev = timestamp_now
  436. self._note("timestamp",
  437. "TIME: NOW: " + timestamp_now.strftime("%Y/%m/%d %H:%M:%S.%f"))
  438. self._note("timestamp",
  439. "TIME: SINCE-PREV: " + str(delta_prev))
  440. self._note("timestamp",
  441. "TIME: SINCE-START: " + str(delta_start))
  442. def status_pass(self, msg, anchor=None):
  443. """Write a note to the log file describing test(s) which passed.
  444. Args:
  445. msg: A message describing the passed test(s).
  446. anchor: Optional internal link target.
  447. Returns:
  448. Nothing.
  449. """
  450. self._note("status-pass", msg, anchor)
  451. def status_warning(self, msg, anchor=None):
  452. """Write a note to the log file describing test(s) which passed.
  453. Args:
  454. msg: A message describing the passed test(s).
  455. anchor: Optional internal link target.
  456. Returns:
  457. Nothing.
  458. """
  459. self._note("status-warning", msg, anchor)
  460. def status_skipped(self, msg, anchor=None):
  461. """Write a note to the log file describing skipped test(s).
  462. Args:
  463. msg: A message describing the skipped test(s).
  464. anchor: Optional internal link target.
  465. Returns:
  466. Nothing.
  467. """
  468. self._note("status-skipped", msg, anchor)
  469. def status_xfail(self, msg, anchor=None):
  470. """Write a note to the log file describing xfailed test(s).
  471. Args:
  472. msg: A message describing the xfailed test(s).
  473. anchor: Optional internal link target.
  474. Returns:
  475. Nothing.
  476. """
  477. self._note("status-xfail", msg, anchor)
  478. def status_xpass(self, msg, anchor=None):
  479. """Write a note to the log file describing xpassed test(s).
  480. Args:
  481. msg: A message describing the xpassed test(s).
  482. anchor: Optional internal link target.
  483. Returns:
  484. Nothing.
  485. """
  486. self._note("status-xpass", msg, anchor)
  487. def status_fail(self, msg, anchor=None):
  488. """Write a note to the log file describing failed test(s).
  489. Args:
  490. msg: A message describing the failed test(s).
  491. anchor: Optional internal link target.
  492. Returns:
  493. Nothing.
  494. """
  495. self._note("status-fail", msg, anchor)
  496. def get_stream(self, name, chained_file=None):
  497. """Create an object to log a single stream's data into the log file.
  498. This creates a "file-like" object that can be written to in order to
  499. write a single stream's data to the log file. The implementation will
  500. handle any required interleaving of data (from multiple streams) in
  501. the log, in a way that makes it obvious which stream each bit of data
  502. came from.
  503. Args:
  504. name: The name of the stream.
  505. chained_file: The file-like object to which all stream data should
  506. be logged to in addition to this log. Can be None.
  507. Returns:
  508. A file-like object.
  509. """
  510. return LogfileStream(self, name, chained_file)
  511. def get_runner(self, name, chained_file=None):
  512. """Create an object that executes processes and logs their output.
  513. Args:
  514. name: The name of this sub-process.
  515. chained_file: The file-like object to which all stream data should
  516. be logged to in addition to logfile. Can be None.
  517. Returns:
  518. A RunAndLog object.
  519. """
  520. return RunAndLog(self, name, chained_file)
  521. def write(self, stream, data, implicit=False):
  522. """Write stream data into the log file.
  523. This function should only be used by instances of LogfileStream or
  524. RunAndLog.
  525. Args:
  526. stream: The stream whose data is being logged.
  527. data: The data to log.
  528. implicit: Boolean indicating whether data actually appeared in the
  529. stream, or was implicitly generated. A valid use-case is to
  530. repeat a shell prompt at the start of each separate log
  531. section, which makes the log sections more readable in
  532. isolation.
  533. Returns:
  534. Nothing.
  535. """
  536. if stream != self.last_stream:
  537. self._terminate_stream()
  538. self.f.write('<div class="stream block">\n')
  539. self.f.write('<div class="stream-header block-header">Stream: ' +
  540. stream.name + '</div>\n')
  541. self.f.write('<div class="stream-content block-content">\n')
  542. self.f.write('<pre>')
  543. if implicit:
  544. self.f.write('<span class="implicit">')
  545. self.f.write(self._escape(data))
  546. if implicit:
  547. self.f.write('</span>')
  548. self.last_stream = stream
  549. def flush(self):
  550. """Flush the log stream, to ensure correct log interleaving.
  551. Args:
  552. None.
  553. Returns:
  554. Nothing.
  555. """
  556. self.f.flush()