##// END OF EJS Templates
Now alarm is a process, add SchainWarning exception for handling non-stop exceptions
jespinoza -
r1129:986a05a7d203
parent child
Show More
@@ -13,6 +13,7 import smtplib
13 import ConfigParser
13 import ConfigParser
14 import StringIO
14 import StringIO
15 from threading import Thread
15 from threading import Thread
16 from multiprocessing import Process
16 from email.mime.text import MIMEText
17 from email.mime.text import MIMEText
17 from email.mime.application import MIMEApplication
18 from email.mime.application import MIMEApplication
18 from email.mime.multipart import MIMEMultipart
19 from email.mime.multipart import MIMEMultipart
@@ -34,7 +35,7 def get_path():
34 except:
35 except:
35 log.error('I am sorry, but something is wrong... __file__ not found')
36 log.error('I am sorry, but something is wrong... __file__ not found')
36
37
37 def alarm(modes=[1], **kwargs):
38 class Alarm(Process):
38 '''
39 '''
39 modes:
40 modes:
40 0 - All
41 0 - All
@@ -44,6 +45,12 def alarm(modes=[1], **kwargs):
44 4 - Send to alarm system TODO
45 4 - Send to alarm system TODO
45 '''
46 '''
46
47
48 def __init__(self, modes=[1], **kwargs):
49 Process.__init__(self)
50 self.modes = modes
51 self.kwargs = kwargs
52
53 @staticmethod
47 def play_sound():
54 def play_sound():
48 sound = os.path.join(get_path(), 'alarm1.oga')
55 sound = os.path.join(get_path(), 'alarm1.oga')
49 if os.path.exists(sound):
56 if os.path.exists(sound):
@@ -53,27 +60,32 def alarm(modes=[1], **kwargs):
53 else:
60 else:
54 log.warning('Unable to play alarm, sound file not found', 'ADMIN')
61 log.warning('Unable to play alarm, sound file not found', 'ADMIN')
55
62
63 @staticmethod
56 def send_email(**kwargs):
64 def send_email(**kwargs):
57 notifier = SchainNotify()
65 notifier = SchainNotify()
58 notifier.notify(**kwargs)
66 notifier.notify(**kwargs)
59
67
68 @staticmethod
60 def show_popup(message='Error'):
69 def show_popup(message='Error'):
61 popup(message)
70 popup(message)
62
71
72 @staticmethod
63 def send_alarm():
73 def send_alarm():
64 pass
74 pass
65
75
76 @staticmethod
66 def get_kwargs(kwargs, keys):
77 def get_kwargs(kwargs, keys):
67 ret = {}
78 ret = {}
68 for key in keys:
79 for key in keys:
69 ret[key] = kwargs[key]
80 ret[key] = kwargs[key]
70 return ret
81 return ret
71
82
83 def run(self):
72 tasks = {
84 tasks = {
73 1 : send_email,
85 1 : self.send_email,
74 2 : play_sound,
86 2 : self.play_sound,
75 3 : show_popup,
87 3 : self.show_popup,
76 4 : send_alarm,
88 4 : self.send_alarm,
77 }
89 }
78
90
79 tasks_args = {
91 tasks_args = {
@@ -82,16 +94,20 def alarm(modes=[1], **kwargs):
82 3: ['message'],
94 3: ['message'],
83 4: [],
95 4: [],
84 }
96 }
85
97 procs = []
86 for mode in modes:
98 for mode in self.modes:
87 if mode == 0:
99 if 0 in self.modes:
88 for x in tasks:
100 for x in tasks:
89 t = Thread(target=tasks[x], kwargs=get_kwargs(kwargs, tasks_args[x]))
101 t = Thread(target=tasks[x], kwargs=self.get_kwargs(self.kwargs, tasks_args[x]))
90 t.start()
102 t.start()
103 procs.append(t)
91 break
104 break
92 else:
105 else:
93 t = Thread(target=tasks[mode], kwargs=get_kwargs(kwargs, tasks_args[x]))
106 t = Thread(target=tasks[mode], kwargs=self.get_kwargs(self.kwargs, tasks_args[mode]))
94 t.start()
107 t.start()
108 procs.append(t)
109 for t in procs:
110 t.join()
95
111
96
112
97 class SchainConfigure():
113 class SchainConfigure():
@@ -262,6 +278,8 class SchainNotify:
262 if not self.__emailServer:
278 if not self.__emailServer:
263 return 0
279 return 0
264
280
281 log.success('Sending email to {}...'.format(email_to), 'System')
282
265 msg = MIMEMultipart()
283 msg = MIMEMultipart()
266 msg['Subject'] = subject
284 msg['Subject'] = subject
267 msg['From'] = "(Python SChain API): " + email_from
285 msg['From'] = "(Python SChain API): " + email_from
@@ -295,7 +313,7 class SchainNotify:
295 try:
313 try:
296 smtp = smtplib.SMTP(self.__emailServer)
314 smtp = smtplib.SMTP(self.__emailServer)
297 except:
315 except:
298 print "***** Could not connect to server %s *****" %self.__emailServer
316 log.error('Could not connect to server {}'.format(self.__emailServer), 'System')
299 return 0
317 return 0
300
318
301 # Start the server:
319 # Start the server:
@@ -307,12 +325,14 class SchainNotify:
307 try:
325 try:
308 smtp.sendmail(msg['From'], msg['To'], msg.as_string())
326 smtp.sendmail(msg['From'], msg['To'], msg.as_string())
309 except:
327 except:
310 print "***** Could not send the email to %s *****" %msg['To']
328 log.error('Could not send the email to {}'.format(msg['To']), 'System')
311 smtp.quit()
329 smtp.quit()
312 return 0
330 return 0
313
331
314 smtp.quit()
332 smtp.quit()
315
333
334 log.success('Email sent ', 'System')
335
316 return 1
336 return 1
317
337
318 def sendAlert(self, message, subject = "", subtitle="", filename=""):
338 def sendAlert(self, message, subject = "", subtitle="", filename=""):
@@ -343,8 +363,6 class SchainNotify:
343 if not sent:
363 if not sent:
344 return 0
364 return 0
345
365
346 print "***** Your system administrator has been notified *****"
347
348 return 1
366 return 1
349
367
350 def notify(self, email, message, subject = "", subtitle="", filename=""):
368 def notify(self, email, message, subject = "", subtitle="", filename=""):
@@ -362,16 +380,15 class SchainNotify:
362 if email is None:
380 if email is None:
363 email = self.__emailToAddress
381 email = self.__emailToAddress
364
382
365 log.success('Notifying to %s ...'.format(email), 'ADMIN')
383 self.sendEmail(
366
384 email_from=self.__emailFromAddress,
367 self.sendEmail(email_from=self.__emailFromAddress,
368 email_to=email,
385 email_to=email,
369 subject=subject,
386 subject=subject,
370 message=message,
387 message=message,
371 subtitle=subtitle,
388 subtitle=subtitle,
372 filename=filename)
389 filename=filename
390 )
373
391
374 log.success('Email sent', 'ADMIN')
375
392
376 class SchainError(Exception):
393 class SchainError(Exception):
377 """SchainError is an exception class that is thrown for all known errors using Schain Py lib.
394 """SchainError is an exception class that is thrown for all known errors using Schain Py lib.
@@ -468,6 +485,10 class SchainError(Exception):
468
485
469 return excStr
486 return excStr
470
487
488 class SchainWarning(Exception):
489 pass
490
491
471 if __name__ == '__main__':
492 if __name__ == '__main__':
472
493
473 test = SchainNotify()
494 test = SchainNotify()
@@ -15,7 +15,7 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
15 from xml.dom import minidom
15 from xml.dom import minidom
16
16
17 import schainpy
17 import schainpy
18 import schainpy.admin
18 from schainpy.admin import Alarm, SchainWarning
19 from schainpy.model import *
19 from schainpy.model import *
20 from schainpy.utils import log
20 from schainpy.utils import log
21
21
@@ -1180,10 +1180,13 class Project(Process):
1180
1180
1181 self.__connect(puObjIN, thisPUObj)
1181 self.__connect(puObjIN, thisPUObj)
1182
1182
1183 def __handleError(self, procUnitConfObj):
1183 def __handleError(self, procUnitConfObj, modes=None):
1184
1184
1185 import socket
1185 import socket
1186
1186
1187 if modes is None:
1188 modes = self.alarm
1189
1187 err = traceback.format_exception(sys.exc_info()[0],
1190 err = traceback.format_exception(sys.exc_info()[0],
1188 sys.exc_info()[1],
1191 sys.exc_info()[1],
1189 sys.exc_info()[2])
1192 sys.exc_info()[2])
@@ -1215,8 +1218,8 class Project(Process):
1215 subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime
1218 subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime
1216 subtitle += '[End time = %s]\n' % readUnitConfObj.endTime
1219 subtitle += '[End time = %s]\n' % readUnitConfObj.endTime
1217
1220
1218 schainpy.admin.alarm(
1221 a = Alarm(
1219 modes=self.alarm,
1222 modes=modes,
1220 email=self.email,
1223 email=self.email,
1221 message=message,
1224 message=message,
1222 subject=subject,
1225 subject=subject,
@@ -1224,6 +1227,8 class Project(Process):
1224 filename=self.filename
1227 filename=self.filename
1225 )
1228 )
1226
1229
1230 a.start()
1231
1227 def isPaused(self):
1232 def isPaused(self):
1228 return 0
1233 return 0
1229
1234
@@ -1292,7 +1297,8 class Project(Process):
1292 try:
1297 try:
1293 sts = procUnitConfObj.run()
1298 sts = procUnitConfObj.run()
1294 is_ok = is_ok or sts
1299 is_ok = is_ok or sts
1295 j
1300 except SchainWarning:
1301 self.__handleError(procUnitConfObj, modes=[2, 3])
1296 except KeyboardInterrupt:
1302 except KeyboardInterrupt:
1297 is_ok = False
1303 is_ok = False
1298 break
1304 break
@@ -37,13 +37,12 def figpause(interval):
37 return
37 return
38
38
39 def popup(message):
39 def popup(message):
40 fig = plt.figure(figsize=(12, 9), facecolor='r')
40 fig = plt.figure(figsize=(12, 8), facecolor='r')
41 fig.text(0.5, 0.5, message, ha='center', va='center', size='20', weight='heavy', color='w')
41 fig.text(0.5, 0.5, message, ha='center', va='center', size='20', weight='heavy', color='w')
42 fig.show()
42 fig.show()
43 figpause(1000)
43 figpause(1000)
44
44
45
45
46
47 class PlotData(Operation, Process):
46 class PlotData(Operation, Process):
48 '''
47 '''
49 Base class for Schain plotting operations
48 Base class for Schain plotting operations
General Comments 0
You need to be logged in to leave comments. Login now