Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # Copyright 2015 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """ |
| 7 | Mail the content of standard input. |
| 8 | |
| 9 | Example usage: |
| 10 | Use pipe: |
| 11 | $ echo "Some content" |./gmail_lib.py -s "subject" abc@bb.com xyz@gmail.com |
| 12 | |
| 13 | Manually input: |
| 14 | $ ./gmail_lib.py -s "subject" abc@bb.com xyz@gmail.com |
| 15 | > Line 1 |
| 16 | > Line 2 |
| 17 | Ctrl-D to end standard input. |
| 18 | """ |
| 19 | import argparse |
| 20 | import base64 |
| 21 | import httplib2 |
| 22 | import logging |
| 23 | import sys |
| 24 | import os |
| 25 | from email.mime.text import MIMEText |
| 26 | |
| 27 | import common |
| 28 | from autotest_lib.client.common_lib import global_config |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 29 | from autotest_lib.client.common_lib.cros.graphite import autotest_stats |
Fang Deng | f3efacb | 2015-09-25 14:20:51 -0700 | [diff] [blame] | 30 | from chromite.lib import retry_util |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 31 | |
| 32 | try: |
| 33 | from apiclient.discovery import build as apiclient_build |
| 34 | from apiclient import errors as apiclient_errors |
| 35 | from oauth2client import file as oauth_client_fileio |
| 36 | except ImportError as e: |
| 37 | apiclient_build = None |
| 38 | logging.debug("API client for gmail disabled. %s", e) |
| 39 | |
| 40 | |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 41 | EMAIL_COUNT_KEY = 'emails.%s' |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 42 | DEFAULT_GMAIL_CREDS_PATH = global_config.global_config.get_config_value( |
| 43 | 'NOTIFICATIONS', 'gmail_api_credentials', default='') |
Fang Deng | f3efacb | 2015-09-25 14:20:51 -0700 | [diff] [blame] | 44 | RETRY_DELAY = 5 |
| 45 | RETRY_BACKOFF_FACTOR = 1.5 |
| 46 | MAX_RETRY = 10 |
| 47 | RETRIABLE_MSGS = [ |
| 48 | # User-rate limit exceeded |
| 49 | r'HttpError 429',] |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 50 | |
| 51 | class GmailApiException(Exception): |
| 52 | """Exception raised in accessing Gmail API.""" |
| 53 | |
| 54 | |
| 55 | class Message(): |
| 56 | """An email message.""" |
| 57 | |
| 58 | def __init__(self, to, subject, message_text): |
| 59 | """Initialize a message. |
| 60 | |
| 61 | @param to: The recievers saperated by comma. |
| 62 | e.g. 'abc@gmail.com,xyz@gmail.com' |
| 63 | @param subject: String, subject of the message |
| 64 | @param message_text: String, content of the message. |
| 65 | """ |
| 66 | self.to = to |
| 67 | self.subject = subject |
| 68 | self.message_text = message_text |
| 69 | |
| 70 | |
| 71 | def get_payload(self): |
| 72 | """Get the payload that can be sent to the Gmail API. |
| 73 | |
| 74 | @return: A dictionary representing the message. |
| 75 | """ |
| 76 | message = MIMEText(self.message_text) |
| 77 | message['to'] = self.to |
| 78 | message['subject'] = self.subject |
| 79 | return {'raw': base64.urlsafe_b64encode(message.as_string())} |
| 80 | |
| 81 | |
| 82 | class GmailApiClient(): |
| 83 | """Client that talks to Gmail API.""" |
| 84 | |
| 85 | def __init__(self, oauth_credentials): |
| 86 | """Init Gmail API client |
| 87 | |
| 88 | @param oauth_credentials: Path to the oauth credential token. |
| 89 | """ |
| 90 | if not apiclient_build: |
| 91 | raise GmailApiException('Cannot get apiclient library.') |
| 92 | |
| 93 | storage = oauth_client_fileio.Storage(oauth_credentials) |
| 94 | credentials = storage.get() |
| 95 | if not credentials or credentials.invalid: |
| 96 | raise GmailApiException('Invalid credentials for Gmail API, ' |
| 97 | 'could not send email.') |
| 98 | http = credentials.authorize(httplib2.Http()) |
| 99 | self._service = apiclient_build('gmail', 'v1', http=http) |
| 100 | |
| 101 | |
Fang Deng | f3efacb | 2015-09-25 14:20:51 -0700 | [diff] [blame] | 102 | def send_message(self, message, ignore_error=True): |
| 103 | """Send an email message. |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 104 | |
Fang Deng | f3efacb | 2015-09-25 14:20:51 -0700 | [diff] [blame] | 105 | @param message: Message to be sent. |
| 106 | @param ignore_error: If True, will ignore any HttpError. |
| 107 | """ |
| 108 | try: |
| 109 | # 'me' represents the default authorized user. |
| 110 | message = self._service.users().messages().send( |
| 111 | userId='me', body=message.get_payload()).execute() |
| 112 | logging.debug('Email sent: %s' , message['id']) |
| 113 | except apiclient_errors.HttpError as error: |
| 114 | if ignore_error: |
| 115 | logging.error('Failed to send email: %s', error) |
| 116 | else: |
| 117 | raise |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 118 | |
| 119 | |
| 120 | def get_default_creds_abspath(): |
| 121 | """Returns the abspath of the gmail api credentials file. |
| 122 | |
| 123 | @return: A path to the oauth2 credentials file. |
| 124 | """ |
| 125 | auth_creds = DEFAULT_GMAIL_CREDS_PATH |
| 126 | return (auth_creds if os.path.isabs(auth_creds) else |
| 127 | os.path.join(common.autotest_dir, auth_creds)) |
| 128 | |
| 129 | |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 130 | def send_email(to, subject, message_text, retry=True): |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 131 | """Send email. |
| 132 | |
| 133 | @param to: The recipients, separated by comma. |
| 134 | @param subject: Subject of the email. |
| 135 | @param message_text: Text to send. |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 136 | @param retry: If retry on retriable failures as defined in RETRIABLE_MSGS. |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 137 | """ |
| 138 | auth_creds = get_default_creds_abspath() |
| 139 | if not os.path.isfile(auth_creds): |
| 140 | logging.error('Failed to send email to %s: Credential file does not' |
| 141 | 'exist: %s. If this is a prod server, puppet should' |
| 142 | 'install it. If you need to be able to send email, ' |
| 143 | 'find the credential file from chromeos-admin repo and ' |
| 144 | 'copy it to %s', to, auth_creds, auth_creds) |
| 145 | return |
| 146 | client = GmailApiClient(oauth_credentials=auth_creds) |
| 147 | m = Message(to, subject, message_text) |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 148 | retry_count = MAX_RETRY if retry else 0 |
Fang Deng | f3efacb | 2015-09-25 14:20:51 -0700 | [diff] [blame] | 149 | |
| 150 | def _run(): |
| 151 | """Send the message.""" |
| 152 | client.send_message(m, ignore_error=False) |
| 153 | |
| 154 | def handler(exc): |
| 155 | """Check if exc is an HttpError and is retriable. |
| 156 | |
| 157 | @param exc: An exception. |
| 158 | |
| 159 | @return: True if is an retriable HttpError. |
| 160 | """ |
| 161 | if not isinstance(exc, apiclient_errors.HttpError): |
| 162 | return False |
| 163 | |
| 164 | error_msg = str(exc) |
| 165 | should_retry = any([msg in error_msg for msg in RETRIABLE_MSGS]) |
| 166 | if should_retry: |
| 167 | logging.warning('Will retry error %s', exc) |
| 168 | return should_retry |
| 169 | |
Fang Deng | 592640c | 2015-10-19 13:22:40 -0700 | [diff] [blame^] | 170 | autotest_stats.Counter(EMAIL_COUNT_KEY % 'total').increment() |
| 171 | try: |
| 172 | retry_util.GenericRetry( |
| 173 | handler, retry_count, _run, sleep=RETRY_DELAY, |
| 174 | backoff_factor=RETRY_BACKOFF_FACTOR) |
| 175 | except Exception: |
| 176 | autotest_stats.Counter(EMAIL_COUNT_KEY % 'fail').increment() |
| 177 | raise |
Fang Deng | 2e19bcf | 2015-03-18 17:49:29 -0700 | [diff] [blame] | 178 | |
| 179 | |
| 180 | if __name__ == '__main__': |
| 181 | logging.basicConfig(level=logging.DEBUG) |
| 182 | parser = argparse.ArgumentParser( |
| 183 | description=__doc__, formatter_class=argparse.RawTextHelpFormatter) |
| 184 | parser.add_argument('-s', '--subject', type=str, dest='subject', |
| 185 | required=True, help='Subject of the mail') |
| 186 | parser.add_argument('recipients', nargs='*', |
| 187 | help='Email addresses separated by space.') |
| 188 | args = parser.parse_args() |
| 189 | if not args.recipients or not args.subject: |
| 190 | print 'Requires both recipients and subject.' |
| 191 | sys.exit(1) |
| 192 | |
| 193 | message_text = sys.stdin.read() |
| 194 | send_email(','.join(args.recipients), args.subject , message_text) |