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