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