ns-3 simulator synchronizing start
[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         ns3_wrapper.logger.debug("SHUTDOWN")
48         
49         return "BYEBYE"
50     
51     if msg_type == NS3WrapperMessage.STOP:
52         time = kwargs.get("time")
53
54         ns3_wrapper.logger.debug("STOP time=%s" % str(time))
55
56         ns3_wrapper.stop(time=time)
57         return "STOPPED"
58
59     if msg_type == NS3WrapperMessage.START:
60         ns3_wrapper.logger.debug("START") 
61
62         ns3_wrapper.start()
63         return "STARTED"
64
65     if msg_type == NS3WrapperMessage.CREATE:
66         clazzname = args.pop(0)
67         
68         result = ns3_wrapper.create(clazzname, *args)
69
70         ns3_wrapper.logger.debug("%s CREATE %s %s" % (str(result), clazzname, 
71             str(args)))
72         
73         return result
74
75     if msg_type == NS3WrapperMessage.FACTORY:
76         type_name = args.pop(0)
77
78         result = ns3_wrapper.factory(type_name, **kwargs)
79         
80         ns3_wrapper.logger.debug("%s FACTORY %s %s" % (str(result), type_name, 
81             str(kwargs)))
82         
83         return result
84
85     if msg_type == NS3WrapperMessage.INVOKE:
86         uuid = args.pop(0)
87         operation = args.pop(0)
88    
89         result = ns3_wrapper.invoke(uuid, operation, *args, **kwargs)
90
91         ns3_wrapper.logger.debug("%s INVOKE %s %s %s %s " % (str(result), uuid, 
92             operation, str(args), str(kwargs)))
93
94         return result
95
96     if msg_type == NS3WrapperMessage.GET:
97         uuid = args.pop(0)
98         name = args.pop(0)
99
100         result = ns3_wrapper.get(uuid, name)
101         
102         ns3_wrapper.logger.debug("%s GET %s %s" % (str(result), uuid, name))
103
104         return result
105
106     if msg_type == NS3WrapperMessage.SET:
107         uuid = args.pop(0)
108         name = args.pop(0)
109         value = args.pop(0)
110
111         result = ns3_wrapper.set(uuid, name, value)
112
113         ns3_wrapper.logger.debug("%s SET %s %s %s" % (str(result), uuid, name, 
114             str(value)))
115
116         return result
117  
118     if msg_type == NS3WrapperMessage.FLUSH:
119         # Forces flushing output and error streams.
120         # NS-3 output will stay unflushed until the program exits or 
121         # explicit invocation flush is done
122         sys.stdout.flush()
123         sys.stderr.flush()
124
125         ns3_wrapper.logger.debug("FLUSHED") 
126         
127         return "FLUSHED"
128
129 def create_socket(socket_name):
130     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
131     sock.bind(socket_name)
132     return sock
133
134 def recv_msg(conn):
135     msg = []
136     chunk = ''
137
138     while '\n' not in chunk:
139         try:
140             chunk = conn.recv(1024)
141         except (OSError, socket.error), e:
142             if e[0] != errno.EINTR:
143                 raise
144             # Ignore eintr errors
145             continue
146
147         if chunk:
148             msg.append(chunk)
149         else:
150             # empty chunk = EOF
151             break
152  
153     msg = ''.join(msg).strip()
154
155     # The message is formatted as follows:
156     #   MESSAGE_TYPE|args|kwargs
157     #
158     #   where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
159
160     def decode(item):
161         item = base64.b64decode(item).rstrip()
162         return cPickle.loads(item)
163
164     decoded = map(decode, msg.split("|"))
165
166     # decoded message
167     dmsg_type = decoded.pop(0)
168     dargs = list(decoded.pop(0)) # transforming touple into list
169     dkwargs = decoded.pop(0)
170
171     return (dmsg_type, dargs, dkwargs)
172
173 def send_reply(conn, reply):
174     encoded = base64.b64encode(cPickle.dumps(reply))
175     conn.send("%s\n" % encoded)
176
177 def get_options():
178     usage = ("usage: %prog -S <socket-name> -L <NS_LOG> -v ")
179     
180     parser = OptionParser(usage = usage)
181
182     parser.add_option("-S", "--socket-name", dest="socket_name",
183         help = "Name for the unix socket used to interact with this process", 
184         default = "tap.sock", type="str")
185
186     parser.add_option("-L", "--ns-log", dest="ns_log",
187         help = "NS_LOG environmental variable to be set", 
188         default = "", type="str")
189
190     parser.add_option("-v", "--verbose",
191         help="Print debug output",
192         action="store_true", 
193         dest="verbose", default=False)
194
195     (options, args) = parser.parse_args()
196     
197     return (options.socket_name, options.verbose, options.ns_log)
198
199 def run_server(socket_name, level = logging.INFO, ns_log = None):
200
201     # Sets NS_LOG environmental variable for NS debugging
202     if ns_log:
203         os.environ["NS_LOG"] = ns_log
204
205     ###### ns-3 wrapper instantiation
206
207     ns3_wrapper = NS3Wrapper(loglevel=level)
208     
209     ns3_wrapper.logger.info("STARTING...")
210
211     # create unix socket to receive instructions
212     sock = create_socket(socket_name)
213     sock.listen(0)
214
215     # wait for messages to arrive and process them
216     stop = False
217
218     while not stop:
219         conn, addr = sock.accept()
220         conn.settimeout(5)
221
222         try:
223             (msg_type, args, kwargs) = recv_msg(conn)
224         except socket.timeout, e:
225             # Ingore time-out
226             continue
227
228         if not msg_type:
229             # Ignore - connection lost
230             break
231
232         if msg_type == NS3WrapperMessage.SHUTDOWN:
233            stop = True
234   
235         try:
236             reply = handle_message(ns3_wrapper, msg_type, args, kwargs)  
237         except:
238             import traceback
239             err = traceback.format_exc()
240             ns3_wrapper.logger.error(err) 
241             raise
242
243         try:
244             send_reply(conn, reply)
245         except socket.error:
246             break
247         
248     ns3_wrapper.logger.info("EXITING...")
249
250 if __name__ == '__main__':
251             
252     (socket_name, verbose, ns_log) = get_options()
253
254     ## configure logging
255     FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
256     level = logging.DEBUG if verbose else logging.INFO
257
258     logging.basicConfig(format = FORMAT, level = level)
259
260     ## Run the server
261     run_server(socket_name, level, ns_log)
262