multiplexed_log.py 21 KB

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