source: trunk/Monitoring/Watch/watch @ 865

Last change on this file since 865 was 865, checked in by jripsl, 11 years ago
  • repository I/O impl.
  • Property svn:executable set to *
File size: 4.4 KB
Line 
1#!/usr/bin/env python
2# -*- coding: ISO-8859-1 -*-
3
4##################################
5#  @program        smon
6#  @description    simulation monitor
7#  @copyright      Copyright “(c)2009 Centre National de la Recherche Scientifique CNRS.
8#                             All Rights Reserved”
9#  @svn_file       $Id: watcher 2545 2013-02-01 09:58:10Z jripsl $
10#  @version        $Rev: 2545 $
11#  @lastrevision   $Date: 2013-02-01 10:58:10 +0100 (Fri, 01 Feb 2013) $
12#  @license        CeCILL (http://dods.ipsl.jussieu.fr/jripsl/smon/LICENSE)
13##################################
14
15import pika
16import base64
17import json
18import sys
19import signal
20import traceback
21import smtplib
22from email.mime.text import MIMEText
23from datetime import datetime
24
25# line below is to include "smon" package in the search path
26sys.path.append("/home/jripsl/snapshot/Monitoring")
27
28import smon.repo_io
29
30
31"""
32Code list reminder
33
340000 (la simulation démarre)
351000 (le job d'une simulation démarre)
362000 (PushStack)
373000 (PopStack OK)
389000 (PopStack NOK)
399999 (FATAL)
40"""
41
42class Mail():
43
44        @classmethod
45        def mail_example(cls):
46                me="jripsl@ipsl.jussieu.fr"
47                you="jripsl@ipsl.jussieu.fr"
48                body="Alarm"
49                object="Supervisor"
50
51                cls.mail(me,you,object,body)
52
53        @classmethod
54        def send_mail(cls,me,you,object,body):
55                msg = MIMEText(body)
56                msg['Subject'] = object
57                msg['From'] = me
58                msg['To'] = you
59
60                # Send the message via our own SMTP server, but don't include the # envelope header.
61                s = smtplib.SMTP('localhost')
62                s.sendmail(me,[you], msg.as_string())
63                s.quit()
64
65class Actions():
66
67        @classmethod
68        def store_msg(cls):
69                repo_io.store_messages(name)
70
71        @classmethod
72        def set_sim_status_to_error(cls):
73                repo_io.update_simulation_status()
74
75        @classmethod
76        def crea_sim(cls):
77                #repo_io.retrieve_simulation(name)
78                #repo_io.delete_simulation(name)
79                repo_io.create_simulation()
80
81        @classmethod
82        def mail(cls):
83                cls.mail_example()
84
85        @classmethod
86        def print_stdout(cls,message):
87                # used for debug
88
89                if "file" in message:
90                        print "%s %s %s\n"%(message["code"],message["jobid"],message["file"])
91                else:
92                        print "%s %s\n"%(message["code"],message["jobid"])
93
94        @classmethod
95        def log(cls,message):
96                with open("/home/jripsl/supervisor/log/supervisor.log", "a") as log_file:
97                        log_file.write("%s %s %s\n"%(datetime.now().strftime('%Y%m%d_%H%M%S'), message["code"],message["jobid"]))
98
99        @classmethod
100        def execActions(cls,message):
101
102                message_code=message["code"]
103
104                for action in MessageActionsMapping.mapping[message_code]:
105                        proc_name=action
106
107                        try:
108                                getattr(Actions, proc_name)(message)
109                        except Exception,e:
110                                traceback.print_exc()
111
112                                raise Exception("WATCH-ERR002","procedure error (%s,%s)"%(proc_name,str(e)))
113
114class MessageActionsMapping():
115
116        mapping = { "0000":["log", "store_msg", "crea_sim"],
117                                "1000":["log", "store_msg"],
118                                "2000":["log", "store_msg"],
119                                "3000":["log", "store_msg"],
120                                "9000":["log", "store_msg", "mail"],
121                                "9999":["log", "store_msg", "set_sim_status_to_error", "mail"] }
122
123class Watcher():
124
125        @classmethod
126        def start(cls):
127                pass
128
129        @classmethod
130        def stop(cls):
131                pass
132
133        @classmethod
134        def main(self):
135
136                """
137                # parse args
138                parser = argparse.ArgumentParser(prog='watcher')
139                parser.add_argument('-v', dest='verbose',required=False,action='store_true')
140                args = parser.parse_args()
141
142                # check
143                if not os.path.exists(SMON.smon_home):
144                        sys.exit(1)
145
146                SMON.init_singleton()
147                """
148
149                connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost'))
150                self.channel = connection.channel()
151
152                #self.channel.queue_declare(queue='myqueue')
153
154                print ' [*] Waiting for messages. To exit press CTRL+C'
155
156                def callback(ch, method, properties, raw_msg):
157                        #
158                        #return
159
160                        base64_decoded_msg=base64.b64decode(raw_msg)
161
162                        # debug
163                        #print " [x] Received %s" % raw_msg
164                        #print " [x] Received %s (uudecoded)" % base64_decoded_msg
165
166                        message=None
167                        try:
168                                message=json.loads(base64_decoded_msg)
169
170                                # message code based action
171                                Watcher.execActions(message)
172                        except Exception,e:
173                                print "Exception occurs (exception=%s,msg=%s)"%(str(e),base64_decoded_msg)
174
175                self.channel.basic_consume(callback, queue='myqueue', no_ack=True)
176
177                self.channel.start_consuming()
178
179
180                """
181                SMON.free_singleton()
182                """
183
184def signal_handler(signal, frame):
185                print 'You pressed Ctrl+C!'
186                Watcher.channel.stop_consuming()
187                sys.exit(0)
188
189if __name__ == '__main__':
190
191        signal.signal(signal.SIGINT, signal_handler)
192
193        try:
194                Watcher.main()
195
196                sys.exit(0)
197
198        except Exception, e:
199
200                traceback.print_exc()
201
202                sys.exit(1)
Note: See TracBrowser for help on using the repository browser.