1 import traceback
, socket
, os
, time
, smtplib
, re
, sys
, getpass
, logging
3 from autotest_lib
.client
.common_lib
import global_config
5 CONFIG_SECTION
= 'SCHEDULER'
7 CONFIG_SECTION_SMTP
= 'SERVER'
9 class EmailNotificationManager(object):
13 self
._from
_address
= global_config
.global_config
.get_config_value(
14 CONFIG_SECTION
, "notify_email_from", default
=getpass
.getuser())
16 self
._notify
_address
= global_config
.global_config
.get_config_value(
17 CONFIG_SECTION
, "notify_email", default
='')
19 self
._smtp
_server
= global_config
.global_config
.get_config_value(
20 CONFIG_SECTION_SMTP
, "smtp_server", default
='localhost')
22 self
._smtp
_port
= global_config
.global_config
.get_config_value(
23 CONFIG_SECTION_SMTP
, "smtp_port", default
=None)
25 self
._smtp
_user
= global_config
.global_config
.get_config_value(
26 CONFIG_SECTION_SMTP
, "smtp_user", default
='')
28 self
._smtp
_password
= global_config
.global_config
.get_config_value(
29 CONFIG_SECTION_SMTP
, "smtp_password", default
='')
31 def send_email(self
, to_string
, subject
, body
):
32 """Mails out emails to the addresses listed in to_string.
34 to_string is split into a list which can be delimited by any of:
35 ';', ',', ':' or any whitespace
37 # Create list from string removing empty strings from the list.
38 to_list
= [x
for x
in re
.split('\s|,|;|:', to_string
) if x
]
42 msg
= "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
43 self
._from
_address
, ', '.join(to_list
), subject
, body
)
45 mailer
= smtplib
.SMTP(self
._smtp
_server
, self
._smtp
_port
)
48 mailer
.login(self
._smtp
_user
, self
._smtp
_password
)
49 mailer
.sendmail(self
._from
_address
, to_list
, msg
)
54 logging
.exception('mailer.quit() failed:')
56 logging
.exception('Sending email failed:')
59 def enqueue_notify_email(self
, subject
, message
):
60 logging
.error(subject
+ '\n' + message
)
61 if not self
._notify
_address
:
64 body
= 'Subject: ' + subject
+ '\n'
65 body
+= "%s / %s / %s\n%s" % (socket
.gethostname(),
67 time
.strftime("%X %x"), message
)
68 self
._emails
.append(body
)
71 def send_queued_emails(self
):
74 subject
= 'Scheduler notifications from ' + socket
.gethostname()
75 separator
= '\n' + '-' * 40 + '\n'
76 body
= separator
.join(self
._emails
)
78 self
.send_email(self
._notify
_address
, subject
, body
)
82 def log_stacktrace(self
, reason
):
83 logging
.exception(reason
)
84 message
= "EXCEPTION: %s\n%s" % (reason
, traceback
.format_exc())
85 self
.enqueue_notify_email("monitor_db exception", message
)
88 manager
= EmailNotificationManager()