5f756ae66f6ee40daa2f286ee2d045572014a4bb
[nepi.git] / src / nepi / resources / ns3 / ns3server.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2014 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published by
7 #    the Free Software Foundation, either version 3 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 import base64
21 import cPickle
22 import errno
23 import logging
24 import os
25 import socket
26 import sys
27
28 from optparse import OptionParser, SUPPRESS_HELP
29
30 from ns3wrapper import NS3Wrapper
31
32 class NS3WrapperMessage:
33     CREATE = "CREATE"
34     FACTORY = "FACTORY"
35     INVOKE = "INVOKE"
36     SET = "SET"
37     GET = "GET"
38     FLUSH = "FLUSH"
39     START = "START"
40     STOP = "STOP"
41     SHUTDOWN = "SHUTDOWN"
42
43 def handle_message(ns3_wrapper, msg_type, args, kwargs):
44     if msg_type == NS3WrapperMessage.SHUTDOWN:
45         ns3_wrapper.shutdown()
46
47         return "BYEBYE"
48     
49     if msg_type == NS3WrapperMessage.STOP:
50         time = kwargs.get("time")
51
52         ns3_wrapper.stop(time=time)
53
54         return "STOPPED"
55
56     if msg_type == NS3WrapperMessage.START:
57         ns3_wrapper.start()
58
59         return "STARTED"
60
61     if msg_type == NS3WrapperMessage.CREATE:
62         clazzname = args.pop(0)
63         
64         return ns3_wrapper.create(clazzname, *args)
65         
66     if msg_type == NS3WrapperMessage.FACTORY:
67         type_name = args.pop(0)
68
69         return ns3_wrapper.factory(type_name, **kwargs)
70        
71     if msg_type == NS3WrapperMessage.INVOKE:
72         uuid = args.pop(0)
73         operation = args.pop(0)
74    
75         return ns3_wrapper.invoke(uuid, operation, *args, **kwargs)
76
77     if msg_type == NS3WrapperMessage.GET:
78         uuid = args.pop(0)
79         name = args.pop(0)
80
81         return ns3_wrapper.get(uuid, name)
82         
83     if msg_type == NS3WrapperMessage.SET:
84         uuid = args.pop(0)
85         name = args.pop(0)
86         value = args.pop(0)
87
88         return ns3_wrapper.set(uuid, name, value)
89
90     if msg_type == NS3WrapperMessage.FLUSH:
91         # Forces flushing output and error streams.
92         # NS-3 output will stay unflushed until the program exits or 
93         # explicit invocation flush is done
94         sys.stdout.flush()
95         sys.stderr.flush()
96
97         ns3_wrapper.logger.debug("FLUSHED") 
98         
99         return "FLUSHED"
100
101 def open_socket(socket_name):
102     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
103     sock.bind(socket_name)
104     return sock
105
106 def close_socket(sock):
107     try:
108         sock.close()
109     except:
110         pass
111
112 def recv_msg(conn):
113     msg = []
114     chunk = ''
115
116     while '\n' not in chunk:
117         try:
118             chunk = conn.recv(1024)
119         except (OSError, socket.error), e:
120             if e[0] != errno.EINTR:
121                 raise
122             # Ignore eintr errors
123             continue
124
125         if chunk:
126             msg.append(chunk)
127         else:
128             # empty chunk = EOF
129             break
130  
131     msg = ''.join(msg).strip()
132
133     # The message is formatted as follows:
134     #   MESSAGE_TYPE|args|kwargs
135     #
136     #   where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
137
138     def decode(item):
139         item = base64.b64decode(item).rstrip()
140         return cPickle.loads(item)
141
142     decoded = map(decode, msg.split("|"))
143
144     # decoded message
145     dmsg_type = decoded.pop(0)
146     dargs = list(decoded.pop(0)) # transforming touple into list
147     dkwargs = decoded.pop(0)
148
149     return (dmsg_type, dargs, dkwargs)
150
151 def send_reply(conn, reply):
152     encoded = base64.b64encode(cPickle.dumps(reply))
153     conn.send("%s\n" % encoded)
154
155 def get_options():
156     usage = ("usage: %prog -S <socket-name> -L <ns-log>  -D <enable-dump> -v ")
157     
158     parser = OptionParser(usage = usage)
159
160     parser.add_option("-S", "--socket-name", dest="socket_name",
161         help = "Name for the unix socket used to interact with this process", 
162         default = "tap.sock", type="str")
163
164     parser.add_option("-L", "--ns-log", dest="ns_log",
165         help = "NS_LOG environmental variable to be set", 
166         default = "", type="str")
167
168     parser.add_option("-D", "--enable-dump", dest="enable_dump",
169         help = "Enable dumping the remote executed ns-3 commands to a script "
170             "in order to later reproduce and debug the experiment",
171         action = "store_true",
172         default = False)
173
174     parser.add_option("-v", "--verbose",
175         help="Print debug output",
176         action="store_true", 
177         dest="verbose", default=False)
178
179     (options, args) = parser.parse_args()
180     
181     return (options.socket_name, options.verbose, options.ns_log,
182             options.enable_dump)
183
184 def run_server(socket_name, level = logging.INFO, ns_log = None, 
185         enable_dump = False):
186
187     # Sets NS_LOG environmental variable for NS debugging
188     if ns_log:
189         os.environ["NS_LOG"] = ns_log
190
191     ###### ns-3 wrapper instantiation
192
193     ns3_wrapper = NS3Wrapper(loglevel=level, enable_dump = enable_dump)
194     
195     ns3_wrapper.logger.info("STARTING...")
196
197     # create unix socket to receive instructions
198     sock = open_socket(socket_name)
199     sock.listen(0)
200
201     # wait for messages to arrive and process them
202     stop = False
203
204     while not stop:
205         conn, addr = sock.accept()
206         conn.settimeout(5)
207
208         try:
209             (msg_type, args, kwargs) = recv_msg(conn)
210         except socket.timeout, e:
211             # Ingore time-out
212             close_socket(conn)
213             continue
214
215         if not msg_type:
216             # Ignore - connection lost
217             close_socket(conn)
218             continue
219
220         if msg_type == NS3WrapperMessage.SHUTDOWN:
221            stop = True
222   
223         try:
224             reply = handle_message(ns3_wrapper, msg_type, args, kwargs)  
225         except:
226             import traceback
227             err = traceback.format_exc()
228             ns3_wrapper.logger.error(err) 
229             close_socket(conn)
230             raise
231
232         try:
233             send_reply(conn, reply)
234         except socket.error:
235             import traceback
236             err = traceback.format_exc()
237             ns3_wrapper.logger.error(err) 
238             close_socket(conn)
239             raise
240         
241         close_socket(conn)
242
243     close_socket(sock)
244
245     ns3_wrapper.logger.info("EXITING...")
246
247 if __name__ == '__main__':
248             
249     (socket_name, verbose, ns_log, enable_dump) = get_options()
250
251     ## configure logging
252     FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
253     level = logging.DEBUG if verbose else logging.INFO
254
255     logging.basicConfig(format = FORMAT, level = level)
256
257     ## Run the server
258     run_server(socket_name, level, ns_log, enable_dump)
259