##// END OF EJS Templates
Merge branch 'schain_alarm' of http://jro-dev.igp.gob.pe/rhodecode/schain into v2.3
jespinoza -
r1131:e8ab492363ef merge
parent child
Show More
1 NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
@@ -5,19 +5,114 notification class and a standard error handing class.
5 5
6 6 $Id: admin.py 3966 2015-12-01 14:32:29Z miguel.urco $
7 7 """
8 import os, sys
8 import os
9 import sys
10 import time
9 11 import traceback
10 12 import smtplib
11 13 import ConfigParser
12 14 import StringIO
13
15 from threading import Thread
16 from multiprocessing import Process
14 17 from email.mime.text import MIMEText
15 18 from email.mime.application import MIMEApplication
16 19 from email.mime.multipart import MIMEMultipart
17 20
18 class SchainConfigure():
21 from schainpy.utils import log
22 from schainpy.model.graphics.jroplot_data import popup
23
24 def get_path():
25 '''
26 Return schainpy path
27 '''
28
29 try:
30 root = __file__
31 if os.path.islink(root):
32 root = os.path.realpath(root)
33
34 return os.path.dirname(os.path.abspath(root))
35 except:
36 log.error('I am sorry, but something is wrong... __file__ not found')
37
38 class Alarm(Process):
39 '''
40 modes:
41 0 - All
42 1 - Sound alarm
43 2 - Send email
44 3 - Popup message
45 4 - Send to alarm system TODO
46 '''
47
48 def __init__(self, modes=[1], **kwargs):
49 Process.__init__(self)
50 self.modes = modes
51 self.kwargs = kwargs
52
53 @staticmethod
54 def play_sound():
55 sound = os.path.join(get_path(), 'alarm1.oga')
56 if os.path.exists(sound):
57 for __ in range(2):
58 os.system('paplay {}'.format(sound))
59 time.sleep(0.5)
60 else:
61 log.warning('Unable to play alarm, sound file not found', 'ADMIN')
62
63 @staticmethod
64 def send_email(**kwargs):
65 notifier = SchainNotify()
66 notifier.notify(**kwargs)
67
68 @staticmethod
69 def show_popup(message='Error'):
70 popup(message)
71
72 @staticmethod
73 def send_alarm():
74 pass
75
76 @staticmethod
77 def get_kwargs(kwargs, keys):
78 ret = {}
79 for key in keys:
80 ret[key] = kwargs[key]
81 return ret
82
83 def run(self):
84 tasks = {
85 1 : self.send_email,
86 2 : self.play_sound,
87 3 : self.show_popup,
88 4 : self.send_alarm,
89 }
90
91 tasks_args = {
92 1: ['email', 'message', 'subject', 'subtitle', 'filename'],
93 2: [],
94 3: ['message'],
95 4: [],
96 }
97 procs = []
98 for mode in self.modes:
99 if 0 in self.modes:
100 for x in tasks:
101 t = Thread(target=tasks[x], kwargs=self.get_kwargs(self.kwargs, tasks_args[x]))
102 t.start()
103 procs.append(t)
104 break
105 else:
106 t = Thread(target=tasks[mode], kwargs=self.get_kwargs(self.kwargs, tasks_args[mode]))
107 t.start()
108 procs.append(t)
109 for t in procs:
110 t.join()
111
112
113 class SchainConfigure():
19 114
20 __DEFAULT_ADMINISTRATOR_EMAIL = ""
115 __DEFAULT_ADMINISTRATOR_EMAIL = "juan.espinoza@jro.igp.gob.pe"
21 116 __DEFAULT_EMAIL_SERVER = "jro-zimbra.igp.gob.pe"
22 117 __DEFAULT_SENDER_EMAIL = "notifier-schain@jro.igp.gob.pe"
23 118 __DEFAULT_SENDER_PASS = ""
@@ -176,13 +271,15 class SchainNotify:
176 271 self.__emailServer = confObj.getEmailServer()
177 272
178 273 def sendEmail(self, email_from, email_to, subject='Error running ...', message="", subtitle="", filename="", html_format=True):
179
274
180 275 if not email_to:
181 276 return 0
182 277
183 278 if not self.__emailServer:
184 279 return 0
185 280
281 log.success('Sending email to {}...'.format(email_to), 'System')
282
186 283 msg = MIMEMultipart()
187 284 msg['Subject'] = subject
188 285 msg['From'] = "(Python SChain API): " + email_from
@@ -204,7 +301,7 class SchainNotify:
204 301
205 302 msg.attach(part)
206 303
207 if os.path.isfile(filename):
304 if filename and os.path.isfile(filename):
208 305 # This is the binary part(The Attachment):
209 306 part = MIMEApplication(open(filename,"rb").read())
210 307 part.add_header('Content-Disposition',
@@ -216,11 +313,11 class SchainNotify:
216 313 try:
217 314 smtp = smtplib.SMTP(self.__emailServer)
218 315 except:
219 print "***** Could not connect to server %s *****" %self.__emailServer
316 log.error('Could not connect to server {}'.format(self.__emailServer), 'System')
220 317 return 0
221 318
222 319 # Start the server:
223 # smtp.ehlo()
320 # smtp.ehlo()
224 321 if self.__emailPass:
225 322 smtp.login(self.__emailFromAddress, self.__emailPass)
226 323
@@ -228,11 +325,13 class SchainNotify:
228 325 try:
229 326 smtp.sendmail(msg['From'], msg['To'], msg.as_string())
230 327 except:
231 print "***** Could not send the email to %s *****" %msg['To']
328 log.error('Could not send the email to {}'.format(msg['To']), 'System')
232 329 smtp.quit()
233 330 return 0
234 331
235 332 smtp.quit()
333
334 log.success('Email sent ', 'System')
236 335
237 336 return 1
238 337
@@ -264,8 +363,6 class SchainNotify:
264 363 if not sent:
265 364 return 0
266 365
267 print "***** Your system administrator has been notified *****"
268
269 366 return 1
270 367
271 368 def notify(self, email, message, subject = "", subtitle="", filename=""):
@@ -280,16 +377,18 class SchainNotify:
280 377 Exceptions: None.
281 378 """
282 379
283 print "Notifying to %s ..." %email
284
285 self.sendEmail(email_from=self.__emailFromAddress,
286 email_to=email,
287 subject=subject,
288 message=message,
289 subtitle=subtitle,
290 filename=filename)
380 if email is None:
381 email = self.__emailToAddress
291 382
292 print "***** Your system administrator has been notified *****"
383 self.sendEmail(
384 email_from=self.__emailFromAddress,
385 email_to=email,
386 subject=subject,
387 message=message,
388 subtitle=subtitle,
389 filename=filename
390 )
391
293 392
294 393 class SchainError(Exception):
295 394 """SchainError is an exception class that is thrown for all known errors using Schain Py lib.
@@ -386,6 +485,10 class SchainError(Exception):
386 485
387 486 return excStr
388 487
488 class SchainWarning(Exception):
489 pass
490
491
389 492 if __name__ == '__main__':
390 493
391 494 test = SchainNotify()
@@ -15,7 +15,7 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
15 15 from xml.dom import minidom
16 16
17 17 import schainpy
18 import schainpy.admin
18 from schainpy.admin import Alarm, SchainWarning
19 19 from schainpy.model import *
20 20 from schainpy.utils import log
21 21
@@ -905,12 +905,11 class Project(Process):
905 905 def __init__(self, plotter_queue=None):
906 906
907 907 Process.__init__(self)
908 self.id = None
909 # self.name = None
908 self.id = None
910 909 self.description = None
911
910 self.email = None
911 self.alarm = [0]
912 912 self.plotterQueue = plotter_queue
913
914 913 self.procUnitConfObjDict = {}
915 914
916 915 def __getNewId(self):
@@ -952,13 +951,12 class Project(Process):
952 951 procUnitConfObj = self.procUnitConfObjDict[procKey]
953 952 idProcUnit = str(int(self.id) * 10 + n)
954 953 procUnitConfObj.updateId(idProcUnit, parentId=self.id)
955
956 954 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
957 955 n += 1
958 956
959 957 self.procUnitConfObjDict = newProcUnitConfObjDict
960 958
961 def setup(self, id, name='', description=''):
959 def setup(self, id, name='', description='', email=None, alarm=[0]):
962 960
963 961 print
964 962 print '*' * 60
@@ -966,11 +964,14 class Project(Process):
966 964 print '*' * 60
967 965 print
968 966 self.id = str(id)
969 self.description = description
967 self.description = description
968 self.email = email
969 self.alarm = alarm
970 970
971 def update(self, name, description):
971 def update(self, **kwargs):
972 972
973 self.description = description
973 for key, value in kwargs:
974 setattr(self, key, value)
974 975
975 976 def clone(self):
976 977
@@ -1179,24 +1180,23 class Project(Process):
1179 1180
1180 1181 self.__connect(puObjIN, thisPUObj)
1181 1182
1182 def __handleError(self, procUnitConfObj, send_email=False):
1183 def __handleError(self, procUnitConfObj, modes=None):
1183 1184
1184 1185 import socket
1185 1186
1187 if modes is None:
1188 modes = self.alarm
1189
1186 1190 err = traceback.format_exception(sys.exc_info()[0],
1187 1191 sys.exc_info()[1],
1188 1192 sys.exc_info()[2])
1189
1190 print '***** Error occurred in %s *****' % (procUnitConfObj.name)
1191 print '***** %s' % err[-1]
1193
1194 log.error('{}'.format(err[-1]), procUnitConfObj.name)
1192 1195
1193 1196 message = ''.join(err)
1194 1197
1195 1198 sys.stderr.write(message)
1196 1199
1197 if not send_email:
1198 return
1199
1200 1200 subject = 'SChain v%s: Error running %s\n' % (
1201 1201 schainpy.__version__, procUnitConfObj.name)
1202 1202
@@ -1218,11 +1218,16 class Project(Process):
1218 1218 subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime
1219 1219 subtitle += '[End time = %s]\n' % readUnitConfObj.endTime
1220 1220
1221 adminObj = schainpy.admin.SchainNotify()
1222 adminObj.sendAlert(message=message,
1223 subject=subject,
1224 subtitle=subtitle,
1225 filename=self.filename)
1221 a = Alarm(
1222 modes=modes,
1223 email=self.email,
1224 message=message,
1225 subject=subject,
1226 subtitle=subtitle,
1227 filename=self.filename
1228 )
1229
1230 a.start()
1226 1231
1227 1232 def isPaused(self):
1228 1233 return 0
@@ -1292,12 +1297,14 class Project(Process):
1292 1297 try:
1293 1298 sts = procUnitConfObj.run()
1294 1299 is_ok = is_ok or sts
1300 except SchainWarning:
1301 self.__handleError(procUnitConfObj, modes=[2, 3])
1295 1302 except KeyboardInterrupt:
1296 1303 is_ok = False
1297 1304 break
1298 1305 except ValueError, e:
1299 1306 time.sleep(0.5)
1300 self.__handleError(procUnitConfObj, send_email=True)
1307 self.__handleError(procUnitConfObj)
1301 1308 is_ok = False
1302 1309 break
1303 1310 except:
@@ -36,6 +36,12 def figpause(interval):
36 36 canvas.start_event_loop(interval)
37 37 return
38 38
39 def popup(message):
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')
42 fig.show()
43 figpause(1000)
44
39 45
40 46 class PlotData(Operation, Process):
41 47 '''
@@ -41,6 +41,7 setup(name = "schainpy",
41 41 ext_package = 'schainpy',
42 42 package_data = {'': ['schain.conf.template'],
43 43 'schainpy.gui.figures': ['*.png', '*.jpg'],
44 'schainpy.files': ['*.oga']
44 45 },
45 46 include_package_data = False,
46 47 scripts = ['schainpy/gui/schainGUI'],
General Comments 0
You need to be logged in to leave comments. Login now