Permalink
Browse files

Converted crashmailbatch and friends from camel case to pythonic style

  • Loading branch information...
Roger Hoover
Roger Hoover committed Jun 30, 2011
1 parent 7f90eeb commit df863a3d09594953d0e09ab9c7c0a9c56bd42acb
@@ -56,14 +56,14 @@
class CrashMailBatch(ProcessStateEmailMonitor):
- processStateEvents = ['PROCESS_STATE_EXITED']
+ process_state_events = ['PROCESS_STATE_EXITED']
def __init__(self, **kwargs):
kwargs['subject'] = kwargs.get('subject', 'Crash alert from supervisord')
ProcessStateEmailMonitor.__init__(self, **kwargs)
self.now = kwargs.get('now', None)
- def getProcessStateChangeMsg(self, headers, payload):
+ def get_process_state_change_msg(self, headers, payload):
pheaders, pdata = childutils.eventdata(payload+'\n')
if int(pheaders['expected']):
@@ -74,7 +74,7 @@ def getProcessStateChangeMsg(self, headers, payload):
return '%s -- %s' % (childutils.get_asctime(self.now), txt)
def main():
- crash = CrashMailBatch.createFromCmdLine()
+ crash = CrashMailBatch.create_from_cmd_line()
crash.run()
if __name__ == '__main__':
View
@@ -63,13 +63,13 @@
from superlance.process_state_email_monitor import ProcessStateEmailMonitor
class CrashSMS(ProcessStateEmailMonitor):
- processStateEvents = ['PROCESS_STATE_EXITED']
+ process_state_events = ['PROCESS_STATE_EXITED']
def __init__(self, **kwargs):
ProcessStateEmailMonitor.__init__(self, **kwargs)
self.now = kwargs.get('now', None)
- def getProcessStateChangeMsg(self, headers, payload):
+ def get_process_state_change_msg(self, headers, payload):
pheaders, pdata = childutils.eventdata(payload+'\n')
if int(pheaders['expected']):
@@ -80,7 +80,7 @@ def getProcessStateChangeMsg(self, headers, payload):
return '%s %s' % (txt, childutils.get_asctime(self.now))
def main():
- crash = CrashSMS.createFromCmdLine()
+ crash = CrashSMS.create_from_cmd_line()
crash.run()
if __name__ == '__main__':
@@ -53,22 +53,22 @@
class FatalMailBatch(ProcessStateEmailMonitor):
- processStateEvents = ['PROCESS_STATE_FATAL']
+ process_state_events = ['PROCESS_STATE_FATAL']
def __init__(self, **kwargs):
kwargs['subject'] = kwargs.get('subject', 'Fatal start alert from supervisord')
ProcessStateEmailMonitor.__init__(self, **kwargs)
self.now = kwargs.get('now', None)
- def getProcessStateChangeMsg(self, headers, payload):
+ def get_process_state_change_msg(self, headers, payload):
pheaders, pdata = childutils.eventdata(payload+'\n')
txt = 'Process %(groupname)s:%(processname)s failed to start too many \
times' % pheaders
return '%s -- %s' % (childutils.get_asctime(self.now), txt)
def main():
- fatal = FatalMailBatch.createFromCmdLine()
+ fatal = FatalMailBatch.create_from_cmd_line()
fatal.run()
if __name__ == '__main__':
@@ -29,29 +29,29 @@
class ProcessStateEmailMonitor(ProcessStateMonitor):
@classmethod
- def createFromCmdLine(cls):
+ def create_from_cmd_line(cls):
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-i", "--interval", dest="interval", type="float", default=1.0,
help="batch interval in minutes (defaults to 1 minute)")
- parser.add_option("-t", "--toEmail", dest="toEmail",
+ parser.add_option("-t", "--toEmail", dest="to_email",
help="destination email address")
- parser.add_option("-f", "--fromEmail", dest="fromEmail",
+ parser.add_option("-f", "--fromEmail", dest="from_email",
help="source email address")
parser.add_option("-s", "--subject", dest="subject",
help="email subject")
- parser.add_option("-H", "--smtpHost", dest="smtpHost", default="localhost",
+ parser.add_option("-H", "--smtpHost", dest="smtp_host", default="localhost",
help="SMTP server hostname or address")
parser.add_option("-e", "--tickEvent", dest="eventname", default="TICK_60",
help="TICK event name (defaults to TICK_60)")
(options, args) = parser.parse_args()
- if not options.toEmail:
+ if not options.to_email:
parser.print_help()
sys.exit(1)
- if not options.fromEmail:
+ if not options.from_email:
parser.print_help()
sys.exit(1)
@@ -64,49 +64,49 @@ def createFromCmdLine(cls):
def __init__(self, **kwargs):
ProcessStateMonitor.__init__(self, **kwargs)
- self.fromEmail = kwargs['fromEmail']
- self.toEmail = kwargs['toEmail']
+ self.from_email = kwargs['from_email']
+ self.to_email = kwargs['to_email']
self.subject = kwargs.get('subject')
- self.smtpHost = kwargs.get('smtpHost', 'localhost')
- self.digestLen = 76
+ self.smtp_host = kwargs.get('smtp_host', 'localhost')
+ self.digest_len = 76
- def sendBatchNotification(self):
- email = self.getBatchEmail()
+ def send_batch_notification(self):
+ email = self.get_batch_email()
if email:
- self.sendEmail(email)
- self.logEmail(email)
-
- def logEmail(self, email):
- email4Log = copy.copy(email)
- if len(email4Log['body']) > self.digestLen:
- email4Log['body'] = '%s...' % email4Log['body'][:self.digestLen]
- self.writeToStderr("Sending notification email:\nTo: %(to)s\n\
-From: %(from)s\nSubject: %(subject)s\nBody:\n%(body)s\n" % email4Log)
-
- def getBatchEmail(self):
- if len(self.batchMsgs):
+ self.send_email(email)
+ self.log_email(email)
+
+ def log_email(self, email):
+ email_for_log = copy.copy(email)
+ if len(email_for_log['body']) > self.digest_len:
+ email_for_log['body'] = '%s...' % email_for_log['body'][:self.digest_len]
+ self.write_stderr("Sending notification email:\nTo: %(to)s\n\
+From: %(from)s\nSubject: %(subject)s\nBody:\n%(body)s\n" % email_for_log)
+
+ def get_batch_email(self):
+ if len(self.batchmsgs):
return {
- 'to': self.toEmail,
- 'from': self.fromEmail,
+ 'to': self.to_email,
+ 'from': self.from_email,
'subject': self.subject,
- 'body': '\n'.join(self.getBatchMsgs()),
+ 'body': '\n'.join(self.get_batch_msgs()),
}
return None
- def sendEmail(self, email):
+ def send_email(self, email):
msg = MIMEText(email['body'])
if self.subject:
msg['Subject'] = email['subject']
msg['From'] = email['from']
msg['To'] = email['to']
try:
- self.sendSMTP(msg)
+ self.send_smtp(msg)
except Exception, e:
- self.writeToStderr("Error sending email: %s\n" % e)
+ self.write_stderr("Error sending email: %s\n" % e)
- def sendSMTP(self, mimeMsg):
- s = smtplib.SMTP(self.smtpHost)
+ def send_smtp(self, mimeMsg):
+ s = smtplib.SMTP(self.smtp_host)
try:
s.sendmail(mimeMsg['From'], [mimeMsg['To']], mimeMsg.as_string())
except:
@@ -24,7 +24,7 @@
class ProcessStateMonitor:
# In child class, define a list of events to monitor
- processStateEvents = []
+ process_state_events = []
def __init__(self, **kwargs):
self.interval = kwargs.get('interval', 1.0)
@@ -36,8 +36,8 @@ def __init__(self, **kwargs):
self.eventname = kwargs.get('eventname', 'TICK_60')
self.tickmins = self._get_tick_mins(self.eventname)
- self.batchMsgs = []
- self.batchMins = 0.0
+ self.batchmsgs = []
+ self.batchmins = 0.0
def _get_tick_mins(self, eventname):
return float(self._get_tick_secs(eventname))/60.0
@@ -53,49 +53,49 @@ def _validate_tick_name(self, eventname):
def run(self):
while 1:
hdrs, payload = childutils.listener.wait(self.stdin, self.stdout)
- self.handleEvent(hdrs, payload)
+ self.handle_event(hdrs, payload)
childutils.listener.ok(self.stdout)
- def handleEvent(self, headers, payload):
- if headers['eventname'] in self.processStateEvents:
- self.handleProcessStateChangeEvent(headers, payload)
+ def handle_event(self, headers, payload):
+ if headers['eventname'] in self.process_state_events:
+ self.handle_process_state_change_event(headers, payload)
elif headers['eventname'] == self.eventname:
- self.handleTickEvent(headers, payload)
+ self.handle_tick_event(headers, payload)
- def handleProcessStateChangeEvent(self, headers, payload):
- msg = self.getProcessStateChangeMsg(headers, payload)
+ def handle_process_state_change_event(self, headers, payload):
+ msg = self.get_process_state_change_msg(headers, payload)
if msg:
- self.writeToStderr('%s\n' % msg)
- self.batchMsgs.append(msg)
+ self.write_stderr('%s\n' % msg)
+ self.batchmsgs.append(msg)
"""
Override this method in child classes to customize messaging
"""
- def getProcessStateChangeMsg(self, headers, payload):
+ def get_process_state_change_msg(self, headers, payload):
return None
- def handleTickEvent(self, headers, payload):
- self.batchMins += self.tickmins
- if self.batchMins >= self.interval:
- self.sendBatchNotification()
- self.clearBatch()
+ def handle_tick_event(self, headers, payload):
+ self.batchmins += self.tickmins
+ if self.batchmins >= self.interval:
+ self.send_batch_notification()
+ self.clear_batch()
"""
Override this method in child classes to send notification
"""
- def sendBatchNotification(self):
+ def send_batch_notification(self):
pass
- def getBatchMinutes(self):
- return self.batchMins
+ def get_batch_minutes(self):
+ return self.batchmins
- def getBatchMsgs(self):
- return self.batchMsgs
+ def get_batch_msgs(self):
+ return self.batchmsgs
- def clearBatch(self):
- self.batchMins = 0.0;
- self.batchMsgs = [];
+ def clear_batch(self):
+ self.batchmins = 0.0;
+ self.batchmsgs = [];
- def writeToStderr(self, msg):
+ def write_stderr(self, msg):
self.stderr.write(msg)
self.stderr.flush()
@@ -3,28 +3,28 @@
from StringIO import StringIO
class CrashMailBatchTests(unittest.TestCase):
- fromEmail = 'testFrom@blah.com'
- toEmail = 'testTo@blah.com'
+ from_email = 'testFrom@blah.com'
+ to_email = 'testTo@blah.com'
subject = 'Test Alert'
- unexpectedErrorMsg = 'Process bar:foo (pid 58597) died unexpectedly'
+ unexpected_err_msg = 'Process bar:foo (pid 58597) died unexpectedly'
- def _getTargetClass(self):
+ def _get_target_class(self):
from superlance.crashmailbatch import CrashMailBatch
return CrashMailBatch
- def _makeOneMocked(self, **kwargs):
+ def _make_one_mocked(self, **kwargs):
kwargs['stdin'] = StringIO()
kwargs['stdout'] = StringIO()
kwargs['stderr'] = StringIO()
- kwargs['fromEmail'] = kwargs.get('fromEmail', self.fromEmail)
- kwargs['toEmail'] = kwargs.get('toEmail', self.toEmail)
+ kwargs['from_email'] = kwargs.get('from_email', self.from_email)
+ kwargs['to_email'] = kwargs.get('to_email', self.to_email)
kwargs['subject'] = kwargs.get('subject', self.subject)
- obj = self._getTargetClass()(**kwargs)
- obj.sendEmail = mock.Mock()
+ obj = self._get_target_class()(**kwargs)
+ obj.send_email = mock.Mock()
return obj
- def getProcessExitedEvent(self, pname, gname, expected):
+ def get_process_exited_event(self, pname, gname, expected):
headers = {
'ver': '3.0', 'poolserial': '7', 'len': '71',
'server': 'supervisor', 'eventname': 'PROCESS_STATE_EXITED',
@@ -34,32 +34,32 @@ def getProcessExitedEvent(self, pname, gname, expected):
pid:58597' % (pname, gname, expected)
return (headers, payload)
- def test_getProcessStateChangeMsg_expected(self):
- crash = self._makeOneMocked()
- hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 1)
- self.assertEquals(None, crash.getProcessStateChangeMsg(hdrs, payload))
+ def test_get_process_state_change_msg_expected(self):
+ crash = self._make_one_mocked()
+ hdrs, payload = self.get_process_exited_event('foo', 'bar', 1)
+ self.assertEquals(None, crash.get_process_state_change_msg(hdrs, payload))
- def test_getProcessStateChangeMsg_unexpected(self):
- crash = self._makeOneMocked()
- hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 0)
- msg = crash.getProcessStateChangeMsg(hdrs, payload)
- self.failUnless(self.unexpectedErrorMsg in msg)
+ def test_get_process_state_change_msg_unexpected(self):
+ crash = self._make_one_mocked()
+ hdrs, payload = self.get_process_exited_event('foo', 'bar', 0)
+ msg = crash.get_process_state_change_msg(hdrs, payload)
+ self.failUnless(self.unexpected_err_msg in msg)
- def test_handleEvent_exit_expected(self):
- crash = self._makeOneMocked()
- hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 1)
- crash.handleEvent(hdrs, payload)
- self.assertEquals([], crash.getBatchMsgs())
+ def test_handle_event_exit_expected(self):
+ crash = self._make_one_mocked()
+ hdrs, payload = self.get_process_exited_event('foo', 'bar', 1)
+ crash.handle_event(hdrs, payload)
+ self.assertEquals([], crash.get_batch_msgs())
self.assertEquals('', crash.stderr.getvalue())
- def test_handleEvent_exit_unexpected(self):
- crash = self._makeOneMocked()
- hdrs, payload = self.getProcessExitedEvent('foo', 'bar', 0)
- crash.handleEvent(hdrs, payload)
- msgs = crash.getBatchMsgs()
+ def test_handle_event_exit_unexpected(self):
+ crash = self._make_one_mocked()
+ hdrs, payload = self.get_process_exited_event('foo', 'bar', 0)
+ crash.handle_event(hdrs, payload)
+ msgs = crash.get_batch_msgs()
self.assertEquals(1, len(msgs))
- self.failUnless(self.unexpectedErrorMsg in msgs[0])
- self.failUnless(self.unexpectedErrorMsg in crash.stderr.getvalue())
+ self.failUnless(self.unexpected_err_msg in msgs[0])
+ self.failUnless(self.unexpected_err_msg in crash.stderr.getvalue())
if __name__ == '__main__':
unittest.main()
@@ -5,11 +5,11 @@
from crashmailbatch_test import CrashMailBatchTests
-class CrashSMSBatchTests(CrashMailBatchTests):
+class CrashSMSTests(CrashMailBatchTests):
subject = 'None'
- unexpectedErrorMsg = '[bar:foo](58597) exited unexpectedly'
+ unexpected_err_msg = '[bar:foo](58597) exited unexpectedly'
- def _getTargetClass(self):
+ def _get_target_class(self):
from superlance.crashsms import CrashSMS
return CrashSMS
Oops, something went wrong.

0 comments on commit df863a3

Please sign in to comment.