multiplexed_log.py 22 KB

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