multiplexed_log.py 19 KB

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