multiplexed_log.py 14 KB

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