2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2014 INRIA
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.
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.
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/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
28 from optparse import OptionParser, SUPPRESS_HELP
30 from ns3wrapper import NS3Wrapper
32 class NS3WrapperMessage:
43 def handle_message(ns3_wrapper, msg_type, args, kwargs):
44 if msg_type == NS3WrapperMessage.SHUTDOWN:
45 ns3_wrapper.shutdown()
47 ns3_wrapper.logger.debug("SHUTDOWN")
51 if msg_type == NS3WrapperMessage.STOP:
52 time = kwargs.get("time")
54 ns3_wrapper.logger.debug("STOP time=%s" % str(time))
56 ns3_wrapper.stop(time=time)
59 if msg_type == NS3WrapperMessage.START:
60 ns3_wrapper.logger.debug("START")
65 if msg_type == NS3WrapperMessage.CREATE:
66 clazzname = args.pop(0)
68 ns3_wrapper.logger.debug("CREATE %s %s" % (clazzname, str(args)))
70 uuid = ns3_wrapper.create(clazzname, *args)
72 #ns3_wrapper.logger.debug("%s = CREATE " % str(uuid))
75 if msg_type == NS3WrapperMessage.FACTORY:
76 type_name = args.pop(0)
78 ns3_wrapper.logger.debug("FACTORY %s %s" % (type_name, str(kwargs)))
80 uuid = ns3_wrapper.factory(type_name, **kwargs)
82 #ns3_wrapper.logger.debug("%s = FACTORY " % str(uuid))
85 if msg_type == NS3WrapperMessage.INVOKE:
87 operation = args.pop(0)
89 ns3_wrapper.logger.debug("INVOKE %s %s %s %s " % (uuid, operation,
90 str(args), str(kwargs)))
92 uuid = ns3_wrapper.invoke(uuid, operation, *args, **kwargs)
95 if msg_type == NS3WrapperMessage.GET:
99 ns3_wrapper.logger.debug("GET %s %s" % (uuid, name))
101 value = ns3_wrapper.get(uuid, name)
104 if msg_type == NS3WrapperMessage.SET:
109 ns3_wrapper.logger.debug("SET %s %s %s" % (uuid, name, str(value)))
111 value = ns3_wrapper.set(uuid, name, value)
114 if msg_type == NS3WrapperMessage.FLUSH:
115 # Forces flushing output and error streams.
116 # NS-3 output will stay unflushed until the program exits or
117 # explicit invocation flush is done
121 ns3_wrapper.logger.debug("FLUSHED")
125 def create_socket(socket_name):
126 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
127 sock.bind(socket_name)
134 while '\n' not in chunk:
136 chunk = conn.recv(1024)
137 except (OSError, socket.error), e:
138 if e[0] != errno.EINTR:
140 # Ignore eintr errors
149 msg = ''.join(msg).strip()
151 # The message is formatted as follows:
152 # MESSAGE_TYPE|args|kwargs
154 # where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
157 item = base64.b64decode(item).rstrip()
158 return cPickle.loads(item)
160 decoded = map(decode, msg.split("|"))
163 dmsg_type = decoded.pop(0)
164 dargs = list(decoded.pop(0)) # transforming touple into list
165 dkwargs = decoded.pop(0)
167 return (dmsg_type, dargs, dkwargs)
169 def send_reply(conn, reply):
170 encoded = base64.b64encode(cPickle.dumps(reply))
171 conn.send("%s\n" % encoded)
174 usage = ("usage: %prog -S <socket-name> -L <NS_LOG> -v ")
176 parser = OptionParser(usage = usage)
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")
182 parser.add_option("-L", "--ns-log", dest="ns_log",
183 help = "NS_LOG environmental variable to be set",
184 default = "", type="str")
186 parser.add_option("-v", "--verbose",
187 help="Print debug output",
189 dest="verbose", default=False)
191 (options, args) = parser.parse_args()
193 return (options.socket_name, options.verbose, options.ns_log)
195 def run_server(socket_name, level = logging.INFO, ns_log = None):
197 # Sets NS_LOG environmental variable for NS debugging
199 os.environ["NS_LOG"] = ns_log
201 ###### ns-3 wrapper instantiation
203 ns3_wrapper = NS3Wrapper(loglevel=level)
205 ns3_wrapper.logger.info("STARTING...")
207 # create unix socket to receive instructions
208 sock = create_socket(socket_name)
211 # wait for messages to arrive and process them
215 conn, addr = sock.accept()
219 (msg_type, args, kwargs) = recv_msg(conn)
220 except socket.timeout, e:
225 # Ignore - connection lost
228 if msg_type == NS3WrapperMessage.SHUTDOWN:
232 reply = handle_message(ns3_wrapper, msg_type, args, kwargs)
235 err = traceback.format_exc()
236 ns3_wrapper.logger.error(err)
240 send_reply(conn, reply)
244 ns3_wrapper.logger.info("EXITING...")
246 if __name__ == '__main__':
248 (socket_name, verbose, ns_log) = get_options()
251 FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
252 level = logging.DEBUG if verbose else logging.INFO
254 logging.basicConfig(format = FORMAT, level = level)
257 run_server(socket_name, level, ns_log)