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 $
10 from config import config
16 logger = logging.getLogger("monitor")
19 FROM="monitor@planet-lab.org"
21 def reformat_for_rt(text):
22 lines = text.split("\n")
25 spaced_text += " %s\n" %line
29 def _setupRTenvironment():
30 os.environ['PATH'] = os.environ['PATH'] + ":/home/soltesz/local/bin/"
31 os.environ['RTSERVER'] = "https://rt.planet-lab.org/"
32 os.environ['RTUSER'] = "monitor"
33 os.environ['RTPASSWD'] = "ssorcmor"
34 os.environ['RTDEBUG'] = "0"
37 def setTicketStatus(ticket_id, status):
39 if ticket_id == None or ticket_id == "":
42 cmd = "rt edit ticket/%s set status=%s" % (ticket_id, status)
43 (f_in, f_out, f_err) = os.popen3(cmd)
45 l_values = value.split('\n')
46 return "".join(l_values).strip()
48 def getTicketStatus(ticket_id):
50 if ticket_id == None or ticket_id == "":
53 cmd = "rt show -t ticket -f id,subject,status,queue %s" % (ticket_id)
54 (f_in, f_out, f_err) = os.popen3(cmd)
56 l_values = value.split('\n')
59 if len(line) == 0: continue
60 vals = line.split(':')
62 r_values[key] = "".join(vals[1:])
63 r_values[key] = r_values[key].strip()
66 def setAdminCCViaRT(ticket_id, to):
67 # Set ENV Variables/PATH
69 if ticket_id == None or ticket_id == "":
70 raise Exception("ERROR: ticket_id must be set to some integer value")
72 # This will raise an exception if it is not a valid id.
73 i_ticket_id = int(ticket_id)
75 # create a comma-separated list
77 cmd = "rt edit ticket/%s set admincc='%s'" % (ticket_id, s_to)
78 (f_in, f_out, f_err) = os.popen3(cmd)
80 l_values = value.split()
81 f_in.close() ; f_out.close() ; f_err.close()
82 if len(l_values) > 3 and "updated" in l_values[3]:
87 print "ERROR: RT failed to update AdminCC for ticket %s" % ticket_id
91 def setSubjectViaRT(ticket_id, subject):
92 # Set ENV Variables/PATH
94 if ticket_id == None or ticket_id == "":
95 raise Exception("ERROR: ticket_id must be set to some integer value")
97 # This will raise an exception if it is not a valid id.
98 i_ticket_id = int(ticket_id)
100 cmd = "rt edit ticket/%s set subject='%s'" % (ticket_id, subject)
101 (f_in, f_out, f_err) = os.popen3(cmd)
103 l_values = value.split()
104 f_in.close() ; f_out.close() ; f_err.close()
105 if len(l_values) > 3 and "updated" in l_values[3]:
109 print "VALUE:", value
110 print "ERROR: RT failed to update subject for ticket %s" % ticket_id
115 def addCommentViaRT(ticket_id, comment):
116 # Set ENV Variables/PATH
117 _setupRTenvironment()
118 if ticket_id == None or ticket_id == "":
119 raise Exception("ERROR: ticket_id must be set to some integer value")
121 # This will raise an exception if it is not a valid id.
122 i_ticket_id = int(ticket_id)
124 cmd = "rt comment -m '%s' ticket/%s" % (comment, i_ticket_id)
125 (f_in, f_out, f_err) = os.popen3(cmd)
127 l_values = value.split()
128 f_in.close() ; f_out.close() ; f_err.close()
129 if len(l_values) > 1 and "recorded" in l_values[1]:
134 f_in.close() ; f_out.close() ; f_err.close()
135 print "ERROR: RT failed to add comment to id %s" % ticket_id
139 def closeTicketViaRT(ticket_id, comment):
140 # Set ENV Variables/PATH
141 _setupRTenvironment()
142 if ticket_id == None or ticket_id == "":
143 raise Exception("ERROR: ticket_id must be set to some integer value")
145 # This will raise an exception if it is not a valid id.
146 i_ticket_id = int(ticket_id)
148 # Append comment to RT ticket
149 addCommentViaRT(ticket_id, comment)
152 cmd = "rt edit ticket/%s set status=resolved" % i_ticket_id
153 (f_in, f_out, f_err) = os.popen3(cmd)
158 l_values = value.split()
159 if len(l_values) >= 4 and "updated" in l_values[3]:
163 print "VALUE: ", value
165 print "FAILED to resolve Ticket %s" % ticket_id
166 print "FAILED to resolve Ticket %s" % i_ticket_id
170 def emailViaRT(subject, text, to, ticket_id=None):
171 if ticket_id == None or ticket_id == "":
172 return emailViaRT_NoTicket(subject, text, to)
175 # Set ENV Variables/PATH
176 _setupRTenvironment()
178 if config.mail and not config.debug:
179 setSubjectViaRT(ticket_id, subject)
180 setAdminCCViaRT(ticket_id, to)
182 cmd = "rt correspond -m - %s" % ticket_id
183 (f_in, f_out, f_err) = os.popen3(cmd)
189 # TODO: rt doesn't write to stderr on error!!!
191 raise Exception, f_err.read()
194 f_out.close(); del f_out
195 f_err.close(); del f_err
201 def emailViaRT_NoTicket(subject, text, to):
202 """Use RT command line tools to send email.
203 return the generated RT ticket ID number.
207 if config.mail and config.debug:
210 # Set ENV Variables/PATH
211 _setupRTenvironment()
213 # NOTE: AdminCc: (in PLC's RT configuration) gets an email sent.
214 # This is not the case (surprisingly) for Cc:
215 input_text = "Subject: %s\n"
216 input_text += "Requestor: monitor@planet-lab.org\n"
217 input_text += "id: ticket/new\n"
218 input_text += "Queue: Monitor\n"
220 input_text += "AdminCc: %s\n" % recipient
221 input_text += "Text: %s"
223 # Add a space for each new line to get RT to accept the file.
224 spaced_text = reformat_for_rt(text)
226 if config.mail and not config.debug:
227 cmd = "rt create -i -t ticket"
228 (f_in, f_out, f_err) = os.popen3(cmd)
229 f_in.write(input_text % (subject, spaced_text))
234 # TODO: rt doesn't write to stderr on error!!!
236 raise Exception, f_err.read()
238 print "MAILER: ticket value == %s" % value.split()[2]
239 i_ticket = int(value.split()[2])
240 # clean up the child process.
241 f_in.close(); del f_in
242 f_out.close(); del f_out
243 f_err.close(); del f_err
245 elif config.mail and config.debug:
246 email(subject, spaced_text, to)
253 def email(subject, text, to):
254 """Create a mime-message that will render HTML in popular
255 MUAs, text in better ones"""
260 if (config.mail and config.debug) or (not config.mail and not config.debug and config.bcc):
263 out = cStringIO.StringIO() # output buffer for our message
264 txtin = cStringIO.StringIO(text)
266 writer = MimeWriter.MimeWriter(out)
268 # set up some basic headers... we put subject here
269 # because smtplib.sendmail expects it to be in the
272 writer.addheader("Subject", subject)
273 if to.__class__ == [].__class__ :
274 writer.addheader("To", to[0])
276 for dest in to[1:len(to)]:
279 writer.addheader("Cc", cc)
281 writer.addheader("To", to)
283 if config.bcc and not config.debug:
284 writer.addheader("Bcc", config.email)
286 writer.addheader("Reply-To", 'monitor@planet-lab.org')
288 writer.addheader("MIME-Version", "1.0")
290 # start the multipart section of the message
291 # multipart/alternative seems to work better
292 # on some MUAs than multipart/mixed
294 writer.startmultipartbody("alternative")
295 writer.flushheaders()
297 # the plain text section
299 subpart = writer.nextpart()
300 subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
301 pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
302 mimetools.encode(txtin, pout, 'quoted-printable')
305 # Now that we're done, close our writer and
306 # return the message body
314 # mail and debug, 'to' changed at the beginning'
315 # nomail, but report who I'd send to.
318 # This is normal operation
319 server = smtplib.SMTP(MTA)
320 server.sendmail(FROM, to, msg)
321 if config.bcc and not config.debug:
322 server.sendmail(FROM, config.email, msg)
324 except Exception, err:
325 print "Mailer error: %s" % err
326 elif not config.debug and not config.mail and config.bcc:
328 server = smtplib.SMTP(MTA)
329 server.sendmail(FROM, to, msg)
331 except Exception, err:
332 print "Mailer error: %s" % err
334 #print "Would mail %s" %to
335 logger.debug("Would send mail to %s" % to)
337 if __name__=="__main__":
341 #email("[spam] bcc test from golf.cs.princeton.edu",
342 # "It gets to both recipients",
343 # "soltesz@cs.utk.edu")
344 #emailViaRT("rt via golf",
345 # "It gets to both recipients",
346 # "soltesz@cs.utk.edu")
347 email("Re: [PL #21323] TEST 7",
348 mailtxt.newbootcd_one[1] % {'hostname_list':"hostname list..."},
349 ['monitor@planet-lab.org'])
350 #print "ticketid: %d" % id
351 #id = plc.siteId(["alice.cs.princeton.edu"])
354 #email('TEST', emailTxt.mailtxt.ssh % {'hostname': "ALICE.cs.princeton.edu"}, "tech-" + id + "@sites.planet-lab.org")
357 #email("TEST111", "I'd like to see if this works anywhere", ["soltesz@cs.princeton.edu", "soltesz@cs.utk.edu"])
358 #print "mailer does nothing in main()"