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