blob: 66b1c69c1a07b0b3fac0c3cf2aabe332fecfeed9 [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:
showardb593fa82009-09-09 15:30:24 +000036 try:
37 mailer.quit()
38 except:
39 logging.exception('mailer.quit() failed:')
showard170873e2009-01-07 00:22:26 +000040 except Exception:
showardf098ebd2009-06-10 00:13:33 +000041 logging.exception('Sending email failed:')
showard170873e2009-01-07 00:22:26 +000042
43
44 def enqueue_notify_email(self, subject, message):
showarded2afea2009-07-07 20:54:07 +000045 logging.error(subject + '\n' + message)
showard170873e2009-01-07 00:22:26 +000046 if not self._notify_address:
47 return
48
49 body = 'Subject: ' + subject + '\n'
50 body += "%s / %s / %s\n%s" % (socket.gethostname(),
51 os.getpid(),
52 time.strftime("%X %x"), message)
53 self._emails.append(body)
54
55
56 def send_queued_emails(self):
57 if not self._emails:
58 return
59 subject = 'Scheduler notifications from ' + socket.gethostname()
60 separator = '\n' + '-' * 40 + '\n'
61 body = separator.join(self._emails)
62
63 self.send_email(self._notify_address, subject, body)
64 self._emails = []
65
66
67 def log_stacktrace(self, reason):
showard27f33872009-04-07 18:20:53 +000068 logging.exception(reason)
showard170873e2009-01-07 00:22:26 +000069 message = "EXCEPTION: %s\n%s" % (reason, traceback.format_exc())
showard170873e2009-01-07 00:22:26 +000070 self.enqueue_notify_email("monitor_db exception", message)
71
72
73manager = EmailNotificationManager()