multiplexed_log.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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):
  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. Returns:
  144. Nothing.
  145. """
  146. self.log = log
  147. self.marker = marker
  148. def __enter__(self):
  149. self.log.start_section(self.marker)
  150. def __exit__(self, extype, value, traceback):
  151. self.log.end_section(self.marker)
  152. class Logfile(object):
  153. """Generates an HTML-formatted log file containing multiple streams of
  154. data, each represented in a well-delineated/-structured fashion."""
  155. def __init__(self, fn):
  156. """Initialize a new object.
  157. Args:
  158. fn: The filename to write to.
  159. Returns:
  160. Nothing.
  161. """
  162. self.f = open(fn, "wt")
  163. self.last_stream = None
  164. self.blocks = []
  165. self.cur_evt = 1
  166. shutil.copy(mod_dir + "/multiplexed_log.css", os.path.dirname(fn))
  167. self.f.write("""\
  168. <html>
  169. <head>
  170. <link rel="stylesheet" type="text/css" href="multiplexed_log.css">
  171. </head>
  172. <body>
  173. <tt>
  174. """)
  175. def close(self):
  176. """Close the log file.
  177. After calling this function, no more data may be written to the log.
  178. Args:
  179. None.
  180. Returns:
  181. Nothing.
  182. """
  183. self.f.write("""\
  184. </tt>
  185. </body>
  186. </html>
  187. """)
  188. self.f.close()
  189. # The set of characters that should be represented as hexadecimal codes in
  190. # the log file.
  191. _nonprint = ("%" + "".join(chr(c) for c in range(0, 32) if c not in (9, 10)) +
  192. "".join(chr(c) for c in range(127, 256)))
  193. def _escape(self, data):
  194. """Render data format suitable for inclusion in an HTML document.
  195. This includes HTML-escaping certain characters, and translating
  196. control characters to a hexadecimal representation.
  197. Args:
  198. data: The raw string data to be escaped.
  199. Returns:
  200. An escaped version of the data.
  201. """
  202. data = data.replace(chr(13), "")
  203. data = "".join((c in self._nonprint) and ("%%%02x" % ord(c)) or
  204. c for c in data)
  205. data = cgi.escape(data)
  206. return data
  207. def _terminate_stream(self):
  208. """Write HTML to the log file to terminate the current stream's data.
  209. Args:
  210. None.
  211. Returns:
  212. Nothing.
  213. """
  214. self.cur_evt += 1
  215. if not self.last_stream:
  216. return
  217. self.f.write("</pre>\n")
  218. self.f.write("<div class=\"stream-trailer\" id=\"" +
  219. self.last_stream.name + "\">End stream: " +
  220. self.last_stream.name + "</div>\n")
  221. self.f.write("</div>\n")
  222. self.last_stream = None
  223. def _note(self, note_type, msg):
  224. """Write a note or one-off message to the log file.
  225. Args:
  226. note_type: The type of note. This must be a value supported by the
  227. accompanying multiplexed_log.css.
  228. msg: The note/message to log.
  229. Returns:
  230. Nothing.
  231. """
  232. self._terminate_stream()
  233. self.f.write("<div class=\"" + note_type + "\">\n<pre>")
  234. self.f.write(self._escape(msg))
  235. self.f.write("\n</pre></div>\n")
  236. def start_section(self, marker):
  237. """Begin a new nested section in the log file.
  238. Args:
  239. marker: The name of the section that is starting.
  240. Returns:
  241. Nothing.
  242. """
  243. self._terminate_stream()
  244. self.blocks.append(marker)
  245. blk_path = "/".join(self.blocks)
  246. self.f.write("<div class=\"section\" id=\"" + blk_path + "\">\n")
  247. self.f.write("<div class=\"section-header\" id=\"" + blk_path +
  248. "\">Section: " + blk_path + "</div>\n")
  249. def end_section(self, marker):
  250. """Terminate the current nested section in the log file.
  251. This function validates proper nesting of start_section() and
  252. end_section() calls. If a mismatch is found, an exception is raised.
  253. Args:
  254. marker: The name of the section that is ending.
  255. Returns:
  256. Nothing.
  257. """
  258. if (not self.blocks) or (marker != self.blocks[-1]):
  259. raise Exception("Block nesting mismatch: \"%s\" \"%s\"" %
  260. (marker, "/".join(self.blocks)))
  261. self._terminate_stream()
  262. blk_path = "/".join(self.blocks)
  263. self.f.write("<div class=\"section-trailer\" id=\"section-trailer-" +
  264. blk_path + "\">End section: " + blk_path + "</div>\n")
  265. self.f.write("</div>\n")
  266. self.blocks.pop()
  267. def section(self, marker):
  268. """Create a temporary section in the log file.
  269. This function creates a context manager for Python's "with" statement,
  270. which allows a certain portion of test code to be logged to a separate
  271. section of the log file.
  272. Usage:
  273. with log.section("somename"):
  274. some test code
  275. Args:
  276. marker: The name of the nested section.
  277. Returns:
  278. A context manager object.
  279. """
  280. return SectionCtxMgr(self, marker)
  281. def error(self, msg):
  282. """Write an error note to the log file.
  283. Args:
  284. msg: A message describing the error.
  285. Returns:
  286. Nothing.
  287. """
  288. self._note("error", msg)
  289. def warning(self, msg):
  290. """Write an warning note to the log file.
  291. Args:
  292. msg: A message describing the warning.
  293. Returns:
  294. Nothing.
  295. """
  296. self._note("warning", msg)
  297. def info(self, msg):
  298. """Write an informational note to the log file.
  299. Args:
  300. msg: An informational message.
  301. Returns:
  302. Nothing.
  303. """
  304. self._note("info", msg)
  305. def action(self, msg):
  306. """Write an action note to the log file.
  307. Args:
  308. msg: A message describing the action that is being logged.
  309. Returns:
  310. Nothing.
  311. """
  312. self._note("action", msg)
  313. def status_pass(self, msg):
  314. """Write a note to the log file describing test(s) which passed.
  315. Args:
  316. msg: A message describing passed test(s).
  317. Returns:
  318. Nothing.
  319. """
  320. self._note("status-pass", msg)
  321. def status_skipped(self, msg):
  322. """Write a note to the log file describing skipped test(s).
  323. Args:
  324. msg: A message describing passed test(s).
  325. Returns:
  326. Nothing.
  327. """
  328. self._note("status-skipped", msg)
  329. def status_fail(self, msg):
  330. """Write a note to the log file describing failed test(s).
  331. Args:
  332. msg: A message describing passed test(s).
  333. Returns:
  334. Nothing.
  335. """
  336. self._note("status-fail", msg)
  337. def get_stream(self, name, chained_file=None):
  338. """Create an object to log a single stream's data into the log file.
  339. This creates a "file-like" object that can be written to in order to
  340. write a single stream's data to the log file. The implementation will
  341. handle any required interleaving of data (from multiple streams) in
  342. the log, in a way that makes it obvious which stream each bit of data
  343. came from.
  344. Args:
  345. name: The name of the stream.
  346. chained_file: The file-like object to which all stream data should
  347. be logged to in addition to this log. Can be None.
  348. Returns:
  349. A file-like object.
  350. """
  351. return LogfileStream(self, name, chained_file)
  352. def get_runner(self, name, chained_file=None):
  353. """Create an object that executes processes and logs their output.
  354. Args:
  355. name: The name of this sub-process.
  356. chained_file: The file-like object to which all stream data should
  357. be logged to in addition to logfile. Can be None.
  358. Returns:
  359. A RunAndLog object.
  360. """
  361. return RunAndLog(self, name, chained_file)
  362. def write(self, stream, data, implicit=False):
  363. """Write stream data into the log file.
  364. This function should only be used by instances of LogfileStream or
  365. RunAndLog.
  366. Args:
  367. stream: The stream whose data is being logged.
  368. data: The data to log.
  369. implicit: Boolean indicating whether data actually appeared in the
  370. stream, or was implicitly generated. A valid use-case is to
  371. repeat a shell prompt at the start of each separate log
  372. section, which makes the log sections more readable in
  373. isolation.
  374. Returns:
  375. Nothing.
  376. """
  377. if stream != self.last_stream:
  378. self._terminate_stream()
  379. self.f.write("<div class=\"stream\" id=\"%s\">\n" % stream.name)
  380. self.f.write("<div class=\"stream-header\" id=\"" + stream.name +
  381. "\">Stream: " + stream.name + "</div>\n")
  382. self.f.write("<pre>")
  383. if implicit:
  384. self.f.write("<span class=\"implicit\">")
  385. self.f.write(self._escape(data))
  386. if implicit:
  387. self.f.write("</span>")
  388. self.last_stream = stream
  389. def flush(self):
  390. """Flush the log stream, to ensure correct log interleaving.
  391. Args:
  392. None.
  393. Returns:
  394. Nothing.
  395. """
  396. self.f.flush()