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, args):
44 if msg == NS3WrapperMessage.SHUTDOWN:
45 ns3_wrapper.shutdown()
47 ns3_wrapper.logger.debug("SHUTDOWN")
51 if msg == NS3WrapperMessage.STOP:
56 ns3_wrapper.logger.debug("STOP time=%s" % str(time))
58 ns3_wrapper.stop(time=time)
61 if msg == NS3WrapperMessage.START:
62 ns3_wrapper.logger.debug("START")
67 if msg == NS3WrapperMessage.CREATE:
68 clazzname = args.pop(0)
70 ns3_wrapper.logger.debug("CREATE %s %s" % (clazzname, str(args)))
72 uuid = ns3_wrapper.create(clazzname, *args)
75 if msg == NS3WrapperMessage.FACTORY:
76 type_name = args.pop(0)
79 ns3_wrapper.logger.debug("FACTORY %s %s" % (type_name, str(kwargs)))
81 uuid = ns3_wrapper.factory(type_name, **kwargs)
84 if msg == NS3WrapperMessage.INVOKE:
86 operation = args.pop(0)
88 ns3_wrapper.logger.debug("INVOKE %s %s %s" % (uuid, operation, str(args)))
90 uuid = ns3_wrapper.invoke(uuid, operation, *args)
93 if msg == NS3WrapperMessage.GET:
97 ns3_wrapper.logger.debug("GET %s %s" % (uuid, name))
99 value = ns3_wrapper.get(uuid, name)
102 if msg == NS3WrapperMessage.SET:
107 ns3_wrapper.logger.debug("SET %s %s" % (uuid, name, str(value)))
109 value = ns3_wrapper.set(uuid, name, value)
112 if msg == NS3WrapperMessage.TRACE:
113 ns3_wrapper.logger.debug("TRACE")
114 return "NOT IMPLEMENTED"
116 def create_socket(socket_name):
117 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
118 sock.bind(socket_name)
125 while '\n' not in chunk:
127 chunk = conn.recv(1024)
128 except (OSError, socket.error), e:
129 if e[0] != errno.EINTR:
131 # Ignore eintr errors
140 msg = ''.join(msg).split('\n')[0]
142 # The message might have arguments that will be appended
143 # as a '|' separated list after the message identifier
145 arg = base64.b64decode(arg).rstrip()
146 return cPickle.loads(arg)
148 dargs = map(decode, msg.split("|"))
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> -H <home_dir> -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("-H", "--homedir", dest="homedir",
173 help = "Home directory where to store results",
174 default = "", type="str")
176 parser.add_option("-v", "--verbose",
177 help="Print debug output",
179 dest="verbose", default=False)
181 (options, args) = parser.parse_args()
183 return (options.socket_name, options.homedir, options.verbose,
186 def run_server(socket_name, homedir = None, level = logging.INFO,
189 # Sets NS_LOG environmental variable for NS debugging
191 os.environ["NS_LOG"] = ns_log
193 ###### ns-3 wrapper instantiation
195 ns3_wrapper = NS3Wrapper(homedir = homedir, loglevel=level)
197 ns3_wrapper.logger.info("STARTING...")
199 # create unix socket to receive instructions
200 sock = create_socket(socket_name)
203 # wait for messages to arrive and process them
207 conn, addr = sock.accept()
211 (msg, args) = recv_msg(conn)
212 except socket.timeout, e:
217 # Ignore - connection lost
220 if msg == NS3WrapperMessage.SHUTDOWN:
224 reply = handle_message(ns3_wrapper, msg, args)
227 err = traceback.format_exc()
228 ns3_wrapper.logger.error(err)
232 send_reply(conn, reply)
236 ns3_wrapper.logger.info("EXITING...")
238 if __name__ == '__main__':
240 (socket_name, homedir, verbose, ns_log) = get_options()
243 FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
244 level = logging.DEBUG if verbose else logging.INFO
246 logging.basicConfig(format = FORMAT, level = level)
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)
255 run_server(socket_name, homedir, level, ns_log)