3 # Copyright (c) 2004 The Trustees of Princeton University (Trustees).
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
6 # Stephen Soltesz <soltesz@cs.princeton.edu>
8 # $Id: mailer.py,v 1.10 2007/08/08 13:28:06 soltesz Exp $
11 from monitor import config
17 logger = logging.getLogger("monitor")
22 def reformat_for_rt(text):
23 lines = text.split("\n")
26 spaced_text += " %s\n" %line
30 def _setupRTenvironment():
31 os.environ['PATH'] = config.RT_WEB_TOOLS_PATH + ":" + os.environ['PATH']
32 os.environ['RTSERVER'] = config.RT_WEB_SERVER
33 os.environ['RTUSER'] = config.RT_WEB_USER
34 os.environ['RTPASSWD'] = config.RT_WEB_PASSWORD
35 os.environ['RTDEBUG'] = config.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)
45 (f_in, f_out, f_err) = os.popen3(cmd)
47 l_values = value.split('\n')
48 return "".join(l_values).strip()
50 def getTicketStatus(ticket_id):
52 if ticket_id == None or ticket_id == "":
55 cmd = "rt show -t ticket -f id,subject,status,queue,created,told %s" % (ticket_id)
57 (f_in, f_out, f_err) = os.popen3(cmd)
59 l_values = value.split('\n')
62 if len(line) == 0: continue
63 vals = line.split(':')
65 r_values[key] = ":".join(vals[1:])
66 r_values[key] = r_values[key].strip()
68 #if 'Created' in r_values:
69 # r_values['Created'] = calendar.timegm(time.strptime(r_values['Created']))
71 r_values['Created'] = calendar.timegm(time.localtime())
73 #r_values['Told'] = calendar.timegm(time.strptime(r_values['Told']))
76 def setAdminCCViaRT(ticket_id, to):
77 # Set ENV Variables/PATH
79 if ticket_id == None or ticket_id == "":
80 raise Exception("ERROR: ticket_id must be set to some integer value")
82 # This will raise an exception if it is not a valid id.
83 i_ticket_id = int(ticket_id)
85 # create a comma-separated list
87 cmd = "rt edit ticket/%s set admincc='%s'" % (ticket_id, s_to)
89 (f_in, f_out, f_err) = os.popen3(cmd)
91 l_values = value.split()
92 f_in.close() ; f_out.close() ; f_err.close()
93 if len(l_values) > 3 and "updated" in l_values[3]:
98 print "ERROR: RT failed to update AdminCC for ticket %s" % ticket_id
102 def setSubjectViaRT(ticket_id, subject):
103 # Set ENV Variables/PATH
104 _setupRTenvironment()
105 if ticket_id == None or ticket_id == "":
106 raise Exception("ERROR: ticket_id must be set to some integer value")
108 # This will raise an exception if it is not a valid id.
109 i_ticket_id = int(ticket_id)
111 cmd = "rt edit ticket/%s set subject='%s'" % (ticket_id, subject)
113 (f_in, f_out, f_err) = os.popen3(cmd)
115 l_values = value.split()
116 f_in.close() ; f_out.close() ; f_err.close()
117 if len(l_values) > 3 and "updated" in l_values[3]:
121 print "VALUE:", value
122 print "ERROR: RT failed to update subject for ticket %s" % ticket_id
127 def addCommentViaRT(ticket_id, comment):
128 # Set ENV Variables/PATH
129 _setupRTenvironment()
130 if ticket_id == None or ticket_id == "":
131 raise Exception("ERROR: ticket_id must be set to some integer value")
133 # This will raise an exception if it is not a valid id.
134 i_ticket_id = int(ticket_id)
136 cmd = "rt comment -m '%s' ticket/%s" % (comment, i_ticket_id)
138 (f_in, f_out, f_err) = os.popen3(cmd)
140 l_values = value.split()
142 f_in.close() ; f_out.close() ; f_err.close()
143 if len(l_values) > 1 and "recorded" in l_values[1]:
148 f_in.close() ; f_out.close() ; f_err.close()
149 print "ERROR: RT failed to add comment to id %s" % ticket_id
150 print "ERROR: %s" % l_err
154 def closeTicketViaRT(ticket_id, comment):
155 # Set ENV Variables/PATH
156 _setupRTenvironment()
157 if ticket_id == None or ticket_id == "":
158 raise Exception("ERROR: ticket_id must be set to some integer value")
160 # This will raise an exception if it is not a valid id.
161 i_ticket_id = int(ticket_id)
163 # Append comment to RT ticket
164 addCommentViaRT(ticket_id, comment)
167 cmd = "rt edit ticket/%s set status=resolved" % i_ticket_id
169 (f_in, f_out, f_err) = os.popen3(cmd)
174 l_values = value.split()
175 if len(l_values) >= 4 and "updated" in l_values[3]:
179 print "VALUE: ", value
181 print "FAILED to resolve Ticket %s" % ticket_id
182 print "FAILED to resolve Ticket %s" % i_ticket_id
186 def emailViaRT(subject, text, to, ticket_id=None):
187 if ticket_id == None or ticket_id == "" or ticket_id == 0:
189 return emailViaRT_NoTicket(subject, text, to)
192 # Set ENV Variables/PATH
193 _setupRTenvironment()
195 if config.mail and not config.debug:
196 setSubjectViaRT(ticket_id, subject)
197 setAdminCCViaRT(ticket_id, to)
199 cmd = "rt correspond -m - %s" % ticket_id
201 (f_in, f_out, f_err) = os.popen3(cmd)
202 #f_in.write(input[:32000])
203 f_in.write(text[:32000])
208 # TODO: rt doesn't write to stderr on error!!!
210 raise Exception, f_err.read()
213 f_out.close(); del f_out
214 f_err.close(); del f_err
220 def emailViaRT_NoTicket(subject, text, to):
221 """Use RT command line tools to send email.
222 return the generated RT ticket ID number.
226 if config.mail and config.debug:
229 # Set ENV Variables/PATH
230 _setupRTenvironment()
232 # NOTE: AdminCc: (in PLC's RT configuration) gets an email sent.
233 # This is not the case (surprisingly) for Cc:
234 input_text = "Subject: %s\n"
235 input_text += "Requestor: %s\n"% FROM
236 input_text += "id: ticket/new\n"
237 input_text += "Queue: %s\n" % config.RT_QUEUE
239 input_text += "AdminCc: %s\n" % recipient
240 #input_text += "AdminCc: %s\n" % config.cc_email
241 input_text += "Text: %s"
243 # Add a space for each new line to get RT to accept the file.
244 spaced_text = reformat_for_rt(text)
246 if config.mail and not config.debug:
247 cmd = "rt create -i -t ticket"
249 (f_in, f_out, f_err) = os.popen3(cmd)
250 input = input_text % (subject, spaced_text)
251 print "length: %s" % len(input)
252 # NOTE: RT hangs with larger input, probably due to some internal
253 # buffering. So, chop off messages at 32000
254 #f_in.write(input[:32000])
255 f_in.write(input[:32000])
260 # TODO: rt doesn't write to stderr on error!!!
262 raise Exception, f_err.read()
264 print "MAILER: ticket value == %s" % value.split()[2]
265 i_ticket = int(value.split()[2])
266 # clean up the child process.
267 f_in.close(); del f_in
268 f_out.close(); del f_out
269 f_err.close(); del f_err
271 elif config.mail and config.debug:
272 email(subject, spaced_text, to)
279 def email(subject, text, to):
280 """Create a mime-message that will render HTML in popular
281 MUAs, text in better ones"""
286 if (config.mail and config.debug) or (not config.mail and not config.debug and config.bcc):
289 out = cStringIO.StringIO() # output buffer for our message
290 txtin = cStringIO.StringIO(text)
292 writer = MimeWriter.MimeWriter(out)
294 # set up some basic headers... we put subject here
295 # because smtplib.sendmail expects it to be in the
298 writer.addheader("Subject", subject)
299 if to.__class__ == [].__class__ :
300 writer.addheader("To", to[0])
302 for dest in to[1:len(to)]:
305 writer.addheader("Cc", cc)
307 writer.addheader("To", to)
309 if config.bcc and not config.debug:
310 writer.addheader("Bcc", config.email)
312 writer.addheader("Reply-To", FROM)
314 writer.addheader("MIME-Version", "1.0")
316 # start the multipart section of the message
317 # multipart/alternative seems to work better
318 # on some MUAs than multipart/mixed
320 writer.startmultipartbody("alternative")
321 writer.flushheaders()
323 # the plain text section
325 subpart = writer.nextpart()
326 subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
327 pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
328 mimetools.encode(txtin, pout, 'quoted-printable')
331 # Now that we're done, close our writer and
332 # return the message body
340 # mail and debug, 'to' changed at the beginning'
341 # nomail, but report who I'd send to.
343 for mta in [MTA, 'golf.cs.princeton.edu']:
345 # This is normal operation
346 server = smtplib.SMTP(mta)
347 server.sendmail(FROM, to, msg)
348 if config.bcc and not config.debug:
349 server.sendmail(FROM, config.email, msg)
351 except Exception, err:
352 print "Mailer error1: failed using MTA(%s) with: %s" % (mta, err)
354 elif not config.debug and not config.mail and config.bcc:
355 for mta in [MTA, 'golf.cs.princeton.edu']:
357 server = smtplib.SMTP(mta)
358 server.sendmail(FROM, to, msg)
360 except Exception, err:
361 print "Mailer error2: failed using MTA(%s) with: %s" % (mta, err)
363 logger.debug("Would send mail to %s" % to)
365 if __name__=="__main__":
369 emailViaRT("mail via RT", "Let's see if this succeeds...", [FROM])