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

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