multiplexed_log.py 19 KB

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