blob: 6ce627a51ee89cc03efaa6f3bcf9289e6cb9c0bf [file] [log] [blame]
showard27f33872009-04-07 18:20:53 +00001import traceback, socket, os, time, smtplib, re, sys, getpass, logging
showard170873e2009-01-07 00:22:26 +00002import common
3from autotest_lib.client.common_lib import global_config
4
5CONFIG_SECTION = 'SCHEDULER'
6
7class EmailNotificationManager(object):
8 def __init__(self):
9 self._emails = []
10
11 self._from_address = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +000012 CONFIG_SECTION, "notify_email_from", default=getpass.getuser())
showard170873e2009-01-07 00:22:26 +000013
14 self._notify_address = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +000015 CONFIG_SECTION, "notify_email", default='')
showard170873e2009-01-07 00:22:26 +000016
17
18 def send_email(self, to_string, subject, body):
19 """Mails out emails to the addresses listed in to_string.
20
21 to_string is split into a list which can be delimited by any of:
22 ';', ',', ':' or any whitespace
23 """
24 # Create list from string removing empty strings from the list.
25 to_list = [x for x in re.split('\s|,|;|:', to_string) if x]
26 if not to_list:
27 return
28
29 msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
30 self._from_address, ', '.join(to_list), subject, body)
31 try:
32 mailer = smtplib.SMTP('localhost')
33 try:
34 mailer.sendmail(self._from_address, to_list, msg)
35 finally:
36 mailer.quit()
37 except Exception:
showardf098ebd2009-06-10 00:13:33 +000038 logging.exception('Sending email failed:')
showard170873e2009-01-07 00:22:26 +000039
40
41 def enqueue_notify_email(self, subject, message):
showarded2afea2009-07-07 20:54:07 +000042 logging.error(subject + '\n' + message)
showard170873e2009-01-07 00:22:26 +000043 if not self._notify_address:
44 return
45
46 body = 'Subject: ' + subject + '\n'
47 body += "%s / %s / %s\n%s" % (socket.gethostname(),
48 os.getpid(),
49 time.strftime("%X %x"), message)
50 self._emails.append(body)
51
52
53 def send_queued_emails(self):
54 if not self._emails:
55 return
56 subject = 'Scheduler notifications from ' + socket.gethostname()
57 separator = '\n' + '-' * 40 + '\n'
58 body = separator.join(self._emails)
59
60 self.send_email(self._notify_address, subject, body)
61 self._emails = []
62
63
64 def log_stacktrace(self, reason):
showard27f33872009-04-07 18:20:53 +000065 logging.exception(reason)
showard170873e2009-01-07 00:22:26 +000066 message = "EXCEPTION: %s\n%s" % (reason, traceback.format_exc())
showard170873e2009-01-07 00:22:26 +000067 self.enqueue_notify_email("monitor_db exception", message)
68
69
70manager = EmailNotificationManager()