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()
49 if msg_type == NS3WrapperMessage.STOP:
50 time = kwargs.get("time")
52 ns3_wrapper.stop(time=time)
56 if msg_type == NS3WrapperMessage.START:
61 if msg_type == NS3WrapperMessage.CREATE:
62 clazzname = args.pop(0)
64 return ns3_wrapper.create(clazzname, *args)
66 if msg_type == NS3WrapperMessage.FACTORY:
67 type_name = args.pop(0)
69 return ns3_wrapper.factory(type_name, **kwargs)
71 if msg_type == NS3WrapperMessage.INVOKE:
73 operation = args.pop(0)
75 return ns3_wrapper.invoke(uuid, operation, *args, **kwargs)
77 if msg_type == NS3WrapperMessage.GET:
81 return ns3_wrapper.get(uuid, name)
83 if msg_type == NS3WrapperMessage.SET:
88 return ns3_wrapper.set(uuid, name, value)
90 if msg_type == NS3WrapperMessage.FLUSH:
91 # Forces flushing output and error streams.
92 # NS-3 output will stay unflushed until the program exits or
93 # explicit invocation flush is done
97 ns3_wrapper.logger.debug("FLUSHED")
101 def open_socket(socket_name):
102 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
103 sock.bind(socket_name)
106 def close_socket(sock):
112 def recv_msg(conn, ns3_wrapper):
116 while '\n' not in chunk:
118 chunk = conn.recv(1024)
119 except (OSError, socket.error), e:
121 err = traceback.format_exc()
122 ns3_wrapper.logger.error(err)
124 if e[0] != errno.EINTR:
126 # Ignore eintr errors
135 msg = ''.join(msg).strip()
137 # The message is formatted as follows:
138 # MESSAGE_TYPE|args|kwargs
140 # where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
143 item = base64.b64decode(item).rstrip()
144 return cPickle.loads(item)
146 decoded = map(decode, msg.split("|"))
149 dmsg_type = decoded.pop(0)
150 dargs = list(decoded.pop(0)) # transforming touple into list
151 dkwargs = decoded.pop(0)
153 return (dmsg_type, dargs, dkwargs)
155 def send_reply(conn, reply):
156 encoded = base64.b64encode(cPickle.dumps(reply))
157 conn.send("%s\n" % encoded)
160 usage = ("usage: %prog -S <socket-name> -L <ns-log> -D <enable-dump> -v ")
162 parser = OptionParser(usage = usage)
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")
168 parser.add_option("-L", "--ns-log", dest="ns_log",
169 help = "NS_LOG environmental variable to be set",
170 default = "", type="str")
172 parser.add_option("-D", "--enable-dump", dest="enable_dump",
173 help = "Enable dumping the remote executed ns-3 commands to a script "
174 "in order to later reproduce and debug the experiment",
175 action = "store_true",
178 parser.add_option("-v", "--verbose",
179 help="Print debug output",
181 dest="verbose", default=False)
183 (options, args) = parser.parse_args()
185 return (options.socket_name, options.verbose, options.ns_log,
188 def run_server(socket_name, level = logging.INFO, ns_log = None,
189 enable_dump = False):
191 # Sets NS_LOG environmental variable for NS debugging
193 os.environ["NS_LOG"] = ns_log
195 ###### ns-3 wrapper instantiation
197 ns3_wrapper = NS3Wrapper(loglevel=level, enable_dump = enable_dump)
199 ns3_wrapper.logger.info("STARTING...")
201 # create unix socket to receive instructions
202 sock = open_socket(socket_name)
205 # wait for messages to arrive and process them
209 conn, addr = sock.accept()
213 (msg_type, args, kwargs) = recv_msg(conn, ns3_wrapper)
214 except socket.timeout, e:
220 # Ignore - connection lost
224 if msg_type == NS3WrapperMessage.SHUTDOWN:
228 reply = handle_message(ns3_wrapper, msg_type, args, kwargs)
231 err = traceback.format_exc()
232 ns3_wrapper.logger.error(err)
237 send_reply(conn, reply)
240 err = traceback.format_exc()
241 ns3_wrapper.logger.error(err)
249 ns3_wrapper.logger.info("EXITING...")
251 if __name__ == '__main__':
253 (socket_name, verbose, ns_log, enable_dump) = get_options()
256 FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
257 level = logging.DEBUG if verbose else logging.INFO
259 logging.basicConfig(format = FORMAT, level = level)
262 run_server(socket_name, level, ns_log, enable_dump)