From 986a05a7d203018a2030b1256d659cbaa859c7c1 2017-12-14 06:31:52 From: jespinoza Date: 2017-12-14 06:31:52 Subject: [PATCH] Now alarm is a process, add SchainWarning exception for handling non-stop exceptions --- diff --git a/schainpy/admin.py b/schainpy/admin.py index 68c99bb..98617ca 100644 --- a/schainpy/admin.py +++ b/schainpy/admin.py @@ -13,6 +13,7 @@ import smtplib import ConfigParser import StringIO from threading import Thread +from multiprocessing import Process from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart @@ -34,7 +35,7 @@ def get_path(): except: log.error('I am sorry, but something is wrong... __file__ not found') -def alarm(modes=[1], **kwargs): +class Alarm(Process): ''' modes: 0 - All @@ -44,6 +45,12 @@ def alarm(modes=[1], **kwargs): 4 - Send to alarm system TODO ''' + def __init__(self, modes=[1], **kwargs): + Process.__init__(self) + self.modes = modes + self.kwargs = kwargs + + @staticmethod def play_sound(): sound = os.path.join(get_path(), 'alarm1.oga') if os.path.exists(sound): @@ -53,45 +60,54 @@ def alarm(modes=[1], **kwargs): else: log.warning('Unable to play alarm, sound file not found', 'ADMIN') + @staticmethod def send_email(**kwargs): notifier = SchainNotify() notifier.notify(**kwargs) + @staticmethod def show_popup(message='Error'): popup(message) + @staticmethod def send_alarm(): pass + @staticmethod def get_kwargs(kwargs, keys): ret = {} for key in keys: ret[key] = kwargs[key] return ret - tasks = { - 1 : send_email, - 2 : play_sound, - 3 : show_popup, - 4 : send_alarm, - } - - tasks_args = { - 1: ['email', 'message', 'subject', 'subtitle', 'filename'], - 2: [], - 3: ['message'], - 4: [], - } - - for mode in modes: - if mode == 0: - for x in tasks: - t = Thread(target=tasks[x], kwargs=get_kwargs(kwargs, tasks_args[x])) + def run(self): + tasks = { + 1 : self.send_email, + 2 : self.play_sound, + 3 : self.show_popup, + 4 : self.send_alarm, + } + + tasks_args = { + 1: ['email', 'message', 'subject', 'subtitle', 'filename'], + 2: [], + 3: ['message'], + 4: [], + } + procs = [] + for mode in self.modes: + if 0 in self.modes: + for x in tasks: + t = Thread(target=tasks[x], kwargs=self.get_kwargs(self.kwargs, tasks_args[x])) + t.start() + procs.append(t) + break + else: + t = Thread(target=tasks[mode], kwargs=self.get_kwargs(self.kwargs, tasks_args[mode])) t.start() - break - else: - t = Thread(target=tasks[mode], kwargs=get_kwargs(kwargs, tasks_args[x])) - t.start() + procs.append(t) + for t in procs: + t.join() class SchainConfigure(): @@ -255,13 +271,15 @@ class SchainNotify: self.__emailServer = confObj.getEmailServer() def sendEmail(self, email_from, email_to, subject='Error running ...', message="", subtitle="", filename="", html_format=True): - + if not email_to: return 0 if not self.__emailServer: return 0 + log.success('Sending email to {}...'.format(email_to), 'System') + msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = "(Python SChain API): " + email_from @@ -295,7 +313,7 @@ class SchainNotify: try: smtp = smtplib.SMTP(self.__emailServer) except: - print "***** Could not connect to server %s *****" %self.__emailServer + log.error('Could not connect to server {}'.format(self.__emailServer), 'System') return 0 # Start the server: @@ -307,11 +325,13 @@ class SchainNotify: try: smtp.sendmail(msg['From'], msg['To'], msg.as_string()) except: - print "***** Could not send the email to %s *****" %msg['To'] + log.error('Could not send the email to {}'.format(msg['To']), 'System') smtp.quit() return 0 smtp.quit() + + log.success('Email sent ', 'System') return 1 @@ -343,8 +363,6 @@ class SchainNotify: if not sent: return 0 - print "***** Your system administrator has been notified *****" - return 1 def notify(self, email, message, subject = "", subtitle="", filename=""): @@ -361,17 +379,16 @@ class SchainNotify: if email is None: email = self.__emailToAddress - - log.success('Notifying to %s ...'.format(email), 'ADMIN') - - self.sendEmail(email_from=self.__emailFromAddress, - email_to=email, - subject=subject, - message=message, - subtitle=subtitle, - filename=filename) - log.success('Email sent', 'ADMIN') + self.sendEmail( + email_from=self.__emailFromAddress, + email_to=email, + subject=subject, + message=message, + subtitle=subtitle, + filename=filename + ) + class SchainError(Exception): """SchainError is an exception class that is thrown for all known errors using Schain Py lib. @@ -468,6 +485,10 @@ class SchainError(Exception): return excStr +class SchainWarning(Exception): + pass + + if __name__ == '__main__': test = SchainNotify() diff --git a/schainpy/controller.py b/schainpy/controller.py index e78f8e0..2542e85 100644 --- a/schainpy/controller.py +++ b/schainpy/controller.py @@ -15,7 +15,7 @@ from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring from xml.dom import minidom import schainpy -import schainpy.admin +from schainpy.admin import Alarm, SchainWarning from schainpy.model import * from schainpy.utils import log @@ -1180,10 +1180,13 @@ class Project(Process): self.__connect(puObjIN, thisPUObj) - def __handleError(self, procUnitConfObj): + def __handleError(self, procUnitConfObj, modes=None): import socket + if modes is None: + modes = self.alarm + err = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) @@ -1215,8 +1218,8 @@ class Project(Process): subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime subtitle += '[End time = %s]\n' % readUnitConfObj.endTime - schainpy.admin.alarm( - modes=self.alarm, + a = Alarm( + modes=modes, email=self.email, message=message, subject=subject, @@ -1224,6 +1227,8 @@ class Project(Process): filename=self.filename ) + a.start() + def isPaused(self): return 0 @@ -1292,7 +1297,8 @@ class Project(Process): try: sts = procUnitConfObj.run() is_ok = is_ok or sts - j + except SchainWarning: + self.__handleError(procUnitConfObj, modes=[2, 3]) except KeyboardInterrupt: is_ok = False break diff --git a/schainpy/model/graphics/jroplot_data.py b/schainpy/model/graphics/jroplot_data.py index 0fded4d..cb401c4 100644 --- a/schainpy/model/graphics/jroplot_data.py +++ b/schainpy/model/graphics/jroplot_data.py @@ -37,13 +37,12 @@ def figpause(interval): return def popup(message): - fig = plt.figure(figsize=(12, 9), facecolor='r') + fig = plt.figure(figsize=(12, 8), facecolor='r') fig.text(0.5, 0.5, message, ha='center', va='center', size='20', weight='heavy', color='w') fig.show() figpause(1000) - class PlotData(Operation, Process): ''' Base class for Schain plotting operations