oe-build-perf-report-email.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #!/usr/bin/python3
  2. #
  3. # Send build performance test report emails
  4. #
  5. # Copyright (c) 2017, Intel Corporation.
  6. #
  7. # This program is free software; you can redistribute it and/or modify it
  8. # under the terms and conditions of the GNU General Public License,
  9. # version 2, as published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. # more details.
  15. #
  16. import argparse
  17. import base64
  18. import logging
  19. import os
  20. import pwd
  21. import re
  22. import shutil
  23. import smtplib
  24. import socket
  25. import subprocess
  26. import sys
  27. import tempfile
  28. from email.mime.image import MIMEImage
  29. from email.mime.multipart import MIMEMultipart
  30. from email.mime.text import MIMEText
  31. # Setup logging
  32. logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
  33. log = logging.getLogger('oe-build-perf-report')
  34. # Find js scaper script
  35. SCRAPE_JS = os.path.join(os.path.dirname(__file__), '..', 'lib', 'build_perf',
  36. 'scrape-html-report.js')
  37. if not os.path.isfile(SCRAPE_JS):
  38. log.error("Unableto find oe-build-perf-report-scrape.js")
  39. sys.exit(1)
  40. class ReportError(Exception):
  41. """Local errors"""
  42. pass
  43. def check_utils():
  44. """Check that all needed utils are installed in the system"""
  45. missing = []
  46. for cmd in ('phantomjs', 'optipng'):
  47. if not shutil.which(cmd):
  48. missing.append(cmd)
  49. if missing:
  50. log.error("The following tools are missing: %s", ' '.join(missing))
  51. sys.exit(1)
  52. def parse_args(argv):
  53. """Parse command line arguments"""
  54. description = """Email build perf test report"""
  55. parser = argparse.ArgumentParser(
  56. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  57. description=description)
  58. parser.add_argument('--debug', '-d', action='store_true',
  59. help="Verbose logging")
  60. parser.add_argument('--quiet', '-q', action='store_true',
  61. help="Only print errors")
  62. parser.add_argument('--to', action='append',
  63. help="Recipients of the email")
  64. parser.add_argument('--cc', action='append',
  65. help="Carbon copy recipients of the email")
  66. parser.add_argument('--bcc', action='append',
  67. help="Blind carbon copy recipients of the email")
  68. parser.add_argument('--subject', default="Yocto build perf test report",
  69. help="Email subject")
  70. parser.add_argument('--outdir', '-o',
  71. help="Store files in OUTDIR. Can be used to preserve "
  72. "the email parts")
  73. parser.add_argument('--text',
  74. help="Plain text message")
  75. parser.add_argument('--html',
  76. help="HTML peport generated by oe-build-perf-report")
  77. parser.add_argument('--phantomjs-args', action='append',
  78. help="Extra command line arguments passed to PhantomJS")
  79. args = parser.parse_args(argv)
  80. if not args.html and not args.text:
  81. parser.error("Please specify --html and/or --text")
  82. return args
  83. def decode_png(infile, outfile):
  84. """Parse/decode/optimize png data from a html element"""
  85. with open(infile) as f:
  86. raw_data = f.read()
  87. # Grab raw base64 data
  88. b64_data = re.sub('^.*href="data:image/png;base64,', '', raw_data, 1)
  89. b64_data = re.sub('">.+$', '', b64_data, 1)
  90. # Replace file with proper decoded png
  91. with open(outfile, 'wb') as f:
  92. f.write(base64.b64decode(b64_data))
  93. subprocess.check_output(['optipng', outfile], stderr=subprocess.STDOUT)
  94. def mangle_html_report(infile, outfile, pngs):
  95. """Mangle html file into a email compatible format"""
  96. paste = True
  97. png_dir = os.path.dirname(outfile)
  98. with open(infile) as f_in:
  99. with open(outfile, 'w') as f_out:
  100. for line in f_in.readlines():
  101. stripped = line.strip()
  102. # Strip out scripts
  103. if stripped == '<!--START-OF-SCRIPTS-->':
  104. paste = False
  105. elif stripped == '<!--END-OF-SCRIPTS-->':
  106. paste = True
  107. elif paste:
  108. if re.match('^.+href="data:image/png;base64', stripped):
  109. # Strip out encoded pngs (as they're huge in size)
  110. continue
  111. elif 'www.gstatic.com' in stripped:
  112. # HACK: drop references to external static pages
  113. continue
  114. # Replace charts with <img> elements
  115. match = re.match('<div id="(?P<id>\w+)"', stripped)
  116. if match and match.group('id') in pngs:
  117. f_out.write('<img src="cid:{}"\n'.format(match.group('id')))
  118. else:
  119. f_out.write(line)
  120. def scrape_html_report(report, outdir, phantomjs_extra_args=None):
  121. """Scrape html report into a format sendable by email"""
  122. tmpdir = tempfile.mkdtemp(dir='.')
  123. log.debug("Using tmpdir %s for phantomjs output", tmpdir)
  124. if not os.path.isdir(outdir):
  125. os.mkdir(outdir)
  126. if os.path.splitext(report)[1] not in ('.html', '.htm'):
  127. raise ReportError("Invalid file extension for report, needs to be "
  128. "'.html' or '.htm'")
  129. try:
  130. log.info("Scraping HTML report with PhangomJS")
  131. extra_args = phantomjs_extra_args if phantomjs_extra_args else []
  132. subprocess.check_output(['phantomjs', '--debug=true'] + extra_args +
  133. [SCRAPE_JS, report, tmpdir],
  134. stderr=subprocess.STDOUT)
  135. pngs = []
  136. images = []
  137. for fname in os.listdir(tmpdir):
  138. base, ext = os.path.splitext(fname)
  139. if ext == '.png':
  140. log.debug("Decoding %s", fname)
  141. decode_png(os.path.join(tmpdir, fname),
  142. os.path.join(outdir, fname))
  143. pngs.append(base)
  144. images.append(fname)
  145. elif ext in ('.html', '.htm'):
  146. report_file = fname
  147. else:
  148. log.warning("Unknown file extension: '%s'", ext)
  149. #shutil.move(os.path.join(tmpdir, fname), outdir)
  150. log.debug("Mangling html report file %s", report_file)
  151. mangle_html_report(os.path.join(tmpdir, report_file),
  152. os.path.join(outdir, report_file), pngs)
  153. return (os.path.join(outdir, report_file),
  154. [os.path.join(outdir, i) for i in images])
  155. finally:
  156. shutil.rmtree(tmpdir)
  157. def send_email(text_fn, html_fn, image_fns, subject, recipients, copy=[],
  158. blind_copy=[]):
  159. """Send email"""
  160. # Generate email message
  161. text_msg = html_msg = None
  162. if text_fn:
  163. with open(text_fn) as f:
  164. text_msg = MIMEText("Yocto build performance test report.\n" +
  165. f.read(), 'plain')
  166. if html_fn:
  167. html_msg = msg = MIMEMultipart('related')
  168. with open(html_fn) as f:
  169. html_msg.attach(MIMEText(f.read(), 'html'))
  170. for img_fn in image_fns:
  171. # Expect that content id is same as the filename
  172. cid = os.path.splitext(os.path.basename(img_fn))[0]
  173. with open(img_fn, 'rb') as f:
  174. image_msg = MIMEImage(f.read())
  175. image_msg['Content-ID'] = '<{}>'.format(cid)
  176. html_msg.attach(image_msg)
  177. if text_msg and html_msg:
  178. msg = MIMEMultipart('alternative')
  179. msg.attach(text_msg)
  180. msg.attach(html_msg)
  181. elif text_msg:
  182. msg = text_msg
  183. elif html_msg:
  184. msg = html_msg
  185. else:
  186. raise ReportError("Neither plain text nor html body specified")
  187. pw_data = pwd.getpwuid(os.getuid())
  188. full_name = pw_data.pw_gecos.split(',')[0]
  189. email = os.environ.get('EMAIL',
  190. '{}@{}'.format(pw_data.pw_name, socket.getfqdn()))
  191. msg['From'] = "{} <{}>".format(full_name, email)
  192. msg['To'] = ', '.join(recipients)
  193. if copy:
  194. msg['Cc'] = ', '.join(copy)
  195. if blind_copy:
  196. msg['Bcc'] = ', '.join(blind_copy)
  197. msg['Subject'] = subject
  198. # Send email
  199. with smtplib.SMTP('localhost') as smtp:
  200. smtp.send_message(msg)
  201. def main(argv=None):
  202. """Script entry point"""
  203. args = parse_args(argv)
  204. if args.quiet:
  205. log.setLevel(logging.ERROR)
  206. if args.debug:
  207. log.setLevel(logging.DEBUG)
  208. check_utils()
  209. if args.outdir:
  210. outdir = args.outdir
  211. if not os.path.exists(outdir):
  212. os.mkdir(outdir)
  213. else:
  214. outdir = tempfile.mkdtemp(dir='.')
  215. try:
  216. log.debug("Storing email parts in %s", outdir)
  217. html_report = images = None
  218. if args.html:
  219. html_report, images = scrape_html_report(args.html, outdir,
  220. args.phantomjs_args)
  221. if args.to:
  222. log.info("Sending email to %s", ', '.join(args.to))
  223. if args.cc:
  224. log.info("Copying to %s", ', '.join(args.cc))
  225. if args.bcc:
  226. log.info("Blind copying to %s", ', '.join(args.bcc))
  227. send_email(args.text, html_report, images, args.subject,
  228. args.to, args.cc, args.bcc)
  229. except subprocess.CalledProcessError as err:
  230. log.error("%s, with output:\n%s", str(err), err.output.decode())
  231. return 1
  232. except ReportError as err:
  233. log.error(err)
  234. return 1
  235. finally:
  236. if not args.outdir:
  237. log.debug("Wiping %s", outdir)
  238. shutil.rmtree(outdir)
  239. return 0
  240. if __name__ == "__main__":
  241. sys.exit(main())