+ introduced rt command line emailViaRT
[monitor.git] / mailer.py
1 #!/usr/bin/python2
2 #
3 # Copyright (c) 2004  The Trustees of Princeton University (Trustees).
4 #
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
6 #
7 # $Id: mailer.py,v 1.8 2007/06/29 12:42:22 soltesz Exp $
8 from emailTxt import *
9 import smtplib
10 from config import config
11 import logging
12 import os
13 import time
14
15 config = config()
16 logger = logging.getLogger("monitor")
17
18 MTA="localhost"
19 FROM="monitor@planet-lab.org"
20
21 def reformat_for_rt(text):
22         lines = text.split("\n")
23         spaced_text = ""
24         for line in lines:
25                 spaced_text += " %s\n" %line
26         return spaced_text
27                 
28
29 def emailViaRT(subject, text, to):
30         """Use RT command line tools to send email.
31                 return the generated RT ticket ID number.
32         """
33         i_ticket = 0
34
35         if config.mail and config.debug:
36                 to = [config.email]
37
38         os.environ['PATH'] = os.environ['PATH'] + ":/home/soltesz/rpm/opt/rt3/bin/"
39         os.environ['RTSERVER'] = "https://rt.planet-lab.org/"
40         os.environ['RTUSER']   = "monitor"
41         os.environ['RTPASSWD'] = "ssorcmor"
42         os.environ['RTDEBUG'] = "0"
43         # NOTE: AdminCc: (in PLC's RT configuration) gets an email sent.
44         # This is not the case (surprisingly) for Cc:
45         input_text  = "Subject: %s\n"
46         input_text += "Requestor: monitor@planet-lab.org\n"
47         input_text += "id: ticket/new\n"
48         input_text += "Queue: Monitor\n"
49         for recipient in to:
50                 input_text += "AdminCc: %s\n" % recipient
51         input_text += "Text: %s"
52
53         spaced_text = reformat_for_rt(text)
54         #if config.debug:
55         #       print input_text % (subject, "") 
56
57         if config.mail and not config.debug:
58                 cmd = "rt create -i -t ticket"
59                 (f_in, f_out, f_err) = os.popen3(cmd)
60                 f_in.write(input_text % (subject, spaced_text))
61                 f_in.flush()
62                 f_in.close()
63                 value = f_out.read()
64
65                 # TODO: rt doesn't write to stderr on error!!!
66                 if value == "":
67                         raise Exception, f_err.read()
68
69                 i_ticket = int(value.split()[2])
70                 # clean up the child process.
71                 f_in.close();  del f_in
72                 f_out.close(); del f_out
73                 f_err.close(); del f_err
74                 os.wait()
75         elif config.mail and config.debug:
76                 email(subject, spaced_text, to)
77                 i_ticket = 0
78         else:
79                 i_ticket = 0
80
81         return i_ticket
82
83 def email(subject, text, to):
84         """Create a mime-message that will render HTML in popular
85         MUAs, text in better ones"""
86         import MimeWriter
87         import mimetools
88         import cStringIO
89
90         if config.mail and config.debug:
91                 to = [config.email]
92
93         out = cStringIO.StringIO() # output buffer for our message 
94         txtin = cStringIO.StringIO(text)
95
96         writer = MimeWriter.MimeWriter(out)
97         #
98         # set up some basic headers... we put subject here
99         # because smtplib.sendmail expects it to be in the
100         # message body
101         #
102         writer.addheader("Subject", subject)
103         if to.__class__ == [].__class__ :       
104                 writer.addheader("To", to[0])
105                 cc = ""
106                 for dest in to[1:len(to)]:
107                         cc +="%s, " % dest
108                 cc = cc.rstrip(", ") 
109                 writer.addheader("Cc", cc)
110         else:
111                 writer.addheader("To", to)
112
113         if config.bcc and not config.debug:
114                 writer.addheader("Bcc", config.email)
115
116         writer.addheader("Reply-To", 'monitor@planet-lab.org')
117                 
118         writer.addheader("MIME-Version", "1.0")
119         #
120         # start the multipart section of the message
121         # multipart/alternative seems to work better
122         # on some MUAs than multipart/mixed
123         #
124         writer.startmultipartbody("alternative")
125         writer.flushheaders()
126         #
127         # the plain text section
128         #
129         subpart = writer.nextpart()
130         subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
131         pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
132         mimetools.encode(txtin, pout, 'quoted-printable')
133         txtin.close()
134         #
135         # Now that we're done, close our writer and
136         # return the message body
137         #
138         writer.lastpart()
139         msg = out.getvalue()
140         out.close()
141
142         # three cases:
143         #       mail but no-debug
144         #       mail and debug, 'to' changed at the beginning'
145         #   nomail, but report who I'd send to.
146         if config.mail:
147                 try:
148                         # This is normal operation
149                         server = smtplib.SMTP(MTA)
150                         server.sendmail(FROM, to,  msg)
151                         if config.bcc and not config.debug:
152                                 server.sendmail(FROM, config.email,  msg)
153                         server.quit()
154                 except Exception, err:
155                         print "Mailer error: %s" % err
156         else:
157                 #print "Would mail %s" %to
158                 logger.debug("Would send mail to %s" % to)
159
160 if __name__=="__main__":
161         import smtplib
162         import emailTxt
163         import plc 
164         #email("[spam] bcc test from golf.cs.princeton.edu", 
165         #         "It gets to both recipients", 
166         #         "soltesz@cs.utk.edu")
167         #emailViaRT("rt via golf", 
168         #         "It gets to both recipients", 
169         #         "soltesz@cs.utk.edu")
170         id = emailViaRT("TEST 7", 
171                            mailtxt.newbootcd_one[1] % {'hostname_list':"hostname list..."},
172                            ["soltesz@cs.utk.edu", "soltesz@romcross.org", "soltesz@cs.princeton.edu"])
173         print "ticketid: %d" % id
174         #id = plc.siteId(["alice.cs.princeton.edu"])
175         #print id
176         #if id:
177                 #email('TEST', emailTxt.mailtxt.ssh % {'hostname': "ALICE.cs.princeton.edu"}, "tech-" + id + "@sites.planet-lab.org")
178         #else:
179         #       print "No dice."
180         #email("TEST111", "I'd like to see if this works anywhere", ["soltesz@cs.princeton.edu", "soltesz@cs.utk.edu"])
181         #print "mailer does nothing in main()"