3 # Copyright (c) 2004 The Trustees of Princeton University (Trustees).
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
7 # $Id: mailer.py,v 1.10 2007/08/08 13:28:06 soltesz Exp $
17 logger = logging.getLogger("monitor")
20 FROM="monitor@planet-lab.org"
22 def reformat_for_rt(text):
23 lines = text.split("\n")
26 spaced_text += " %s\n" %line
30 def _setupRTenvironment():
31 os.environ['PATH'] = os.environ['PATH'] + ":" + monitorconfig.RT_WEB_TOOLS_PATH
32 os.environ['RTSERVER'] = monitorconfig.RT_WEB_SERVER
33 os.environ['RTUSER'] = monitorconfig.RT_WEB_USER
34 os.environ['RTPASSWD'] = monitorconfig.RT_WEB_PASSWORD
35 os.environ['RTDEBUG'] = monitorconfig.RT_WEB_DEBUG
38 def setTicketStatus(ticket_id, status):
40 if ticket_id == None or ticket_id == "":
43 cmd = "rt edit ticket/%s set status=%s" % (ticket_id, status)
44 (f_in, f_out, f_err) = os.popen3(cmd)
46 l_values = value.split('\n')
47 return "".join(l_values).strip()
49 def getTicketStatus(ticket_id):
51 if ticket_id == None or ticket_id == "":
54 cmd = "rt show -t ticket -f id,subject,status,queue,created %s" % (ticket_id)
55 (f_in, f_out, f_err) = os.popen3(cmd)
57 l_values = value.split('\n')
60 if len(line) == 0: continue
61 vals = line.split(':')
63 r_values[key] = ":".join(vals[1:])
64 r_values[key] = r_values[key].strip()
66 r_values['Created'] = calendar.timegm(time.strptime(r_values['Created']))
69 def setAdminCCViaRT(ticket_id, to):
70 # Set ENV Variables/PATH
72 if ticket_id == None or ticket_id == "":
73 raise Exception("ERROR: ticket_id must be set to some integer value")
75 # This will raise an exception if it is not a valid id.
76 i_ticket_id = int(ticket_id)
78 # create a comma-separated list
80 cmd = "rt edit ticket/%s set admincc='%s'" % (ticket_id, s_to)
81 (f_in, f_out, f_err) = os.popen3(cmd)
83 l_values = value.split()
84 f_in.close() ; f_out.close() ; f_err.close()
85 if len(l_values) > 3 and "updated" in l_values[3]:
90 print "ERROR: RT failed to update AdminCC for ticket %s" % ticket_id
94 def setSubjectViaRT(ticket_id, subject):
95 # Set ENV Variables/PATH
97 if ticket_id == None or ticket_id == "":
98 raise Exception("ERROR: ticket_id must be set to some integer value")
100 # This will raise an exception if it is not a valid id.
101 i_ticket_id = int(ticket_id)
103 cmd = "rt edit ticket/%s set subject='%s'" % (ticket_id, subject)
104 (f_in, f_out, f_err) = os.popen3(cmd)
106 l_values = value.split()
107 f_in.close() ; f_out.close() ; f_err.close()
108 if len(l_values) > 3 and "updated" in l_values[3]:
112 print "VALUE:", value
113 print "ERROR: RT failed to update subject for ticket %s" % ticket_id
118 def addCommentViaRT(ticket_id, comment):
119 # Set ENV Variables/PATH
120 _setupRTenvironment()
121 if ticket_id == None or ticket_id == "":
122 raise Exception("ERROR: ticket_id must be set to some integer value")
124 # This will raise an exception if it is not a valid id.
125 i_ticket_id = int(ticket_id)
127 cmd = "rt comment -m '%s' ticket/%s" % (comment, i_ticket_id)
128 (f_in, f_out, f_err) = os.popen3(cmd)
130 l_values = value.split()
131 f_in.close() ; f_out.close() ; f_err.close()
132 if len(l_values) > 1 and "recorded" in l_values[1]:
137 f_in.close() ; f_out.close() ; f_err.close()
138 print "ERROR: RT failed to add comment to id %s" % ticket_id
142 def closeTicketViaRT(ticket_id, comment):
143 # Set ENV Variables/PATH
144 _setupRTenvironment()
145 if ticket_id == None or ticket_id == "":
146 raise Exception("ERROR: ticket_id must be set to some integer value")
148 # This will raise an exception if it is not a valid id.
149 i_ticket_id = int(ticket_id)
151 # Append comment to RT ticket
152 addCommentViaRT(ticket_id, comment)
155 cmd = "rt edit ticket/%s set status=resolved" % i_ticket_id
156 (f_in, f_out, f_err) = os.popen3(cmd)
161 l_values = value.split()
162 if len(l_values) >= 4 and "updated" in l_values[3]:
166 print "VALUE: ", value
168 print "FAILED to resolve Ticket %s" % ticket_id
169 print "FAILED to resolve Ticket %s" % i_ticket_id
173 def emailViaRT(subject, text, to, ticket_id=None):
174 if ticket_id == None or ticket_id == "":
176 return emailViaRT_NoTicket(subject, text, to)
179 # Set ENV Variables/PATH
180 _setupRTenvironment()
182 if config.mail and not config.debug:
183 setSubjectViaRT(ticket_id, subject)
184 setAdminCCViaRT(ticket_id, to)
186 cmd = "rt correspond -m - %s" % ticket_id
187 (f_in, f_out, f_err) = os.popen3(cmd)
193 # TODO: rt doesn't write to stderr on error!!!
195 raise Exception, f_err.read()
198 f_out.close(); del f_out
199 f_err.close(); del f_err
205 def emailViaRT_NoTicket(subject, text, to):
206 """Use RT command line tools to send email.
207 return the generated RT ticket ID number.
211 if config.mail and config.debug:
214 # Set ENV Variables/PATH
215 _setupRTenvironment()
217 # NOTE: AdminCc: (in PLC's RT configuration) gets an email sent.
218 # This is not the case (surprisingly) for Cc:
219 input_text = "Subject: %s\n"
220 input_text += "Requestor: monitor@planet-lab.org\n"
221 input_text += "id: ticket/new\n"
222 input_text += "Queue: Monitor\n"
224 input_text += "AdminCc: %s\n" % recipient
225 input_text += "Text: %s"
227 # Add a space for each new line to get RT to accept the file.
228 spaced_text = reformat_for_rt(text)
230 if config.mail and not config.debug:
231 cmd = "rt create -i -t ticket"
232 (f_in, f_out, f_err) = os.popen3(cmd)
233 f_in.write(input_text % (subject, spaced_text))
238 # TODO: rt doesn't write to stderr on error!!!
240 raise Exception, f_err.read()
242 print "MAILER: ticket value == %s" % value.split()[2]
243 i_ticket = int(value.split()[2])
244 # clean up the child process.
245 f_in.close(); del f_in
246 f_out.close(); del f_out
247 f_err.close(); del f_err
249 elif config.mail and config.debug:
250 email(subject, spaced_text, to)
257 def email(subject, text, to):
258 """Create a mime-message that will render HTML in popular
259 MUAs, text in better ones"""
264 if (config.mail and config.debug) or (not config.mail and not config.debug and config.bcc):
267 out = cStringIO.StringIO() # output buffer for our message
268 txtin = cStringIO.StringIO(text)
270 writer = MimeWriter.MimeWriter(out)
272 # set up some basic headers... we put subject here
273 # because smtplib.sendmail expects it to be in the
276 writer.addheader("Subject", subject)
277 if to.__class__ == [].__class__ :
278 writer.addheader("To", to[0])
280 for dest in to[1:len(to)]:
283 writer.addheader("Cc", cc)
285 writer.addheader("To", to)
287 if config.bcc and not config.debug:
288 writer.addheader("Bcc", config.email)
290 writer.addheader("Reply-To", 'monitor@planet-lab.org')
292 writer.addheader("MIME-Version", "1.0")
294 # start the multipart section of the message
295 # multipart/alternative seems to work better
296 # on some MUAs than multipart/mixed
298 writer.startmultipartbody("alternative")
299 writer.flushheaders()
301 # the plain text section
303 subpart = writer.nextpart()
304 subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
305 pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
306 mimetools.encode(txtin, pout, 'quoted-printable')
309 # Now that we're done, close our writer and
310 # return the message body
318 # mail and debug, 'to' changed at the beginning'
319 # nomail, but report who I'd send to.
321 for mta in [MTA, 'golf.cs.princeton.edu']:
323 # This is normal operation
328 server = smtplib.SMTP(mta)
329 #server = smtplib.SMTP('golf.cs.princeton.edu')
330 server.sendmail(FROM, to, msg)
331 if config.bcc and not config.debug:
332 server.sendmail(FROM, config.email, msg)
334 except Exception, err:
335 print "Mailer error1: failed using MTA(%s) with: %s" % (mta, err)
337 elif not config.debug and not config.mail and config.bcc:
338 for mta in [MTA, 'golf.cs.princeton.edu']:
340 server = smtplib.SMTP(mta)
341 server.sendmail(FROM, to, msg)
343 except Exception, err:
344 print "Mailer error2: failed using MTA(%s) with: %s" % (mta, err)
346 #print "Would mail %s" %to
347 logger.debug("Would send mail to %s" % to)
349 if __name__=="__main__":
353 #email("[spam] bcc test from golf.cs.princeton.edu",
354 # "It gets to both recipients",
355 # "soltesz@cs.utk.edu")
356 #emailViaRT("rt via golf",
357 # "It gets to both recipients",
358 # "soltesz@cs.utk.edu")
359 email("Re: [PL #21323] TEST 7",
360 mailtxt.newbootcd_one[1] % {'hostname_list':"hostname list..."},
361 ['monitor@planet-lab.org'])
362 #print "ticketid: %d" % id
363 #id = plc.siteId(["alice.cs.princeton.edu"])
366 #email('TEST', emailTxt.mailtxt.ssh % {'hostname': "ALICE.cs.princeton.edu"}, "tech-" + id + "@sites.planet-lab.org")
369 #email("TEST111", "I'd like to see if this works anywhere", ["soltesz@cs.princeton.edu", "soltesz@cs.utk.edu"])
370 #print "mailer does nothing in main()"