multiplexed_log.py 21 KB

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