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 %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 r_values['Created'] = calendar.timegm(time.strptime(r_values['Created']))
71 def setAdminCCViaRT(ticket_id, to):
72 # Set ENV Variables/PATH
74 if ticket_id == None or ticket_id == "":
75 raise Exception("ERROR: ticket_id must be set to some integer value")
77 # This will raise an exception if it is not a valid id.
78 i_ticket_id = int(ticket_id)
80 # create a comma-separated list
82 cmd = "rt edit ticket/%s set admincc='%s'" % (ticket_id, s_to)
84 (f_in, f_out, f_err) = os.popen3(cmd)
86 l_values = value.split()
87 f_in.close() ; f_out.close() ; f_err.close()
88 if len(l_values) > 3 and "updated" in l_values[3]:
93 print "ERROR: RT failed to update AdminCC for ticket %s" % ticket_id
97 def setSubjectViaRT(ticket_id, subject):
98 # Set ENV Variables/PATH
100 if ticket_id == None or ticket_id == "":
101 raise Exception("ERROR: ticket_id must be set to some integer value")
103 # This will raise an exception if it is not a valid id.
104 i_ticket_id = int(ticket_id)
106 cmd = "rt edit ticket/%s set subject='%s'" % (ticket_id, subject)
108 (f_in, f_out, f_err) = os.popen3(cmd)
110 l_values = value.split()
111 f_in.close() ; f_out.close() ; f_err.close()
112 if len(l_values) > 3 and "updated" in l_values[3]:
116 print "VALUE:", value
117 print "ERROR: RT failed to update subject for ticket %s" % ticket_id
122 def addCommentViaRT(ticket_id, comment):
123 # Set ENV Variables/PATH
124 _setupRTenvironment()
125 if ticket_id == None or ticket_id == "":
126 raise Exception("ERROR: ticket_id must be set to some integer value")
128 # This will raise an exception if it is not a valid id.
129 i_ticket_id = int(ticket_id)
131 cmd = "rt comment -m '%s' ticket/%s" % (comment, i_ticket_id)
133 (f_in, f_out, f_err) = os.popen3(cmd)
135 l_values = value.split()
137 f_in.close() ; f_out.close() ; f_err.close()
138 if len(l_values) > 1 and "recorded" in l_values[1]:
143 f_in.close() ; f_out.close() ; f_err.close()
144 print "ERROR: RT failed to add comment to id %s" % ticket_id
145 print "ERROR: %s" % l_err
149 def closeTicketViaRT(ticket_id, comment):
150 # Set ENV Variables/PATH
151 _setupRTenvironment()
152 if ticket_id == None or ticket_id == "":
153 raise Exception("ERROR: ticket_id must be set to some integer value")
155 # This will raise an exception if it is not a valid id.
156 i_ticket_id = int(ticket_id)
158 # Append comment to RT ticket
159 addCommentViaRT(ticket_id, comment)
162 cmd = "rt edit ticket/%s set status=resolved" % i_ticket_id
164 (f_in, f_out, f_err) = os.popen3(cmd)
169 l_values = value.split()
170 if len(l_values) >= 4 and "updated" in l_values[3]:
174 print "VALUE: ", value
176 print "FAILED to resolve Ticket %s" % ticket_id
177 print "FAILED to resolve Ticket %s" % i_ticket_id
181 def emailViaRT(subject, text, to, ticket_id=None):
182 if ticket_id == None or ticket_id == "" or ticket_id == 0:
184 return emailViaRT_NoTicket(subject, text, to)
187 # Set ENV Variables/PATH
188 _setupRTenvironment()
190 if config.mail and not config.debug:
191 setSubjectViaRT(ticket_id, subject)
192 setAdminCCViaRT(ticket_id, to)
194 cmd = "rt correspond -m - %s" % ticket_id
196 (f_in, f_out, f_err) = os.popen3(cmd)
197 #f_in.write(input[:32000])
198 f_in.write(text[:32000])
203 # TODO: rt doesn't write to stderr on error!!!
205 raise Exception, f_err.read()
208 f_out.close(); del f_out
209 f_err.close(); del f_err
215 def emailViaRT_NoTicket(subject, text, to):
216 """Use RT command line tools to send email.
217 return the generated RT ticket ID number.
221 if config.mail and config.debug:
224 # Set ENV Variables/PATH
225 _setupRTenvironment()
227 # NOTE: AdminCc: (in PLC's RT configuration) gets an email sent.
228 # This is not the case (surprisingly) for Cc:
229 input_text = "Subject: %s\n"
230 input_text += "Requestor: %s\n"% FROM
231 input_text += "id: ticket/new\n"
232 input_text += "Queue: %s\n" % config.RT_QUEUE
234 input_text += "AdminCc: %s\n" % recipient
235 #input_text += "AdminCc: %s\n" % config.cc_email
236 input_text += "Text: %s"
238 # Add a space for each new line to get RT to accept the file.
239 spaced_text = reformat_for_rt(text)
241 if config.mail and not config.debug:
242 cmd = "rt create -i -t ticket"
244 (f_in, f_out, f_err) = os.popen3(cmd)
245 input = input_text % (subject, spaced_text)
246 print "length: %s" % len(input)
247 # NOTE: RT hangs with larger input, probably due to some internal
248 # buffering. So, chop off messages at 32000
249 #f_in.write(input[:32000])
250 f_in.write(input[:32000])
255 # TODO: rt doesn't write to stderr on error!!!
257 raise Exception, f_err.read()
259 print "MAILER: ticket value == %s" % value.split()[2]
260 i_ticket = int(value.split()[2])
261 # clean up the child process.
262 f_in.close(); del f_in
263 f_out.close(); del f_out
264 f_err.close(); del f_err
266 elif config.mail and config.debug:
267 email(subject, spaced_text, to)
274 def email(subject, text, to):
275 """Create a mime-message that will render HTML in popular
276 MUAs, text in better ones"""
281 if (config.mail and config.debug) or (not config.mail and not config.debug and config.bcc):
284 out = cStringIO.StringIO() # output buffer for our message
285 txtin = cStringIO.StringIO(text)
287 writer = MimeWriter.MimeWriter(out)
289 # set up some basic headers... we put subject here
290 # because smtplib.sendmail expects it to be in the
293 writer.addheader("Subject", subject)
294 if to.__class__ == [].__class__ :
295 writer.addheader("To", to[0])
297 for dest in to[1:len(to)]:
300 writer.addheader("Cc", cc)
302 writer.addheader("To", to)
304 if config.bcc and not config.debug:
305 writer.addheader("Bcc", config.email)
307 writer.addheader("Reply-To", FROM)
309 writer.addheader("MIME-Version", "1.0")
311 # start the multipart section of the message
312 # multipart/alternative seems to work better
313 # on some MUAs than multipart/mixed
315 writer.startmultipartbody("alternative")
316 writer.flushheaders()
318 # the plain text section
320 subpart = writer.nextpart()
321 subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
322 pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
323 mimetools.encode(txtin, pout, 'quoted-printable')
326 # Now that we're done, close our writer and
327 # return the message body
335 # mail and debug, 'to' changed at the beginning'
336 # nomail, but report who I'd send to.
338 for mta in [MTA, 'golf.cs.princeton.edu']:
340 # This is normal operation
345 server = smtplib.SMTP(mta)
346 #server = smtplib.SMTP('golf.cs.princeton.edu')
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 #print "Would mail %s" %to
364 logger.debug("Would send mail to %s" % to)
366 if __name__=="__main__":
370 #email("[spam] bcc test from golf.cs.princeton.edu",
371 # "It gets to both recipients",
372 # "soltesz@cs.utk.edu")
373 emailViaRT("mail via RT", "Let's see if this succeeds...", [FROM])
374 #email("Re: [PL #21323] TEST 7",
375 # mailtxt.newbootcd_one[1] % {'hostname_list':"hostname list..."},