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
10import argparse
11import base64
12import logging
13import os
14import pwd
15import re
16import shutil
17import smtplib
18import socket
19import subprocess
20import sys
21import tempfile
22from email.mime.text import MIMEText
23
24
25# Setup logging
26logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
27log = logging.getLogger('oe-build-perf-report')
28
29
30def parse_args(argv):
31    """Parse command line arguments"""
32    description = """Email build perf test report"""
33    parser = argparse.ArgumentParser(
34        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
35        description=description)
36
37    parser.add_argument('--debug', '-d', action='store_true',
38                        help="Verbose logging")
39    parser.add_argument('--quiet', '-q', action='store_true',
40                        help="Only print errors")
41    parser.add_argument('--to', action='append',
42                        help="Recipients of the email")
43    parser.add_argument('--cc', action='append',
44                        help="Carbon copy recipients of the email")
45    parser.add_argument('--bcc', action='append',
46                        help="Blind carbon copy recipients of the email")
47    parser.add_argument('--subject', default="Yocto build perf test report",
48                        help="Email subject")
49    parser.add_argument('--outdir', '-o',
50                        help="Store files in OUTDIR. Can be used to preserve "
51                             "the email parts")
52    parser.add_argument('--text',
53                        help="Plain text message")
54
55    args = parser.parse_args(argv)
56
57    if not args.text:
58        parser.error("Please specify --text")
59
60    return args
61
62
63def send_email(text_fn, subject, recipients, copy=[], blind_copy=[]):
64    # Generate email message
65    with open(text_fn) as f:
66        msg = MIMEText("Yocto build performance test report.\n" + f.read(), 'plain')
67
68    pw_data = pwd.getpwuid(os.getuid())
69    full_name = pw_data.pw_gecos.split(',')[0]
70    email = os.environ.get('EMAIL',
71                           '{}@{}'.format(pw_data.pw_name, socket.getfqdn()))
72    msg['From'] = "{} <{}>".format(full_name, email)
73    msg['To'] = ', '.join(recipients)
74    if copy:
75        msg['Cc'] = ', '.join(copy)
76    if blind_copy:
77        msg['Bcc'] = ', '.join(blind_copy)
78    msg['Subject'] = subject
79
80    # Send email
81    with smtplib.SMTP('localhost') as smtp:
82        smtp.send_message(msg)
83
84
85def main(argv=None):
86    """Script entry point"""
87    args = parse_args(argv)
88    if args.quiet:
89        log.setLevel(logging.ERROR)
90    if args.debug:
91        log.setLevel(logging.DEBUG)
92
93    if args.outdir:
94        outdir = args.outdir
95        if not os.path.exists(outdir):
96            os.mkdir(outdir)
97    else:
98        outdir = tempfile.mkdtemp(dir='.')
99
100    try:
101        log.debug("Storing email parts in %s", outdir)
102        if args.to:
103            log.info("Sending email to %s", ', '.join(args.to))
104            if args.cc:
105                log.info("Copying to %s", ', '.join(args.cc))
106            if args.bcc:
107                log.info("Blind copying to %s", ', '.join(args.bcc))
108            send_email(args.text, args.subject, args.to, args.cc, args.bcc)
109    except subprocess.CalledProcessError as err:
110        log.error("%s, with output:\n%s", str(err), err.output.decode())
111        return 1
112    finally:
113        if not args.outdir:
114            log.debug("Wiping %s", outdir)
115            shutil.rmtree(outdir)
116
117    return 0
118
119
120if __name__ == "__main__":
121    sys.exit(main())
122